RizTech Academy logo
RizTech Academy
Control FlowLesson 5 of 615 min

break, continue and loop else

Two keywords for interrupting a loop, and one loop feature so obscure that most working Python developers have never knowingly used it — but which is genuinely the right tool for one specific job.

break

break leaves the loop immediately. Not the current pass — the whole loop.

for number in range(1, 11):
    if number == 5:
        break
    print(number)

print("Done")
1
2
3
4
Done

The loop had seven more numbers to go and abandoned them.

The main use is searching: once you have found the thing, there is no reason to keep looking.

names = ["priya", "arjun", "sneha", "rahul"]
target = "sneha"

for name in names:
    if name == target:
        print(f"Found {target}")
        break

On a list of four this saves nothing. On a list of four million, stopping at the match rather than checking every remaining entry is the whole difference.

continue

continue skips the rest of the current pass and goes straight to the next one. The loop carries on.

for number in range(1, 11):
    if number % 2 == 0:
        continue
    print(number)
1
3
5
7
9

When number is even, continue fires and print is skipped.

It is most useful for filtering out the cases you do not want to deal with, so the real work is not buried inside an if:

lines = ["  ", "apple", "", "banana", "   ", "mango"]

for line in lines:
    if not line.strip():
        continue
    print(line.strip().title())
Apple
Banana
Mango

Compare the alternative:

for line in lines:
    if line.strip():
        print(line.strip().title())

Both work. With one condition the second is arguably cleaner. With four conditions to reject, continue keeps the main body flat instead of pushing it further and further right. That is the same "handle the awkward cases first" idea from the if lesson, applied to loops.

break only escapes one loop

This catches everyone once:

for i in range(3):
    for j in range(3):
        if j == 1:
            break
        print(i, j)
0 0
1 0
2 0

The break ends the inner loop only. The outer loop starts its next pass and the inner loop begins again from scratch.

To leave both, the clearest approach is a flag:

found = False

for i in range(3):
    for j in range(3):
        if grid[i][j] == target:
            found = True
            break
    if found:
        break

It is a bit clunky. Python has no break 2 — the language deliberately does not offer one. Once you have functions, the tidy answer is to put the nested loops in a function and return, which leaves everything at once. That is module 5.

The else on a loop

Here is the obscure one. A for or while loop can have an else, and it runs only if the loop finished without hitting a break.

names = ["priya", "arjun", "sneha"]
target = "rahul"

for name in names:
    if name == target:
        print(f"Found {target}")
        break
else:
    print(f"{target} is not in the list")
rahul is not in the list

The else belongs to the for, not to the if — note that it lines up with for, not with if.

It is genuinely useful for exactly this: "search, and do something if you never found it." Without it you need a flag:

found = False
for name in names:
    if name == target:
        found = True
        break

if not found:
    print(f"{target} is not in the list")

Four extra lines to express the same idea.

Be honest about the trade-off. for/else reads as "otherwise" to most people, and "otherwise" is not what it means — it means "if no break". Plenty of experienced developers misread it, and some teams ban it for that reason. It is worth knowing because you will meet it in other people's code, and worth using only where the search-and-not-found shape is obvious. If you do use it, a short comment costs nothing.

A clearer example, checking for a prime:

number = 29

for divisor in range(2, int(number ** 0.5) + 1):
    if number % divisor == 0:
        print(f"{number} is not prime")
        break
else:
    print(f"{number} is prime")
29 is prime

break and continue in while loops

They work identically:

while True:
    command = input("> ").strip().lower()

    if command == "":
        continue
    if command == "quit":
        break

    print(f"You said: {command}")

print("Goodbye.")

while True with break as the exit is the standard shape for a loop whose ending condition is easiest to express in the middle rather than at the top.

A caution

break and continue are easy to overuse. A loop with four breaks and three continues scattered through forty lines is genuinely hard to follow, because understanding it means tracing every escape route.

A reasonable rule: one break is usually fine, two deserves a second look, and three means the loop is doing too much and wants splitting up.

Practice

  1. Loop through range(1, 101) and stop at the first number divisible by both 7 and 13. Print it.
  2. Print every number from 1 to 50 that is not divisible by 3, using continue.
  3. Given a list of mixed values like ["12", "abc", "7", "", "30"], loop through, skip anything that is not a number with continue, and total the rest.
  4. Write a search over a list of names that prints "found" or "not in the list", first with a flag, then with for/else. Decide which you would rather maintain.
  5. Write the prime check above, then test it with 2, 9, 17, 25 and 97. The number 2 is the one most implementations get wrong.
  6. Write nested loops over a 3 x 3 grid searching for a value, and get the break to leave both loops. Notice how awkward it is — that awkwardness is the reason functions exist.
  7. Build the command loop above and add a help command listing the others.

Next: putting all of it together in a real, playable program.

Stuck on this lesson?

Being stuck is part of it — but being stuck alone for three days is not. Our internship programme pairs this curriculum with code review and one-to-one help from working developers, and it is free.

About the internship