1.2. Variables and assignments#
A variable is a name that refers to a value
Variable names:
Can contain most unicode characters, but cannot begin with a number
Are case sensitive (e.g.
Tau
is different fromtau
)Should ideally be a good description of what the variable represents
An assignment statement has the form
variable_name = expression
, and it creates a new variable and gives it the value of the evaluated expression
my_number = 1.2 # Assignment
1.2
pi # Pre-defined variable
π = 3.1415926535897...
My_number # Error - was defined without capital M
UndefVarError: `My_number` not defined
δ = 0.001 # Unicode characters allowed (type \delta and press tab)
0.001
my_number_2 = (my_number + 1) * δ # Use pre-defined variables in expressions
0.0022
1.2.1. Updating operators#
The following updating operators make it convenient to operate on a variable and assign the result back to the variable:
+= -= *= /= \= ÷= %= ^=
counter = 1 # counter = 1
1
counter += 1 # counter = counter + 1
2
counter ^= 4 # counter = counter ^ 4
16
angle = 60 # degrees
60
angle *= π / 180 # convert to radians
1.0471975511965976
1.2.2. Numerical literal coefficients#
Julia allows variables to be immediately preceded by a numeric literal, implying multiplication
This can make expressions easier to read, and look more like mathematical notation
x = 3
println(2x^2 - 3x + 1)
println(1.5x^2 - .5x + 1)
println(2(x-1)^2 - 3(x-1) + 1)
10
13.0
3
Numeric literal coefficients have higher precedence than
*
and/
:
println(360 / 2*π) # Left first - equals 180*π
println(360 / 2π) # Right first - equals 180/π
565.4866776461628
57.29577951308232
For exponentiation
^
, numeric literal coefficients behave similarly to unary operators:
println(2^2x) # 2^(2x), not (4)x
println(2x^2) # 2*(x^2), not (2x)^2
64
18
1.2.4. Example of comments#
The comments in this code make it easy to understand exactly what it does
#=
Experiments with spheres
=#
radius1 = 100 # Outer sphere radius
radius2 = 50 # Inner sphere radius
# Compute the volume of each sphere
vol1 = 4π * radius1^3 / 3
vol2 = 4π * radius2^3 / 3
# Compute the volume of a hollow sphere
vol_hollow = vol1 - vol2
3.665191429188092e6
1.2.3. Comments#
Comments start with the
#
symbol, and everything from the#
to the end of the line is ignored by JuliaAlternatively, you can write multi-line comments by wrapping the text inside
#=
and=#
Comments are very important, but should be descriptive. Do not comment on obvious things.
Typical uses of comments:
Start each program (script) with a concise description of what it does
Define each important variable/constant
Top a block of code for a specific task with a concise comment