Zoom Control flow
Last updated: January 12, 2023
Table of contents
Conditional statements
Conditional statements allow to run instructions based on predicates.
Different set of instructions will be executed depending on whether the predicates return true
or false
.
Here are a few examples of predicates:
occursin("that", "this and that")
4 < 3
a == b
a != b
2 in 1:3
3 <= 4 && 4 > 5
3 <= 4 || 4 > 5
Note that Julia possesses an inexact equality comparator which is useful to compare floating-point numbers despite computer rounding.
The function isapprox
or the equivalent binary operator โ
can be used:
0.1 + 0.2 == 0.3
false
0.1 + 0.2 โ 0.3
true
The negatives are the function !isapprox
and โ
.
If statements
if <predicate>
<some action>
end
- If the predicate evaluates to
true
, the body of the if statement gets evaluated, - If the predicate evaluates to
false
, nothing happens.
Example:
function testsign1(x)
if x >= 0
println("x is positive")
end
end
testsign1 (generic function with 1 method)
testsign1(3)
x is positive
testsign1(0)
x is positive
testsign1(-2)
If else statements
if <predicate>
<some action>
else
<some other action>
end
- If the predicate evaluates to
true
,<some action>
is done, - If the predicate evaluates to
false
,<some other action>
is done.
Example:
function testsign2(x)
if x >= 0
println("x is positive")
else
println("x is negative")
end
end
testsign2 (generic function with 1 method)
testsign2(3)
x is positive
testsign2(0)
x is positive
testsign2(-2)
x is negative
If else statements can be written in a compact format using the ternary operator:
<predicate> ? <some action> : <some other action>
In other words:
<predicate> ? <action if predicate returns true> : <action if predicate returns false>
Example:
function testsign2(x)
x >= 0 ? println("x is positive") : println("x is negative")
end
testsign2(-2)
x is negative
If elseif else statements
if <predicate1>
<do if predicate1 true>
elseif <predicate2>
<do if predicate1 false and predicate2 true>
else
<do if predicate1 and predicate2 false>
end
Example:
function testsign3(x)
if x > 0
println("x is positive")
elseif x == 0
println("x is zero")
else
println("x is negative")
end
end
testsign3 (generic function with 1 method)
testsign3(3)
x is positive
testsign3(0)
x is zero
testsign3(-2)
x is negative
Loops
For loops
For loops run a set of instructions for each element of an iterator:
for name = ["Paul", "Lucie", "Sophie"]
println("Hello $name")
end
Hello Paul
Hello Lucie
Hello Sophie
for i = 1:3, j = 3:5
println(i + j)
end
4
5
6
5
6
7
6
7
8
While loops
While loops run as long as the condition remains true:
i = 0
while i <= 10
println(i)
i += 1
end
0
1
2
3
4
5
6
7
8
9
10