Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 40 ยท Basics

Control Flow

Learn Julia control flow: if/elseif/else, the ternary operator, short-circuit evaluation, for and while loops, break, continue, ranges and begin blocks.

Control flow decides which code runs and how many times. Julia keeps it simple: blocks are closed with the keyword end instead of braces or indentation, conditions must be real Bool values, and nearly everything is an expression that returns a value. In this lesson you will use if, the ternary operator, short-circuit logic, for and while loops, break and continue, ranges and begin blocks.

Julia code is read-only on this site, with output in comments. Python stand-ins reproduce the loops and range rules.

if, elseif and else

JULIA
x = 15

if x < 10
    println("small")
elseif x < 20
    println("medium")
else
    println("large")
end
# medium

Parentheses around the condition are optional. Indentation is a style choice (four spaces by convention); end is what closes the block.

The condition must evaluate to true or false. Unlike C, Python or JavaScript, Julia has no "truthy" values:

JULIA
if 1
    println("yes")
end
# TypeError: non-boolean (Int64) used in boolean context

if !isempty([1, 2])   # use an explicit test instead
    println("not empty")
end

if is an expression, so it returns the value of the branch that ran:

JULIA
label = if x < 10
    "small"
else
    "big"
end
label   # "big"

Comparison operators chain like in mathematics: 1 < x < 100. Combine conditions with && (and), || (or) and ! (not).

The ternary operator

For short two-way choices there is condition ? value_if_true : value_if_false. The spaces around ? and : are required:

JULIA
x = 7
parity = x % 2 == 0 ? "even" : "odd"   # "odd"
abs_x = x >= 0 ? x : -x                # 7

A related function is ifelse(cond, a, b). It evaluates both a and b before choosing, which is useful for branch-free code in tight numeric loops but wrong if either side has side effects or may throw.

Short-circuit evaluation

&& and || stop as soon as the answer is known:

JULIA
x = 0
x != 0 && println("divide by x")   # skipped: the left side is false
x == 0 || println("x is not 0")    # skipped: the left side is true

Julia programmers use this as a compact "if without else":

JULIA
isfile("data.csv") || error("data.csv is missing")
n > 0 && println("positive")

Use & and | (no doubling) for bitwise operations on integers; they do not short-circuit. They also work element-wise with broadcasting as .& and .|.

for loops

A for loop runs its body once per element of anything iterable. Both in and = work, and the symbol โˆˆ too:

JULIA
for i in 1:3
    println("i = ", i)
end
# i = 1
# i = 2
# i = 3

for fruit in ["apple", "banana"]
    println(uppercase(fruit))
end
# APPLE
# BANANA

for c in "abc"
    print(c, "-")
end
# a-b-c-

Useful helpers: enumerate gives (index, value) pairs, zip walks collections in parallel, and eachindex gives valid indices.

JULIA
names = ["Ada", "Grace", "Linus"]
for (i, name) in enumerate(names)
    println(i, ". ", name)
end
# 1. Ada
# 2. Grace
# 3. Linus

for (n, sq) in zip(1:3, [1, 4, 9])
    println(n, " squared is ", sq)
end

Several loop variables can be combined in one line. This is a single loop over every pair, not two separate loops:

JULIA
for i in 1:2, j in 1:3
    println((i, j))
end
# (1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3), one per line

A break inside this form leaves both levels at once. Use separate nested for blocks when you want break to leave only the inner loop.

A for loop itself returns nothing. If you need to collect results, use a comprehension: [i^2 for i in 1:5] gives [1, 4, 9, 16, 25].

while loops

JULIA
n = 1
while n < 100
    n *= 2
end
n   # 128

while repeats as long as the condition holds. Make sure something inside the loop changes it, or the program runs forever (press Ctrl+C in the REPL to interrupt).

break and continue

break leaves the loop immediately and continue skips to the next iteration:

JULIA
for i in 1:10
    i % 2 == 0 && continue   # skip even numbers
    i > 7 && break           # stop after 7
    println(i)
end
# 1
# 3
# 5
# 7

Here is the idea as Python code you can run. The loop is the same, only the syntax differs.

Python break and continue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Ranges

A range such as 1:5 is a compact object that stores only its start, step and stop, not every value. Both ends are included:

JULIA
collect(1:5)          # [1, 2, 3, 4, 5]
collect(1:2:10)       # [1, 3, 5, 7, 9]    start:step:stop
collect(10:-3:0)      # [10, 7, 4, 1]
collect(5:1)          # Int64[] (empty: the default step is +1)
length(1:2:10)        # 5
sum(1:100)            # 5050
range(0, 1, length=5) # 0.0:0.25:1.0
collect(range(0, 1, length=5))   # [0.0, 0.25, 0.5, 0.75, 1.0]

Use range(start, stop, length=n) (or LinRange) for evenly spaced floats. Floating-point steps like 0.0:0.1:1.0 also work but can accumulate rounding error, so prefer length.

Ranges at a glance

1:5 Start to stop. Both included.
1:2:9 Start, step, stop.
10:-1:1 A negative step counts down.
range(...) Pick a length for floats.

A range never stores its elements, so 1:10^9 costs almost nothing.

1 / 2

Python ranges differ in one important way: they exclude the stop value. This stand-in defines a Julia-style helper so you can compare.

Python Julia-style ranges (analogy)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

begin blocks and compound expressions

begin ... end groups several expressions into one, and its value is the last expression:

JULIA
result = begin
    a = 3
    b = 4
    sqrt(a^2 + b^2)
end
result   # 5.0

You will meet begin mostly where syntax allows only one expression, for example in a one-line function body or in the body of a macro call. A semicolon chain (a = 3; b = 4; a + b) does the same on one line.

for and while bodies create a new local scope, so variables first assigned inside them disappear after the loop, while if and begin blocks do not create one. The precise rules are in Modules and Scope.

A complete example: FizzBuzz

JULIA
for n in 1:15
    if n % 15 == 0
        println("FizzBuzz")
    elseif n % 3 == 0
        println("Fizz")
    elseif n % 5 == 0
        println("Buzz")
    else
        println(n)
    end
end

It prints 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, one per line. The order of the checks matters: the test for 15 must come first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens with if 1 ... end in Julia?

    Julia has no truthy or falsy values. A condition must be true or false, so use an explicit comparison.
  2. 2. What is the value of 3 > 2 ? "a" : "b"?

    The ternary operator returns the first branch when the condition is true.
  3. 3. What does collect(1:2:10) return?

    The syntax is start:step:stop. It starts at 1, adds 2 each time and stops before exceeding 10.
  4. 4. What does x > 0 && println("positive") do when x is -1?

    && short-circuits: the right-hand side is evaluated only when the left side is true.
  5. 5. Which statement about for i in 1:3, j in 1:3 is correct?

    Combining iterators in one for creates a single loop, so break ends the whole thing. Write nested for blocks to break only the inner loop.

Summary

  • Blocks end with end; conditions must be Bool; if returns a value.
  • condition ? a : b is the ternary operator; ifelse evaluates both branches.
  • && and || short-circuit and are often used as one-line conditionals.
  • for x in collection iterates over anything iterable; enumerate, zip and eachindex help.
  • while repeats while a condition holds; break and continue control loops.
  • Ranges start:step:stop include the stop value and are stored lazily; use range(...; length=n) for floats.
  • begin ... end groups expressions and returns the last value.

Next, package your logic into reusable pieces with Functions.