Skip to content
Kuza Ndoto Academy

While Loops

Beginner → IntermediateChapter 3 · Page 15 of 564 min readUpdated 15 Nov 2026

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!")
3 2 1 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.

count = 3 count > 0? True print(count) count -= 1 False print("Liftoff!") count count > 0 3True 2True 1True 0False
Figure 1. After each run of the body, the arrow goes back to the condition. The trace on the right shows the condition being checked four times: three True results run the body, and the False result ends the loop.

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")
Week 1 savings: 500 Week 2 savings: 1000 Week 3 savings: 1500 Week 4 savings: 2000 Week 5 savings: 2500 Week 6 savings: 3000 Target reached in 6 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)
Sum of digits: 10

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")
Enter your 4-digit PIN: 12a4 Invalid PIN. Try again. Enter your 4-digit PIN: 123 Invalid PIN. Try again. Enter your 4-digit PIN: 1234 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.")
Guess the number (1-10): 3 Too low Guess the number (1-10): 9 Too high Guess the number (1-10): 7 Correct! You took 3 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.

Common mistake

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 happensYou repeat for each item in a collection
The number of repetitions is unknownThe number of repetitions is known, e.g. range(10)
Example: keep asking until the input is validExample: 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 while when 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.
Up next · Control FlowFor LoopsRepeat code for every item in a sequence.
→

Tip: use the ← and → keys to move between pages.