Skip to content

Mojo Break/Continue

A loop normally runs to the end: every item in the list, or until the condition turns False. Two small statements let you change that from inside the body. break stops the whole loop right away, and continue skips the rest of the current round and moves on to the next one. They work in both for and while loops, exactly as they do in Python.

Say you’re checking a list of temperatures and only care about the first one below zero. Once you’ve found it, there’s no point looking at the rest:

def main():
var temps: List[Int] = [12, 15, -2, 8, -5]
for t in temps:
if t < 0:
print("First frost:", t)
break
print("Checked", t)
print("Done")

Output:

Checked 12
Checked 15
First frost: -2
Done

When t is -2, the if runs, prints the message and hits break. The loop ends on the spot: Checked -2 is never printed, and 8 and -5 are never looked at. The program carries on with the first line after the loop, print("Done").

continue doesn’t end the loop. It ends the current round and jumps back to the top for the next item. It’s handy for “ignore the ones that don’t count”:

def main():
var readings: List[Int] = [4, -1, 7, 0, -3, 5]
var total = 0
for r in readings:
if r <= 0:
continue
total += r
print("Added", r)
print("Total:", total)

Output:

Added 4
Added 7
Added 5
Total: 16

For -1, 0 and -3, the continue runs and the two lines below it are skipped. You could write the same thing with if r > 0: and indent the rest, and for two lines that’s fine. continue pays off when the loop body is long, because it keeps the main code from being pushed further and further to the right.

break and continue work the same way in a while loop. while True: with a break is a common pattern when the stopping point is in the middle of the body:

def main():
var n = 50
while True:
n += 1
if n % 7 == 0:
break
print("First multiple of 7 after 50:", n)

Output:

First multiple of 7 after 50: 56

With continue in a while loop, be careful where you update the counter. This version counts up first, so continue can’t skip the update:

def main():
var n = 0
while n < 10:
n += 1
if n % 3 != 0:
continue
print(n, "is a multiple of 3")

Output:

3 is a multiple of 3
6 is a multiple of 3
9 is a multiple of 3

Did the search find anything? for ... else

Section titled “Did the search find anything? for ... else”

A very common job: look through a list for something and do one thing if you found it and another if you didn’t. You could use a found variable:

def main():
var names: List[String] = ["Ana", "Ben", "Cleo"]
var found = False
for name in names:
if name == "Dan":
found = True
break
if not found:
print("Dan is not on the list")

Output:

Dan is not on the list

Mojo also has a shorter way, borrowed from Python: a loop can have an else block. The else runs when the loop finishes normally, after the last item, and is skipped when the loop ends with break:

def main():
var names: List[String] = ["Ana", "Ben", "Cleo"]
for name in names:
if name == "Dan":
print("Found Dan")
break
else:
print("Dan is not on the list")
for name in names:
if name == "Ben":
print("Found Ben")
break
else:
print("Ben is not on the list")

Output:

Dan is not on the list
Found Ben

The first loop never hits break, so its else runs. The second loop breaks at Ben, so its else is skipped.

while loops can have an else too, with the same rule: it runs when the condition turns False, but not after a break. The compound statements reference spells out the rules for both.

In nested loops, break and continue only affect the loop they’re directly inside:

def main():
for row in range(3):
for col in range(3):
if col > row:
break
print(row, col)

Output:

0 0
1 0
1 1
2 0
2 1
2 2

Each break stops the inner col loop, but the outer row loop keeps going with the next row.

Mojo has no labelled break (like break outer in Java or Rust) that jumps out of several loops at once. When you want to stop everything, you have two options.

Option 1: a flag. Set a variable, break out of the inner loop, and check the variable in the outer one:

def main():
var seats: List[List[String]] = [["A1", "A2", "A3"], ["B1", "B2", "B3"]]
var found = False
for row in seats:
for seat in row:
print("Checking", seat)
if seat == "B2":
found = True
break
if found:
break
print("Found it" if found else "Not found")

Output:

Checking A1
Checking A2
Checking A3
Checking B1
Checking B2
Found it

seats is a list of lists: each row is its own List[String]. The inner break leaves the row, and the if found: break right after it leaves the outer loop too.

Option 2: a function with return. Put the loops in their own function. return leaves the function, and with it every loop inside:

def has_pair(nums: List[Int], target: Int) -> Bool:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
print("Found", nums[i], "+", nums[j])
return True
return False
def main():
var nums: List[Int] = [3, 8, 4, 6]
print(has_pair(nums, 10))
print(has_pair(nums, 20))

Output:

Found 4 + 6
True
False

This is often the cleanest choice, and the function gets a name that says what the loops are for. You’ll learn functions properly in a couple of lessons.

break and continue only make sense inside a loop. Anywhere else, Mojo refuses to build the program:

def main():
var stock = 0
if stock == 0:
print("Sold out")
break
hello.mojo:5:9: error: 'break' is not inside a loop
break
^
mojo: error: failed to run the pass manager

To stop a function early from outside a loop, use return instead. The Mojo manual’s control flow page has more short examples of break and continue in for loops.

Given var words: List[String] = ["sun", "tree", "mountain", "sky", "waterfall"], print the first word with more than 5 letters and stop looking. It should print First long word: mountain.

Hint: len(w.codepoints()) gives the number of characters in a String (len(w) on its own doesn’t work for strings).

Show solution
def main():
var words: List[String] = ["sun", "tree", "mountain", "sky", "waterfall"]
for w in words:
if len(w.codepoints()) > 5:
print("First long word:", w)
break

Output:

First long word: mountain

break stops the loop at mountain, so waterfall, which is also long, is never checked.

From var readings: List[Int] = [3, -2, 0, 9, -7, 4], count and add up only the numbers above zero, using continue. Print 3 readings, total 16.

Hint: continue when r <= 0, then update both counters below it.

Show solution
def main():
var readings: List[Int] = [3, -2, 0, 9, -7, 4]
var count = 0
var total = 0
for r in readings:
if r <= 0:
continue
count += 1
total += r
print(count, "readings, total", total)

Output:

3 readings, total 16

The three non-positive readings hit continue and skip both updates. 3 + 9 + 4 is 16.

A prime number can only be divided evenly by 1 and itself. Check whether var x = 91 is prime by trying every divisor from 2 to x - 1. Print 91 is not prime, it divides by 7, or 91 is prime if no divisor works. Use for ... else, without a found variable.

Hint: break as soon as x % d == 0. The else then only runs when no divisor was found.

Show solution
def main():
var x = 91
for d in range(2, x):
if x % d == 0:
print(x, "is not prime, it divides by", d)
break
else:
print(x, "is prime")

Output:

91 is not prime, it divides by 7

91 is 7 × 13, so the loop breaks at d = 7 and the else is skipped. Try x = 97: no divisor works, the loop ends normally and the else prints 97 is prime.

  • break ends the whole loop at once; the program continues after the loop.
  • continue skips the rest of the current round and goes on with the next one.
  • In a while loop, update the counter before any continue, or the loop may never end.
  • A loop’s else block runs when the loop ends normally and is skipped after break. Read it as “no break”.
  • break and continue only affect the innermost loop. Mojo has no labelled break: use a flag or return from a function.
  • break outside a loop is a compile error: 'break' is not inside a loop.

Next up: match, choosing between many cases in a tidier way than a long if/elif chain.

Quick check

1. What does continue do inside a for loop?
2. A for loop with an else block finds what it is looking for and runs break. Does the else run?
3. You have a loop inside a loop. The inner loop runs break. What happens?
4. Why can while n < 10: with continue near the top and n += 1 at the bottom run forever?