Syllabus Lesson 15 of 239 · Control Flow
Control Flow

break, continue, and the loop else

Two keywords give you finer control inside loops.

break stops the loop immediately, even if more items remain. It is perfect for searching: once you find what you want, you leave.

for n in [4, 9, 7, 2]:
    if n > 5:
        print("found", n)
        break   # stop at the first match (9)

continue skips the rest of the current pass and jumps to the next item. Use it to ignore values you do not care about:

for n in range(1, 6):
    if n % 2 == 0:
        continue   # skip even numbers
    print(n)       # prints 1, 3, 5

Loops also have an optional else block. It runs only if the loop finished without hitting break. This is the clean way to express "I searched everything and found nothing":

target = 8
for n in [4, 9, 7, 2]:
    if n == target:
        print("found it")
        break
else:
    print("not found")   # runs because no break happened

Read the loop else as "if we never broke out." It pairs naturally with searches and works the same on while loops.

Your turn

Define a function first_negative(numbers) that returns the first negative number in the list using a for loop and break. If there are no negatives, return the string "none" using the loop's else clause. For example first_negative([3, 1, -2, 5]) is -2.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output