Skip to content
AgileLogics
4 min read

if Statements

Prerequisites: Booleans and comparisons

if runs code only when a condition is true. Blocks end with end:

function describe(temp)
    if temp > 30
        println("$temp: hot")
    elseif temp > 15
        println("$temp: pleasant")
    else
        println("$temp: cold")
    end
end

describe(35)
describe(20)
describe(3)
35: hot
20: pleasant
3: cold
  • elseif (one word) and else are optional.
  • Indentation is for humans — Julia uses end to close blocks. Four spaces is the standard style.

if is an expression

An if block produces a value — the value of the branch that ran — so you can assign it:

score = 72
grade = if score >= 90
    "A"
elseif score >= 70
    "B"
else
    "C"
end
println(grade)
B

The ternary operator

For a simple two-way choice, condition ? a : b is shorter:

for n in 1:4
    println(n, " is ", iseven(n) ? "even" : "odd")
end
1 is odd
2 is even
3 is odd
4 is even

The spaces around ? and : are required.

Practice

Write a function fizzbuzz(n) that returns "FizzBuzz" if n is divisible by 15, "Fizz" if divisible by 3, "Buzz" if divisible by 5, and otherwise the number as a string. Print it for 1 through 15 on one line.

Show solution
function fizzbuzz(n)
    if n % 15 == 0
        "FizzBuzz"
    elseif n % 3 == 0
        "Fizz"
    elseif n % 5 == 0
        "Buzz"
    else
        string(n)
    end
end

println(join([fizzbuzz(n) for n in 1:15], " "))
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz