While Loops
A while loop repeats a block of code as long as a condition stays true. Use it when you don't know in advance how many repetitions you need, for example "keep asking until the PIN is valid" or "keep saving until you reach the target".
How a while loop works
Python checks the condition. If it's true, the indented block runs once, then Python goes back and checks the condition again. As soon as the condition is false, the loop ends and the program continues with the next unindented line.
count = 3
while count > 0:
print(count)
count -= 1 # count goes down by 1 each time
print("Liftoff!")
Trace it: count starts at 3, so the block runs and prints 3, then count becomes 2. The same happens for 2 and 1. When count becomes 0, the condition count > 0 is false, so the loop stops. If the condition is false the very first time, the block never runs at all.
Looping until a goal is reached
Here a student saves KES 500 a week in a SACCO until she reaches KES 3,000. The loop works out how many weeks that takes.
savings = 0
week = 0
while savings < 3000:
week += 1
savings += 500
print("Week", week, "savings:", savings)
print("Target reached in", week, "weeks")
Every loop like this has three parts: a variable set up before the loop, a condition that tests it, and an update inside the loop that moves it towards making the condition false.
Working with numbers you don't know in advance
This loop adds up the digits of a number. The number of digits isn't fixed, so while is a natural fit: keep going until no digits are left.
number = 2026
total = 0
while number > 0:
total += number % 10 # take the last digit
number //= 10 # remove the last digit
print("Sum of digits:", total)
number % 10 gives the last digit (6, then 2, then 0, then 2) and number //= 10 drops it (2026 → 202 → 20 → 2 → 0). The digits add up to 6 + 2 + 0 + 2 = 10.
Validating user input
A very common use of while is to keep asking until the user types something acceptable. The output below is a sample run.
pin = input("Enter your 4-digit PIN: ")
while len(pin) != 4 or not pin.isdigit():
print("Invalid PIN. Try again.")
pin = input("Enter your 4-digit PIN: ")
print("PIN accepted")
A guessing game
secret = 7
guess = 0
attempts = 0
while guess != secret:
guess = int(input("Guess the number (1-10): "))
attempts += 1
if guess < secret:
print("Too low")
elif guess > secret:
print("Too high")
print(f"Correct! You took {attempts} attempts.")
We set guess = 0 before the loop so the condition has something to test on the first check. In a real game the secret would be random; the standard library page shows how.
Infinite loops
If the condition never becomes false, the loop runs forever. This is called an infinite loop.
count = 1
while count <= 5:
print(count)
# forgot: count += 1
This prints 1 again and again without stopping. To stop a runaway program, click in the terminal and press Ctrl+C; Python stops with a KeyboardInterrupt.
Forgetting the update step, or updating the wrong variable, is the classic cause of infinite loops. Before running a while loop, ask yourself: "What line inside this loop moves me closer to stopping?"
Sometimes an infinite loop is deliberate. while True: runs forever until a break statement inside it ends the loop. Menus and games are often built this way, as you'll see on Break, Continue & Pass.
while or for?
| Use while when… | Use for when… |
|---|---|
| You repeat until something happens | You repeat for each item in a collection |
| The number of repetitions is unknown | The number of repetitions is known, e.g. range(10) |
| Example: keep asking until the input is valid | Example: print every name in a class list |
The For Loops page covers the other kind of loop.
Key points
while condition:repeats its block as long as the condition is true.- Set up a variable before the loop and update it inside, so the condition eventually becomes false.
- Use
whilewhen you don't know in advance how many repetitions are needed. - An infinite loop never ends; stop it with Ctrl+C, and check your update step.
Tip: use the ← and → keys to move between pages.
