Python Basics · Repeating Work · lesson 11 of 12
break and continue
about 10 minutes · free · runs in your browser
Step 1 of 2
Leaving early and skipping ahead
Two keywords change how a loop flows:
breakstops the loop immediately and carries on after itcontinueabandons this pass and jumps to the next one
for n in numbers:
if n < 0:
continue # ignore negatives
if n > 100:
break # stop entirely
print(n)
break is the natural way to write a search: as soon as you have found what you are
looking for, there is no reason to keep going.
Your turn: write first_negative(numbers) returning the first negative number in the
list, or None if there are none. Stop looking as soon as you find one.
You start from this, and edit it in the browser:
def first_negative(numbers):
# Return the first negative number, or None.
pass
Step 2 of 2
Skipping with continue
continue keeps the interesting case unindented, which makes a loop much easier to
read than wrapping the whole body in an if.
for line in lines:
if not line:
continue
process(line)
Your turn: write sum_positive(numbers) adding up only the numbers greater than
zero, skipping the rest with continue.
You start from this, and edit it in the browser:
def sum_positive(numbers):
# Add up only the positive numbers.
pass