A while loop in Python repeats a block of code for as long as a given condition stays True. Unlike a for loop, which iterates over a known sequence, a while loop is ideal when you don't know in advance how many times you'll need to repeat something — for example, repeating until a user enters valid input, or counting down until a value crosses a threshold.

The loop checks its condition before every iteration. The moment the condition evaluates to False, the loop stops and the program continues with whatever comes after it.

Basic while Loop Syntax

A while loop needs a condition, and almost always something inside the loop body that eventually makes that condition false — otherwise it never stops.

count = 1

while count <= 5:
    print(count)
    count += 1  # without this line, the loop would never end

Output:

1
2
3
4
5

Each time through the loop, Python checks whether count <= 5 is still true. The count += 1 line is what moves the counter forward — forget it, and you've written an infinite loop.

The Infinite Loop Danger

If the condition never becomes False, the loop runs forever (or until you force-stop the program with Ctrl+C). This is one of the most common beginner mistakes with while loops.

# DO NOT RUN THIS — it never stops, because count is never changed
count = 1
while count <= 5:
    print(count)
    # missing: count += 1

A common deliberate exception is while True:, used when you want a loop that only exits via an explicit break statement inside it — useful for things like a menu that keeps prompting the user until they choose "quit".

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

while vs for

As a rule of thumb: reach for a for loop when you're iterating over a known collection or a fixed number of times, and reach for a while loop when you're repeating based on a condition that depends on something changing at runtime — like waiting for valid input, or processing items until a queue is empty.

You can see a counting while loop used as a complete worked example in printing the Fibonacci series, which uses a loop to keep generating terms until the requested count is reached.