1. Stop early with break
Two words change how a loop runs:
breakstops the loop right now and jumps to the code after itcontinueskips 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.