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.
A basic while loop
Section titled “A basic while loop”def main(): var count = 3 while count > 0: print(count) count -= 1 print("Liftoff!")Output:
321Liftoff!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.
Loops that never end
Section titled “Loops that never end”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 -= 1This 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.
When you don’t know how many rounds
Section titled “When you don’t know how many rounds”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: 12Each round takes one digit (1, then 7, then 0, then 4) until n reaches 0.
Updating two values at once
Section titled “Updating two values at once”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.
Looping until a list is empty
Section titled “Looping until a list is empty”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 leftDoing dry with 1 leftDoing fold with 0 leftAll done.chores.pop(0) takes the first item off the list. Each round the list gets shorter, so the loop is sure to end.
while True and break
Section titled “while True and break”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 daysYou 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.
while with else
Section titled “while with else”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 failedAttempt 2 failedAttempt 3 failedGiving up after 3 attemptsThis 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.
while or for?
Section titled “while or for?”| 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.
Practice
Section titled “Practice”1. Count down by twos
Section titled “1. Count down by twos”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:
108642DoneAfter printing 2, n becomes 0, and 0 > 0 is False, so the loop stops.
2. How many digits?
Section titled “2. How many digits?”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: 6907214 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.)
3. Fix the endless loop
Section titled “3. Fix the endless 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 *= 2Hint: look closely at the indentation of the last line.
Show solution
def main(): var power = 1 while power < 50: print(power) power *= 2Output:
12481632power *= 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 isTrue. 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
whilewhen you don’t know the number of rounds up front. a, b = b, a + bupdates two variables at once, using the old values.while items:loops until a list is empty.while True:plusbreakstops from the middle of the body; Mojo has nodo ... while.- A
while ... elseblock runs when the condition turnsFalse, but not after abreak.
Next up: for loops, the easy way to go through ranges, lists and strings.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Control flow: the
whilestatement: the Mojo manual’s section onwhile,break,continue,elseandwhile case. - While loops in the compound statements reference: the exact rules.
- Loops and else clauses: when a loop’s
elseblock runs and when it doesn’t. Listin the standard library: every method onList, includingappendandpop.