CodingNic

Loops and Iteration

Break and Continue

Loops and Iteration 20 min read

Break and Continue

Break and Continue

Sometimes a loop needs extra control.

You may want to stop the loop early, or skip one turn and continue with the next turn.

Python gives us two useful keywords for this:

  • break
  • continue

What Is Break?

break stops the loop immediately.

Python leaves the loop and moves to the next line after it.

python
for number in range(1, 6):
    if number == 4:
        break
    print(number)

Output

text
1
2
3

The loop stops when the number becomes 4.

What Is Continue?

continue skips the current turn.

The loop does not stop. It moves to the next turn.

python
for number in range(1, 6):
    if number == 3:
        continue
    print(number)

Output

text
1
2
4
5

The number 3 is skipped.

How They Are Different

  • break ends the whole loop
  • continue skips one turn only

Break in a While Loop

python
count = 1

while True:
    print(count)
    if count == 3:
        break
    count += 1

Continue in a While Loop

python
count = 0

while count < 5:
    count += 1

    if count == 2:
        continue

    print(count)

Code Along

python
for letter in "Python":
    if letter == "h":
        break
    print(letter)

Mini Challenge

Build a skip number program.

Steps:

  • Use a loop to print numbers from 1 to 5
  • Skip number 3
  • Print all other numbers

Real World Use Case

Programs use break to stop searches when something is found, and continue to skip invalid data and keep working.

Quiz

  1. What does break do?
  2. What does continue do?
  3. Does continue stop the loop?
  4. Which one ends the whole loop?

Assignment

Create a program that prints numbers from 1 to 10 but stops when it reaches 6.

Summary

You learned how break stops a loop and how continue skips one turn and keeps the loop running.