πŸ”
CodingπŸ”¬ Ages 11-13Beginner 12 min read

Python While Loops

Master Python while loops: how a condition controls repetition, updating the loop variable, avoiding infinite loops, break and continue, and input validation. Runnable code, a worked example and a quiz.

Key takeaways

  • A while loop repeats its block as long as its condition stays True
  • Something inside the loop must change the condition, or it never stops
  • An infinite loop happens when the condition is always True β€” a common bug
  • break exits a loop immediately; continue skips to the next repetition

Repeating until something changes

Computers are brilliant at doing the same thing over and over. A loop is how you tell a program to repeat. You may already have met the for loop, which is perfect when you know exactly how many times to repeat. But what about when you don't know? "Keep asking for the password until it's right." "Keep the game running until the player quits." For those, you need a while loop.

A while loop repeats its block as long as a condition stays True. The moment the condition becomes False, the loop ends. This lesson assumes you're comfortable with conditions like x < 10; if not, review conditionals in Python first. For the bigger picture of looping in general, see loops and repeats.

The shape of a while loop

Here is the simplest possible while loop:

count = 1
while count <= 5:
    print(count)
    count = count + 1

print("Done!")

Output:

1
2
3
4
5
Done!

Three pieces make every while loop work. Watch for them:

  1. Setup before the loop: count = 1 gives the loop variable a starting value.
  2. The condition: while count <= 5: is checked before each repetition. While it is True, the block runs again.
  3. The update inside the loop: count = count + 1 changes the variable so the condition will eventually become False.

Let's trace it. count is 1; 1 <= 5 is True, so it prints 1 and bumps count to 2. Then 2, then 3, 4, 5. After printing 5, count becomes 6. Now 6 <= 5 is False, so the loop stops and "Done!" prints.

The danger: infinite loops

The most important rule about while loops:

Something inside the loop must make the condition False β€” eventually β€” or the loop runs forever.

Forget the update line and you get an infinite loop:

count = 1
while count <= 5:
    print(count)
    # oops β€” we never change count!

Because count stays 1 forever, 1 <= 5 is always True, and the program prints 1 endlessly until you force it to stop. If this happens to you, press Ctrl+C in the terminal to interrupt it. Whenever you write a while loop, ask yourself: what changes the condition? If you can't answer, you have a bug.

A shorter way to update: +=

Writing count = count + 1 is so common that Python gives you a shortcut, the augmented assignment operator:

count += 1   # same as count = count + 1
count -= 2   # same as count = count - 2
count *= 3   # same as count = count * 3

We'll use += from here on.

Counting down and counting by steps

A while loop can count in any direction or step. Here's a countdown:

seconds = 5
while seconds > 0:
    print(seconds)
    seconds -= 1
print("Lift off!")

This prints 5, 4, 3, 2, 1, then "Lift off!". The condition seconds > 0 becomes False once seconds reaches 0. You could just as easily step by 2 (seconds -= 2) or count upward by tens.

break: leaving a loop early

Sometimes you want to stop a loop in the middle, before the condition would naturally turn False. The break statement exits the loop immediately:

while True:
    answer = input("Type 'quit' to stop: ")
    if answer == "quit":
        break
    print("You typed:", answer)

print("Goodbye!")

Look closely: while True: is an intentional "forever" loop β€” the condition is always True. It would never stop on its own. But break gives us a controlled exit: when the user types quit, the loop ends and "Goodbye!" prints. This pattern, while True plus break, is a clean way to repeat until some event happens.

continue: skipping one repetition

The continue statement is gentler than break. Instead of leaving the loop, it skips the rest of the current repetition and jumps back to the condition check:

number = 0
while number < 10:
    number += 1
    if number % 2 == 0:      # if number is even
        continue             # skip the print below
    print(number)

This prints only the odd numbers 1, 3, 5, 7, 9. When number is even, continue skips the print and goes straight to the next repetition. The key difference to remember: break ends the whole loop; continue only skips to the next round.

Worked example: input validation

Here's where while loops truly shine β€” making sure the user gives you good input. We'll keep asking for a number between 1 and 10 until they actually type one.

number = 0

while number < 1 or number > 10:
    number = int(input("Pick a number from 1 to 10: "))
    if number < 1 or number > 10:
        print("That's out of range. Try again.")

print(f"Great choice: {number}!")

Step by step:

  1. We start number at 0 β€” deliberately invalid, so the loop runs at least once.
  2. The condition number < 1 or number > 10 is True for any out-of-range value, so the loop keeps going.
  3. Inside, we read a new number. If it's still out of range, we print a warning, and the loop repeats.
  4. As soon as the user enters something from 1 to 10, the condition becomes False and the loop ends.

If the user types 50, then 0, then 7, they see two warnings and finally "Great choice: 7!". This "keep asking until it's valid" pattern is one of the most useful jobs a while loop ever does, and it's hard to do cleanly with a for loop, because you don't know how many tries it'll take.

while vs for: which to choose

A quick rule of thumb:

  • Use a for loop when you know the number of repetitions or are stepping through every item in a list or range.
  • Use a while loop when repetition depends on a condition and you don't know how many times it'll run β€” validating input, running a game until "game over," or waiting for an event.

Try it yourself

Build a small number-guessing game using a while loop:

  • Store a secret number, for example secret = 7.
  • Use a while loop that keeps running until the player guesses correctly.
  • Each time, read a guess with int(input(...)). If it's too high, print "Too high!"; if too low, print "Too low!"; using if / elif / else.
  • When the guess equals secret, print a congratulations message and use break (or let the condition end the loop).
  • Extra challenge: count how many guesses it took with a counter that you += 1 each round, and report it at the end.

Watch carefully that your loop can always end β€” every path should move the player closer to stopping. Once your while loops behave, you've unlocked one of the most powerful tools in programming: repeating exactly as long as needed, no more and no less. πŸ”

Quick quiz

Test yourself and earn XP

When does a while loop stop?

What causes an infinite loop?

What does this print? ``` n = 1 while n <= 3: print(n) n = n + 1 ```

What does the break statement do inside a loop?

How is continue different from break?

FAQ

Use a while loop when you don't know in advance how many times you need to repeat β€” for example, keep asking for a password until it's correct, or keep playing until the user quits. Use a for loop when you're counting through a fixed range or stepping through every item in a list.

You almost certainly wrote an infinite loop: the while condition never became False. Check that something inside the loop actually changes the value the condition depends on, like increasing a counter. To stop a runaway program, press Ctrl+C in the terminal.