a = 21
if a > 20
b = 20
elseif a > 10
b = 10
else
b = 1
end
b20
if, elseif, elseIn 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
b20
&&, ||a, b = 10, 20(10, 20)
&& can replace a simple if <condition> <statement> end statement:
if a > 5 println("a is greater than 5") enda 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")
enda is not greater than 20
a > 20 || println("a is not greater than 20")a is not greater than 20
for loopsfor i = 2:3
println("I would like ", i, " croissants, please, thank you!")
endI 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!")
endI would like 3 cappuccinos, please, thank you!
I would like 4 cappuccinos, please, thank you!
enumerate()a = [3, 5, 7, 9]
for (i, val) in enumerate(a)
println("i is ", i, ", val is ", val)
endi is 1, val is 3
i is 2, val is 5
i is 3, val is 7
i is 4, val is 9
while loopsa = 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