Learn Python / While Loops

While Loops

A for loop repeats once for each item in a collection. Sometimes you don't know in advance how many times to repeat. You just want to keep going while something is true: until the user types the right password, until the money runs out, until the game ends. That's what a while loop does.

The while loop

A while loop checks a condition. If it's True, the body runs, and then Python checks the condition again. Once the condition is False, the loop ends.

count = 1

while count <= 5:
    print("Count is", count)
    count += 1

print("Loop finished")
Output

Step by step, Python does this:

Check count <= 5 Prints count becomes
1 <= 5 is True Count is 1 2
2 <= 5 is True Count is 2 3
3 <= 5 is True Count is 3 4
4 <= 5 is True Count is 4 5
5 <= 5 is True Count is 5 6
6 <= 5 is False (loop ends)

Three things make this work:

  1. A variable is set before the loop (count = 1).
  2. The condition uses it (count <= 5).
  3. The body changes it (count += 1).

Infinite loops

If the condition never becomes False, the loop runs forever. That's called an infinite loop, and it's the most common while bug. Forgetting the count += 1 line above would cause one.

Try this one, and press Stop to end it:

n = 1
while n > 0:
    n += 1
Output

Tip: If your program seems frozen, check that something inside the loop changes the condition.

Looping until something happens

while shines when the number of repeats depends on the data. How many years does it take for savings to double at 5% interest?

balance = 1000
years = 0

while balance < 2000:
    balance *= 1.05
    years += 1

print(f"It takes {years} years to reach {balance:.2f}")
Output

Asking until the input is valid

Keep asking until the user gives an acceptable answer. Run this and try typing a number outside the range first:

rating = int(input("Rate us from 1 to 5: "))

while rating < 1 or rating > 5:
    print("Please enter a number between 1 and 5.")
    rating = int(input("Rate us from 1 to 5: "))

print(f"Thanks for rating us {rating}!")
Output

while True with break

Another common style is an endless while True: loop that you leave with break when you're done. It's handy when the exit check belongs in the middle of the loop:

total = 0

while True:
    entry = input("Enter a number (or 'done'): ")
    if entry == "done":
        break
    total += float(entry)

print(f"Total: {total}")
Output

continue

continue skips the rest of the current pass and jumps back to the condition:

n = 0

while n < 10:
    n += 1
    if n % 2 == 0:
        continue      # skip even numbers
    print(n, end=" ")
Output
Going deeper: while ... else optional

Like a for loop, a while loop can have an else block. It runs when the condition becomes false, but not when the loop is left with break. That's handy for "you have a limited number of tries" situations:

attempts = 0

while attempts < 3:
    password = input("Password: ")
    if password == "python":
        print("Welcome!")
        break
    attempts += 1
else:
    print("Too many attempts. Locked out.")
Output

Run it twice: once typing python, and once getting it wrong three times. Only the second run reaches the else block.

A while True: loop can only end with break, so an else block after it would never run.

A guessing game

Here's everything together. The random module picks a secret number:

import random

secret = random.randint(1, 20)
guesses = 0

print("I'm thinking of a number between 1 and 20.")

while True:
    guess = int(input("Your guess: "))
    guesses += 1

    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")
    else:
        print(f"Correct! You got it in {guesses} guesses.")
        break
Output

for or while?

Use for when… Use while when…
you're going through every item of a collection you repeat until a condition changes
you know how many times to repeat (range) you don't know how many repeats you'll need
e.g. print each name e.g. keep asking until the answer is valid

If you can write it as a for loop, that's usually simpler and safer, because a for loop can't run forever by accident.

Exercises

Exercise 1: Powers of two

Use a while loop to print every power of 2 that is less than 1000: 1 2 4 8 ... 512.

power = 1
Output

Exercise 2: Digit sum

Add up the digits of number using a while loop, % 10 (last digit) and // 10 (remove the last digit). For 4719 it should print 21.

number = 4719
total = 0
Output

Exercise 3: Password check

Keep asking for the password until the user types python123, then print Access granted. Allow at most 3 attempts. After 3 wrong attempts, print Account locked.

attempts = 0
Output

The else on a loop runs only if the loop finished without hitting break. It's a neat trick for "searched everything, didn't find it" situations.

Exercise 4: Fix the infinite loop

This loop is meant to print 10, 8, 6, 4, 2, but it never stops. Press Run, then Stop, and fix it.

n = 10
while n != 0:
    print(n)
    n -= 3
Output

Summary

  • while condition: repeats the body as long as the condition is true.
  • Something inside the loop must eventually make the condition false, or the loop runs forever.
  • while is ideal when you don't know the number of repeats in advance, such as input validation or games.
  • while True: with break exits from the middle of a loop. continue skips to the next pass.
  • Prefer for when you're going through a collection or a fixed range.