Definition
How does a game keep going until you win?
A while loop repeats a block of code as long as its condition stays True, checking the condition before each repeat. break exits the loop immediately, and continue skips the rest of the current repeat and goes back to the condition. A loop whose condition never becomes False runs forever.
In simple words
Use for when you know how many times to repeat. Use while when you repeat until something happens: until the guess is right, until the tank is full, until the user types 'quit'. Always make sure something inside the loop moves it towards stopping.
Why it matters
Chatbots wait for messages until the user leaves, games run until someone wins, and training continues until the error is small enough. All of these are while loops.
How it works
attempts = 0
while attempts < 3:
attempts += 1 # without this line the loop never ends
print("Attempt", attempts)- break: stop the loop now, for example when the answer is found.
- continue: skip this repeat, for example to ignore a blank entry.
- while True: with a break inside is a common pattern for menus and chats.
In code
A number-guessing game. The guesses are listed in advance so it runs the same everywhere; on your computer you could use input().
secret = 7
guesses = [3, 9, 0, 7, 5]
tries = 0
while tries < len(guesses):
guess = guesses[tries]
tries += 1
if guess == 0:
print("0 isn't allowed, skipping")
continue
if guess == secret:
print("Guess", guess, "is right! Tries:", tries)
break
print("Guess", guess, "is", "too low" if guess < secret else "too high")
countdown = 3
while countdown > 0:
print(countdown)
countdown -= 1
print("Lift off!")Output
Guess 3 is too low Guess 9 is too high 0 isn't allowed, skipping Guess 7 is right! Tries: 4 3 2 1 Lift off!
Try it yourself
Predict the output
What does each loop print?
- n starts at 1. While n < 4: print n, then add 1 to n.
- For n in range(5): if n is 3, break; otherwise print n.
- For n in range(5): if n is 2, continue; otherwise print n.
- n starts at 10. While n > 10: print n.
Common mistakes
- Forgetting to change the variable in the condition: an infinite loop.
- Using while when a for loop over a list would be simpler.
- Putting break outside a loop.
Check yourself
Summary
- while repeats as long as its condition is True.
- break exits; continue skips to the next check.
- Always change something that moves the loop towards stopping.
Finished reading?
Sources: W3Schools: Python While Loops