PYTHON CORE · LESSON 25

Stop the loop

Command break · about 12 minutes

Learning with progressRead the summary for free. To save the work, log in to the account.
STEP 1

Getting out before the end

break immediately stops the loop. This is useful when the right thing has already been found.

for n in range(5):
    if n == 2:
        break
    print(n)

✦ There will be 0s and 1s.

STEP 2

The retreats show nesting

The line inside the if is shifted even further than the if itself. So Python sees where break will work.

for n in range(4):
    if n == 3:
        break
    print(n)

✦ The number 3 won't appear.

IN-CLASS PRACTICE

Type the code yourself

Dial the stop loop. Watch the two levels of indentation.

for n in range(5):
    if n == 3:
        break
    print(n)
Open the editor for class work
HOMEWORK

Solve it yourself

for loop with n and range(6) output numbers, but stop using break when n becomes 4. Lines 0-3 should appear.

The answer is hidden. Use similar examples from the lesson notes.

Opening up your homework