Mojo Loops
Loops execute a block of code repeatedly without you writing the same code multiple times. Mojo provides for loops for iterating a known number of times and while loops for repeating as long as a condition holds true.
Why Loops Exist
Without a loop (tedious): With a loop (efficient): print(1) for i in range(1, 6): print(2) print(i) print(3) print(4) print(5) Both produce: 1 2 3 4 5 The loop version works for any count — even 1,000,000.
The for Loop
A for loop iterates over a sequence of values. Each iteration gives the loop variable the next value from the sequence.
fn main():
for i in range(5):
print(i)
Output:
0 1 2 3 4
Understanding range()
The range() function generates a sequence of integers. It accepts up to three arguments.
range(stop) → 0, 1, 2, ..., stop-1 range(start, stop) → start, start+1, ..., stop-1 range(start, stop, step) → start, start+step, start+2*step, ... < stop
fn main():
# Count from 1 to 5
for n in range(1, 6):
print(n, end=" ") # 1 2 3 4 5
print("")
# Count by 2 (even numbers)
for n in range(0, 10, 2):
print(n, end=" ") # 0 2 4 6 8
print("")
# Count down from 5 to 1
for n in range(5, 0, -1):
print(n, end=" ") # 5 4 3 2 1
print("")
Diagram: range(2, 10, 3)
Start=2, Stop=10, Step=3
Sequence: 2 → 5 → 8 → (11 exceeds 10, stop)
Values produced: 2, 5, 8
----+----+----+----+----+----+----+----+----+----
0 1 2 3 4 5 6 7 8 9 10
↑ ↑ ↑
2 5 8
Accumulation Pattern
A very common loop pattern accumulates a result across all iterations. The result starts at zero and grows with each loop pass.
fn main():
var total = 0
for i in range(1, 6):
total += i
print("Sum of 1 to 5:", total) # 15
Step-by-step: i=1: total = 0 + 1 = 1 i=2: total = 1 + 2 = 3 i=3: total = 3 + 3 = 6 i=4: total = 6 + 4 = 10 i=5: total = 10 + 5 = 15
The while Loop
A while loop repeats as long as its condition remains True. It suits situations where you do not know in advance how many iterations are needed.
fn main():
var countdown = 5
while countdown > 0:
print(countdown)
countdown -= 1
print("Liftoff!")
Output:
5 4 3 2 1 Liftoff!
Execution Flow:
countdown=5 → 5 > 0? True → print 5, countdown=4
countdown=4 → 4 > 0? True → print 4, countdown=3
countdown=3 → 3 > 0? True → print 3, countdown=2
countdown=2 → 2 > 0? True → print 2, countdown=1
countdown=1 → 1 > 0? True → print 1, countdown=0
countdown=0 → 0 > 0? False → exit loop
print("Liftoff!")
Infinite Loops and break
A loop with a condition that never becomes False runs forever. Use break to exit such a loop when a specific condition inside the loop is met.
fn main():
var number = 1
while True: # This condition never becomes False on its own
if number == 5:
break # Exit the loop when number reaches 5
print(number)
number += 1
print("Loop ended at:", number)
Output:
1 2 3 4 Loop ended at: 5
Skipping Iterations with continue
The continue statement skips the rest of the current iteration and jumps to the next one. This lets you filter out certain values without breaking the entire loop.
fn main():
# Print only odd numbers from 1 to 10
for i in range(1, 11):
if i % 2 == 0:
continue # Skip even numbers
print(i, end=" ") # 1 3 5 7 9
Flow with continue: i=1 → odd → print 1 i=2 → even → continue → jump to i=3 i=3 → odd → print 3 i=4 → even → continue → jump to i=5 ...
Nested Loops
Place one loop inside another to iterate over two-dimensional structures. A common example is printing a multiplication table.
fn main():
for row in range(1, 4):
for col in range(1, 4):
print(row * col, end="\t")
print("") # New line after each row
Output:
1 2 3 2 4 6 3 6 9
Execution Pattern: row=1: col=1 (1×1=1), col=2 (1×2=2), col=3 (1×3=3) row=2: col=1 (2×1=2), col=2 (2×2=4), col=3 (2×3=6) row=3: col=1 (3×1=3), col=2 (3×2=6), col=3 (3×3=9)
The else Clause on Loops
Mojo loops support an optional else block that runs only when the loop completes without hitting a break. This provides a clean way to handle "item not found" scenarios.
fn main():
var target = 7
for n in range(1, 6):
if n == target:
print("Found:", target)
break
else:
print(target, "was not found in the range")
Output (because 7 is not in range 1–5):
7 was not found in the range
Key Takeaways
The for loop iterates over sequences from range() or other iterable types. The while loop repeats until its condition becomes False. Use break to exit a loop early and continue to skip the current iteration. Nested loops iterate over two-dimensional data. The loop else block runs when no break was executed, making "not found" logic clean and readable.
