Not every repetition in code has a known number of steps ahead of time. Sometimes you just need to keep going "while" something is true — waiting for valid input, running a game loop, retrying until something succeeds. That's what the python while loop is for, and it comes with its own set of patterns and pitfalls worth understanding well.
Introduction: What Is a while Loop?
A while loop repeats a block of code for as long as a condition remains True. Once the condition becomes False, the loop stops.
count = 0
while count < 5:
print(count)
count += 1
# 0 1 2 3 4while vs. for: the key difference
The earlier article in this series covered for loops, which iterate over a known collection — a list, a string, a range — a fixed, predictable number of times. while loops are for a different situation entirely: repeating something an unknown number of times, based on a condition that depends on what happens during the loop itself. You don't know in advance how many times a while loop will run — it depends entirely on when the condition eventually becomes False.
Basic syntax
while condition:
# runs repeatedly as long as condition is TrueA simple countdown example
count = 5
while count > 0:
print(count)
count -= 1
print("Liftoff!")
# 5
# 4
# 3
# 2
# 1
# Liftoff!Avoiding Infinite Loops
Why the loop variable must change
This is the single most important habit to build with while loops: something inside the loop body needs to actually change the condition's outcome, or the loop will run forever. Forgetting this is an extremely common beginner mistake:
# DON'T DO THIS — count never changes, so the condition stays True forever
count = 0
while count < 5:
print(count)
# forgot to increment count — this is a python infinite loopIf you accidentally run something like this, your program will appear to hang, endlessly printing 0 forever, and you'll need to manually interrupt it (usually Ctrl+C in a terminal).
Intentional infinite loops
That said, an infinite loop isn't always a mistake — while True: is a common, entirely valid pattern for situations where you genuinely want the loop to keep running until something inside the loop explicitly decides to stop it:
while True:
# runs forever, until something inside explicitly breaks out
passThis shows up constantly in real programs: game loops that keep running until the player quits, servers that keep listening for connections, or programs that keep prompting for input until it's valid. The key difference from an accidental infinite loop is intent — you're deliberately choosing True as the condition, with a clear plan for exiting from inside.
Safely exiting an intentional infinite loop
The standard way to exit a while True: loop is with break, covered in detail next:
while True:
resp input("Type 'quit' to exit: ")
if resp= "quit":
breakControlling the Loop: break and continue
break: exit immediately
break stops the loop entirely, regardless of what the loop's condition currently evaluates to:
number = 0
while number < 100:
if number == 5:
break
print(number)
number += 1
# 0 1 2 3 4Even though the condition number < 100 is still True when the loop exits, break overrides it and stops the loop immediately once number reaches 5.
continue: skip to the next check
continue skips the rest of the current iteration's code and jumps straight back to re-checking the loop's condition:
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue
print(number)
# 1 3 5 7 9Here, whenever number is even, continue skips the print() line for that iteration entirely — but the loop keeps running, incrementing and re-checking on the next pass.
A word of caution with continue in while loops specifically: make sure whatever needs to change for the condition to eventually become False happens before the continue line, not after — otherwise you can accidentally create the exact infinite loop covered in the previous section, since continue skips everything below it on that pass.
The else Clause on while Loops
What it does
Like for loops, while loops support an else clause — and it behaves the same way: the else block runs only if the loop finished naturally, meaning the condition eventually became False on its own, rather than the loop being cut short with a break.
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop finished normally")
# 0
# 1
# 2
# Loop finished normallyIf a break had interrupted the loop instead, the else block would be skipped entirely.
Why this is useful
This construct genuinely earns its place for a specific kind of logic: "keep trying something; if you eventually find or achieve what you were looking for, break out and handle that case; but if you run out of chances without success, do something else" — all without needing a separate flag variable to track which outcome occurred.
Practical example: a number-guessing game
import random
secret_number = random.randint(1, 10)
attempts_remaining = 3
while attempts_remaining > 0:
guess = int(input("Guess the number (1-10): "))
if guess == secret_number:
print("Correct! You win!")
break
attempts_remaining -= 1
print(f"Wrong. {attempts_remaining} attempts left.")
else:
print(f"Out of attempts! The number was {secret_number}.")The else block here only runs if the player never guessed correctly — if they had, the break on a correct guess would have skipped it entirely. This is a clean way to express "did they succeed, or did they run out of tries?" without a separate won = False variable that you'd otherwise need to set and check manually.
Practical Example: Input Validation Loop
One of the most common real-world uses of a while loop is repeatedly asking for input until it's actually valid — a pattern you'll write constantly once you start building anything interactive.
while True:
user_input = input("Enter a number between 1 and 10: ")
if not user_input.isdigit():
print("That's not a valid number. Try again.")
continue
number = int(user_input)
if 1 <= number <= 10:
print(f"Thanks! You entered {number}.")
break
else:
print("Out of range. Try again.")This combines several patterns from this article into one clean, practical loop: while True: provides the "keep asking" behavior, continue re-prompts immediately when the input isn't even a valid number, and break exits once a genuinely valid number is entered. It's the same underlying shape you'd use for a password prompt, a menu selection, or any situation where you need to keep asking until you get something usable.
Best-practice note: choosing between for and while
As a general rule: reach for a for loop whenever you're iterating over a known collection or a fixed range — a list, a string, range(10). Reserve while for situations genuinely driven by a condition rather than a known sequence — waiting for valid input, running until some external state changes, or repeating until a specific goal is reached. Using a while loop where a for loop would fit more naturally (or vice versa) usually still works, but it tends to produce more awkward, harder-to-follow code than picking the tool that actually matches the shape of the problem.