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 times to loop — only when to stop.

Basic while loop

count: int = 1

while count <= 5:
    print(count)
    count += 1
1
2
3
4
5

The loop checks count <= 5 before each pass. As long as it’s True, the body runs. When count becomes 6, the condition is False and the loop ends.

When to use while

Use while when the exit condition matters more than the number of iterations:

  • Reading lines until you hit an empty one
  • Retrying an action until it succeeds
  • Asking the user for input until they type something valid

A small example — keep asking until the user types a number:

text: str = ""

while not text.isdigit():
    text = input("Enter a positive whole number: ")

number: int = int(text)
print(f"You entered: {number}")

str.isdigit() returns True only if the string is made entirely of digits. The loop keeps asking until that’s the case.

The infinite loop

If the condition is always true, the loop runs forever. This is a real bug if it happens by accident:

count: int = 1
while count <= 5:
    print(count)
    # forgot to increment count!

This prints 1 forever. To stop a runaway program in the terminal, press Ctrl+C.

Sometimes you want an “intentional” infinite loop and break out from inside:

while True:
    user_input: str = input("Command (type 'quit' to exit): ")
    if user_input == "quit":
        break
    print(f"You said: {user_input}")

while True: reads as “loop forever”. The break statement (next lesson) jumps out when needed.

while vs for

Most of the time, for is the right choice:

# clumsy
i: int = 0
while i < len(items):
    print(items[i])
    i += 1

# Pythonic
for item in items:
    print(item)

If you’re tempted to write a while loop that walks through a known collection by index, you almost always want for ... in ... instead.

The cases where while is the right tool:

  • You’re waiting for an external condition (user input, network response, file change)
  • You don’t know how many iterations are needed
  • You’re implementing a search or convergence loop (common in ML — “iterate until error is small enough”)

A convergence example

A toy “guess the number” game, written with while:

import random

target: int = random.randint(1, 100)
guess: int = -1
tries: int = 0

while guess != target:
    guess = int(input("Guess a number 1-100: "))
    tries += 1

    if guess < target:
        print("Too low.")
    elif guess > target:
        print("Too high.")

print(f"Got it in {tries} tries!")

We use while guess != target: because we don’t know how many guesses the player will need.

while/else

Like for loops (next lesson), while loops have an optional else clause that runs if the loop finishes without hitting break. We’ll cover this pattern in the break/continue/pass lesson.

What’s next

You now have both loop types. Next, the three statements that change loop behaviour from inside: break, continue, pass.

Toggle theme (T)