Julia Syntax & Output
Julia's syntax is designed to be easy to read. There are no semicolons at the end of lines, no braces around blocks, and indentation is only a matter of style: blocks are closed with the keyword end.
x = 10
if x > 5
println("x is large")
end
function double(n)
return 2n
end
println(double(x))x is large
20
Notice 2n: a numeric literal directly in front of a variable means multiplication. This juxtaposition makes formulas look like they do on paper (3x^2 + 2x + 1).
Printing output
| Function | What it does |
|---|---|
println(a, b, ...) |
Prints all arguments with no separator, then a newline |
print(a, b, ...) |
Same, without the newline |
show(x) |
Prints the representation of a value (strings get quotes) |
@show expr |
Prints the expression and its value — handy for debugging |
print("Hello, ")
print("Julia")
println()
println("a", 1, 'b', 2.5)
show("text")
println()
show([1, 2, 3])
println()Hello, Julia
a1b2.5
"text"
[1, 2, 3]
println joins its arguments without spaces, so add " " yourself or use string interpolation with $:
name = "Grace"
age = 36
println(name, " is ", age, " years old")
println("$name is $age years old")
println("Next year: $(age + 1)")
total = 3 * 4
@show total
@show total + 1Grace is 36 years old
Grace is 36 years old
Next year: 37
total = 12
total + 1 = 13
Statements and expressions
In Julia, almost everything is an expression that produces a value. Blocks such as if, begin ... end and function bodies return the value of their last expression.
result = begin
a = 3
b = 4
a * b # the block evaluates to this value
end
println(result)
sign_word = if result > 0 "positive" else "non-positive" end
println(sign_word)
# Several statements on one line need semicolons
p = 1; q = 2; println(p + q)12
positive
3
Case sensitivity and naming
- Julia is case-sensitive:
value,ValueandVALUEare three different names. - By convention, variables and functions use
lowercaseorsnake_case, types and modules useCamelCase. - Functions that modify their arguments end with
!, such aspush!andsort!.
Long expressions
A line continues automatically when the expression is incomplete, for example after an operator or inside parentheses:
total = 1 +
2 +
3
values = [10,
20,
30]
println(total, " ", sum(values))6 60
Note: A newline ends an expression if it is already complete.
x = 1followed by+ 2on the next line gives two separate statements, so put the operator at the end of the line, not the start.
Test yourself
What does println("a", 1, "b") print?
- a 1 b
- a1b
- ("a", 1, "b")
- an error
How are blocks such as if and function closed in Julia?
- With a closing brace
} - With the keyword
end - By returning to the previous indentation
- With a semicolon
If x = 5, what is 3x + 1?
- 16
- 351
- An error: missing
* - 35