← Python from Scratch
Lesson 33 of 78 · 10 XP
break, continue and else in loops
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Sometimes you need to stop a loop early or skip a step.
break — leave the loop immediately:
for n in [3, 8, -1, 5]:
if n < 0:
break # we don't go any further
print(n) # 3, 8
continue — skip the rest of this step and go on to the next one:
for n in range(1, 6):
if n % 2 == 0:
continue
print(n) # 1, 3, 5
A common pattern is an "endless" loop that you leave with break:
while True:
cmd = input()
if cmd == "quit":
break
print("You typed:", cmd)
Loops have an unusual else branch: it runs if the loop finished by itself, without break. It's handy for searching: "went through everything and didn't find it".
Task. The program reads numbers, one per line, until it meets the word stop. Print the sum of all the numbers entered.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.