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.
Stopping early with break
Section titled “Stopping early with break”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 12Checked 15First frost: -2DoneWhen 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").
Skipping a round with continue
Section titled “Skipping a round with continue”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 4Added 7Added 5Total: 16For -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.
In a while loop
Section titled “In a while loop”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: 56With 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 36 is a multiple of 39 is a multiple of 3Did 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 listMojo 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 listFound BenThe 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.
break only leaves the innermost loop
Section titled “break only leaves the innermost loop”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 01 01 12 02 12 2Each 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 A1Checking A2Checking A3Checking B1Checking B2Found itseats 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 + 6TrueFalseThis 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 must be inside a loop
Section titled “break must be inside a loop”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") breakhello.mojo:5:9: error: 'break' is not inside a loop break ^mojo: error: failed to run the pass managerTo 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.
Practice
Section titled “Practice”1. First long word
Section titled “1. First long word”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) breakOutput:
First long word: mountainbreak stops the loop at mountain, so waterfall, which is also long, is never checked.
2. Only the positives
Section titled “2. Only the positives”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 16The three non-positive readings hit continue and skip both updates. 3 + 9 + 4 is 16.
3. Is it prime?
Section titled “3. Is it prime?”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 791 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.
breakends the whole loop at once; the program continues after the loop.continueskips the rest of the current round and goes on with the next one.- In a
whileloop, update the counter before anycontinue, or the loop may never end. - A loop’s
elseblock runs when the loop ends normally and is skipped afterbreak. Read it as “no break”. breakandcontinueonly affect the innermost loop. Mojo has no labelled break: use a flag orreturnfrom a function.breakoutside 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Control flow in the Mojo manual:
break,continueandelseinforandwhileloops. - Break and continue statements: the reference entry for both statements.
- Loops and else clauses: exactly when a loop’s
elseblock runs. - Basics cheat sheet:
breakandcontinuenext to the rest of Mojo’s loop syntax.