8  Control Flow

8.1 Conditional Evalutation: if, elseif, else

In Julia, we use if, elseif, else with no parentheses, no colons:

a = 21

if a > 20
    b = 20
elseif a > 10
    b = 10
else
    b = 1
end

b
20

8.2 Short-circuit evaluation: &&, ||

a, b = 10, 20
(10, 20)

&& can replace a simple if <condition> <statement> end statement:

if a > 5 println("a is greater than 5") end
a is greater than 5
a > 5 && println("a is greater than 5")
a is greater than 5

|| can replace a simple if !<condition> <statement> end statement:

if !(a > 20)
    println("a is not greater than 20")
end
a is not greater than 20
a > 20 || println("a is not greater than 20")
a is not greater than 20

8.3 Loops

8.3.1 for loops

for i = 2:3
    println("I would like ", i, " croissants, please, thank you!")
end
I would like 2 croissants, please, thank you!
I would like 3 croissants, please, thank you!

in also works:

for i in 3:4
    println("I would like ", i, " cappuccinos, please, thank you!")
end
I would like 3 cappuccinos, please, thank you!
I would like 4 cappuccinos, please, thank you!

8.3.2 enumerate()

a = [3, 5, 7, 9]
for (i, val) in enumerate(a)
    println("i is ", i, ", val is ", val)
end
i is 1, val is 3
i is 2, val is 5
i is 3, val is 7
i is 4, val is 9

8.3.3 while loops

a = 5

while a > 1
    println("You still have ", a, " alphas, lose some")
    a -= 1
end

println("OK, you only have ", a, " alpha now, you can go")
You still have 5 alphas, lose some
You still have 4 alphas, lose some
You still have 3 alphas, lose some
You still have 2 alphas, lose some
OK, you only have 1 alpha now, you can go