Python While Break & Continue
break and continue are statements that control a while loop from inside.
Leave early with break
The loop stops when count reaches 4.
count = 1
while count <= 10:
if count == 4:
break
print(count)
count += 1
print("Stopped")Skip one round with continue
The value 3 is skipped, but the loop keeps going.
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count)The while else block
This loop ends by its condition, so else runs.
count = 1
while count <= 3:
print(count)
count += 1
else:
print("Finished normally")Example
secret = 7
tries = 0
while tries < 3:
guess = int(input("Guess a number: "))
tries += 1
if guess == secret:
print("Correct!")
break
print("Try again")
else:
print("Out of guesses")Key points
- Use break to leave the loop right now.
- Use continue to skip to the next iteration.
- break and continue change how a while loop runs its rounds.
- Code after continue in that round does not run.
- The else block on a while loop runs when the condition ends the loop.
- The else block does not run when break ends the loop.
In this example, secret is 7 and tries starts at 0. The typed input for this run is 5, then 7, each on its own line. The loop reads the first guess, which is 5. It adds 1 to tries and prints "Try again". The loop reads the second guess, which is 7. It prints "Correct!" and break leaves the loop. The else block is skipped because break ended the loop. The loop would also end after three tries, so the input cannot run forever.
Note
Loop else is a Python surprise.
Many other languages do not have it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
A while loop ends with break. What happens to its else block?