break, continue and else

Loops, lesson 4 of 5

🔁 Loops, lesson 4 of 5

break, continue and else

Stop a loop early, skip items, and detect when no break happened.

10 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

Two keywords let you steer a loop from inside:

  • break leaves the loop immediately.
  • continue skips the rest of this pass and jumps to the next item.

Both usually sit inside an if.

Example

First frost (break)

The loop stops at -2, so 4, -5 and 11 are never checked. Remove the break and compare.

Example

Skip bad orders (continue)

continue jumps straight to the next order, so total += amount is skipped.

Quiz

What does this print?

while True + break is a popular pattern for "keep going until the user says stop". The loop would run forever, but a break inside ends it.

Example

Cash register

One line per input() call

The prices 4.50, 2.25 and 10 are typed in, then "done" breaks the loop.

Loops can have an else block. It runs only if the loop finished without hitting break. Read it as "if no break".

Example

Is it prime? (for … else)

Try 97, or 2026.

Exercise

Find the magic number

Find the smallest number above 100 that is divisible by both 7 and 9. Loop upwards from 101, store the number in found and break as soon as you find it.

Quiz

What does continue do inside a loop?