Julia If Else
An if statement runs a block of code only when its condition is true. Adding else and elseif lets a program pick between several blocks.
An if block runs only when its condition is true
The age is 20, so the check passes and the line inside prints. The line after the block always runs.
age = 20
if age >= 18
println("Adult")
end
println("Done")Else runs when the condition is false
The score is below 50, so the if block is skipped. The else block runs instead.
score = 42
if score >= 50
println("Pass")
else
println("Try again")
end
println(score)Elseif checks more conditions in order
The mark misses the first two bands and lands in the third. Only that one block runs.
mark = 75
if mark >= 90
println("A")
elseif mark >= 80
println("B")
elseif mark >= 70
println("C")
else
println("Keep going")
endExample
age = 16
member = true
if age >= 18
println("Full price")
elseif member
println("Member discount")
else
println("Regular price")
end
println("Age: $age")Key points
- If block: the code inside runs only when the condition after if is true.
- Condition: a comparison or boolean expression that gives true or false.
- Else block: the code inside runs when the condition is false.
- Elseif: an extra condition checked only when every condition before it was false.
- End: this keyword closes the whole if statement.
- Order: Julia checks the conditions from top to bottom and runs the first block that matches.
In this example, age is 16 and member is true. The first condition fails because 16 is not at least 18. The elseif condition is true, so the program prints the member discount line. The last line prints the age with interpolation.
Note
Unlike some other languages, Julia needs no parentheses around the condition.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
age is 15. An if block checks age >= 18 and prints "Adult", and an else block prints "Child". What prints?