Python break & continue Examples
Short, runnable programs that show python break and continue in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python break and continue lesson.
1Stop at the correct PIN
A search-and-stop: the loop counts the tries and leaves with break the moment a guess matches, so later guesses are never looked at.
attempts = ["1234", "0000", "4821", "9999"]
correct = "4821"
tries = 0
for guess in attempts:
tries += 1
if guess == correct:
print("Unlocked after", tries, "tries")
break
print("Wrong PIN:", guess)Expected outputWrong PIN: 1234
Wrong PIN: 0000
Unlocked after 3 tries
2Cleaning a list with continue
Each age that fails a check is skipped with continue, so only sensible values reach the line that builds valid_ages.
ages = [34, -2, 28, 250, 41, 0, 19]
valid_ages = []
for age in ages:
if age < 1 or age > 120:
print("Ignoring", age)
continue
valid_ages.append(age)
print(valid_ages)Expected outputIgnoring -2
Ignoring 250
Ignoring 0
[34, 28, 41, 19]
3A retry loop with while True
There are two ways out of this loop: success, or too many tries. Each one is a break with its own message. The server replies are simulated with a list.
replies = ["timeout", "timeout", "ok", "ok"]
attempt = 0
while True:
reply = replies[attempt]
attempt += 1
print("Attempt", attempt, "->", reply)
if reply == "ok":
print("Connected!")
break
if attempt == 3:
print("Giving up")
breakExpected outputAttempt 1 -> timeout
Attempt 2 -> timeout
Attempt 3 -> ok
Connected!
4Finding the first free seat in two nested loops
The inner break leaves the row, and the flag-style check if seat: leaves the grid. enumerate(..., start=1) gives human-friendly row and seat numbers.
cinema = [["X", "X", "X"], ["X", "free", "X"], ["free", "X", "X"]]
seat = None
for row_no, row in enumerate(cinema, start=1):
for seat_no, status in enumerate(row, start=1):
if status == "free":
seat = (row_no, seat_no)
break
if seat:
break
print("First free seat (row, seat):", seat)Expected outputFirst free seat (row, seat): (2, 2)
5Skip the bad ratings, stop at three good ones
continue and break can work in the same loop: invalid ratings are skipped, and the loop ends as soon as enough valid ones are collected.
ratings = [5, 0, 4, 11, 3, 5, 2]
valid = []
for rating in ratings:
if rating < 1 or rating > 5:
continue
valid.append(rating)
if len(valid) == 3:
break
print(valid, "average", sum(valid) / len(valid))Expected output[5, 4, 3] average 4.0
Practise next
Python break and continue exercises → Back to the lesson
Python pass Statement examplesPython else on Loops examplesPython Nested Loops examples