Skip to content

Mojo While

A while loop repeats a block of code for as long as a condition stays True. It’s the loop to reach for when you don’t know in advance how many times you’ll go round: keep halving until the number is small enough, keep reading until the list is empty, keep trying until it works. Mojo’s while works the same way as Python’s.

def main():
var count = 3
while count > 0:
print(count)
count -= 1
print("Liftoff!")

Output:

3
2
1
Liftoff!

Here’s what happens, step by step:

Check count > 0 count before What runs
3 > 0 is True 3 print 3, then count becomes 2
2 > 0 is True 2 print 2, then count becomes 1
1 > 0 is True 1 print 1, then count becomes 0
0 > 0 is False 0 the loop ends, Mojo moves on to print("Liftoff!")

The condition is checked before every round, including the first. If it’s False from the start, the body never runs at all.

count -= 1 is short for count = count - 1. Lines like this, which move the loop closer to its end, are the most important part of a while loop.

If nothing in the body ever makes the condition False, the loop runs forever. This is the classic while bug:

def main():
var count = 3
while count > 0:
print(count)
# forgot: count -= 1

This prints 3 over and over, and the program never finishes. If it happens to you, press Ctrl+C in the terminal to stop it. Then check that every path through the loop body changes something the condition depends on.

while shines when the number of rounds depends on the data. Say one bacterium splits in two every hour. How many hours until there are at least 1000?

def main():
var cells = 1
var hours = 0
while cells < 1000:
cells *= 2
hours += 1
print("After", hours, "hours there are", cells, "cells.")

Output:

After 10 hours there are 1024 cells.

You couldn’t easily say “loop 10 times” up front, because 10 is the answer you’re looking for. The loop just keeps going until the condition says stop.

Here’s another one: adding up the digits of a number. n % 10 gives the last digit, and n //= 10 chops it off:

def main():
var n = 4071
var total = 0
while n > 0:
total += n % 10
n //= 10
print("Digit sum:", total)

Output:

Digit sum: 12

Each round takes one digit (1, then 7, then 0, then 4) until n reaches 0.

Some loops need to update several variables together. You can assign two values in one line with a comma, just like in Python. This loop collects the Fibonacci numbers below 100, where each number is the sum of the two before it:

def main():
var a = 0
var b = 1
var fibs: List[Int] = []
while b < 100:
fibs.append(b)
a, b = b, a + b
print(fibs)

Output:

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

a, b = b, a + b works out both values on the right first, using the old a and b, and only then stores them. Without that, you’d need a third, temporary variable. fibs.append(b) adds a value to the end of the list; lists get their own lesson later.

Because an empty list counts as False, while items: means “while there’s anything left”. Combine it with pop, which removes an item and gives it back:

def main():
var chores: List[String] = ["wash", "dry", "fold"]
while chores:
var chore = chores.pop(0)
print("Doing", chore, "with", len(chores), "left")
print("All done.")

Output:

Doing wash with 2 left
Doing dry with 1 left
Doing fold with 0 left
All done.

chores.pop(0) takes the first item off the list. Each round the list gets shorter, so the loop is sure to end.

Sometimes the natural place to decide “stop now” is in the middle of the body, not at the top. Then you can write while True:, which on its own would run forever, and leave with break:

def main():
var total = 0
var day = 0
while True:
day += 1
total += day * 10
if total >= 100:
break
print("Saved", total, "after", day, "days")

Output:

Saved 100 after 4 days

You save 10 on day 1, 20 on day 2 and so on, and the loop stops on the day the total reaches 100. break jumps straight out of the loop, to the first line after it.

Mojo has no do ... while loop (neither does Python). while True: with a break at the end of the body is how you write a loop that always runs at least once. The next lessons cover break and its partner continue in detail.

A while loop can have an else block. It runs once, when the condition turns False, but not if the loop was left with break:

def main():
var attempts = 0
while attempts < 3:
attempts += 1
print("Attempt", attempts, "failed")
else:
print("Giving up after", attempts, "attempts")

Output:

Attempt 1 failed
Attempt 2 failed
Attempt 3 failed
Giving up after 3 attempts

This is the same rule as in Python. It’s most useful together with break, so you’ll see it again in the Break/Continue lesson. The control flow page of the Mojo manual has more while examples, including while case, a form that works with values that might be missing.

Use When
while You loop until something happens, and you don’t know how many rounds that takes.
for You go through a known set of things: the numbers 1 to 10, the items in a list, the characters in a string.

You can write any for loop as a while loop with a counter, but a for loop is shorter and can’t forget to update the counter. That’s the next lesson.

Write a loop that prints 10 8 6 4 2 on separate lines, then Done.

Hint: start at 10 and subtract 2 each round. Think about what the condition should be so that 2 is printed but 0 isn’t.

Show solution
def main():
var n = 10
while n > 0:
print(n)
n -= 2
print("Done")

Output:

10
8
6
4
2
Done

After printing 2, n becomes 0, and 0 > 0 is False, so the loop stops.

Count how many digits the number 907214 has, using a while loop. Print Digits: 6.

Hint: each n //= 10 removes one digit. Count how many times you can do it before n reaches 0.

Show solution
def main():
var n = 907214
var digits = 0
while n > 0:
n //= 10
digits += 1
print("Digits:", digits)

Output:

Digits: 6

907214 becomes 90721, 9072, 907, 90, 9 and finally 0: six rounds. (For n = 0 this prints 0 digits; you’d handle that case with an if before the loop.)

This program should print the powers of 2 below 50 (1 2 4 8 16 32, one per line), but it never stops. Fix it.

def main():
var power = 1
while power < 50:
print(power)
power *= 2

Hint: look closely at the indentation of the last line.

Show solution
def main():
var power = 1
while power < 50:
print(power)
power *= 2

Output:

1
2
4
8
16
32

power *= 2 was outside the loop body, so power stayed 1 forever. Indented under while, it runs every round, and the loop ends once power reaches 64.

  • while condition: repeats its block as long as the condition is True. The condition is checked before each round.
  • Something in the body must move the loop towards its end, or it runs forever (stop it with Ctrl+C).
  • Use while when you don’t know the number of rounds up front.
  • a, b = b, a + b updates two variables at once, using the old values.
  • while items: loops until a list is empty.
  • while True: plus break stops from the middle of the body; Mojo has no do ... while.
  • A while ... else block runs when the condition turns False, but not after a break.

Next up: for loops, the easy way to go through ranges, lists and strings.

Quick check

1. How many times does the body run? var n = 5 then while n < 3: n += 1
2. What is wrong with while x > 0: print(x) if nothing else changes x?
3. When does the else block of a while loop run?
4. Mojo has no do ... while loop. How do you write a loop that always runs at least once?