Code / Python for Beginners / Unit 3: Loops

break and continue break और continue

Lesson 9 of 14 · about 12 minutes · Stop a loop early; skip a round.

⚡ 0 XP

Step 1 of 1

Stop early with break

repeat× 4

Two words change how a loop runs:

  • break stops the loop right now and jumps to the code after it
  • continue skips the rest of this round and starts the next one

To remember whether something happened inside a loop, use a flag: a bool that starts as False and becomes True when it happens. After the loop, check the flag.

Example
for n in range(1, 10):
    if n == 3:
        continue   # skip 3
    if n == 6:
        break      # stop at 6
    print(n)

🎯 Challenge: Guess the number +25 XP

The secret number is 7 and the player gets 3 guesses. In the loop: if the guess is right, print Correct! 🎉, set found = True and break (so the program stops asking). If wrong, print Try again. After the loop, if nothing was found, print Out of guesses! It was 7.

Try twice to unlock the solution (0/2)

main.pyCtrl ⏎
Output

What your program prints appears here.

Checklist

Press Run to check your code.

  • First guess right: stops asking
  • Wrong, then right
  • Three wrong guesses reveal the number
Lesson notes (text version)

1. Stop early with break

Two words change how a loop runs:

  • break stops the loop right now and jumps to the code after it
  • continue skips the rest of this round and starts the next one

To remember whether something happened inside a loop, use a flag: a bool that starts as False and becomes True when it happens. After the loop, check the flag.

                for n in range(1, 10):
    if n == 3:
        continue   # skip 3
    if n == 6:
        break      # stop at 6
    print(n)
              

Challenge: Guess the number

The secret number is 7 and the player gets 3 guesses. In the loop: if the guess is right, print Correct! 🎉, set found = True and break (so the program stops asking). If wrong, print Try again. After the loop, if nothing was found, print Out of guesses! It was 7.

Search by task, format or tool name.