The while loop in Python repeats a block of code as long as a condition evaluates to True. You use it when you do not know upfront how many iterations you need. The loop stops the moment the condition becomes False, or when you explicitly break out of it. This is the fundamental difference between a while loop and a for loop. For loops iterate over a known sequence, while loops wait for a condition to change.
This guide covers the while loop syntax, the flow of execution, common patterns like counters and user input validation, and the finer details like the while-else construct and the danger of infinite loops.
while Loop Syntax
while condition:
# code block runs while condition is True
How the while Loop Executes
The while loop follows a predictable cycle. Python checks the condition first. If it is True, the loop body executes. After the body finishes, Python checks the condition again. This cycle repeats until the condition is False.
If the condition is False on the very first check, the loop body never executes. The loop skips directly to the code after it. This is called a zero-iteration execution and it is a normal behavior.
Basic Example: Counter Loop
The most common while loop pattern is a counter. You initialize a variable before the loop, check it in the condition, and modify it inside the loop body.
def print_msg(count, msg):
while count > 0:
print(msg)
count -= 1
print_msg(3, "Hello World")
The output is three lines of “Hello World”. The variable count starts at 3. Each iteration prints the message and decrements count by 1. When count reaches 0, the condition count > 0 becomes False and the loop exits.
Infinite Loops and How to Avoid Them
If the condition in a while loop never becomes False, the loop runs forever. This is called an infinite loop and it freezes your program until you kill it.
# This runs forever
i = 1
while i > 0:
print(i)
i += 1
Two things cause infinite loops most often. First, forgetting to modify the loop variable inside the body. Second, a logical error where the condition never becomes False. Always ask yourself what should make this condition False and whether the loop body guarantees that will eventually happen.
break and continue
Sometimes you want to exit a loop early. The break statement exits the loop immediately. The continue statement skips the rest of the current iteration and jumps back to the condition check.
i = 0
while i < 10:
i += 1
if i == 5:
break
if i % 2 == 0:
continue
print(i)
The output is 1 and 3. When i becomes 5, break exits the loop before printing. When i is even, continue skips the print statement.
while with else
Python adds an unusual feature to while loops: an else block that runs when the loop exits normally (when the condition becomes False rather than when break is hit).
i = 1
while i < 5:
print(i)
i += 1
else:
print("Loop finished normally")
When i reaches 5, the condition i < 5 is False and the loop exits. The else block runs. If you add a break that exits the loop early, the else block does not run.
User Input Validation
One of the most practical uses of a while loop is validating user input. You keep asking until the user provides something acceptable.
def get_positive_number(prompt="Enter a positive number: "):
while True:
value = input(prompt)
try:
value = float(value)
if value > 0:
return value
print("That is not positive. Try again.")
except ValueError:
print("That is not a valid number. Try again.")
num = get_positive_number()
print(f"You entered: {num}")
This loop runs until the user enters a positive number. while True is the idiom for a loop where you want to keep going until a break happens. The break is implicit in the return statement.
Nested while Loops
You can nest one while loop inside another. The inner loop completes all its iterations before the outer loop advances. Be careful: every inner loop must have its own condition variable that it modifies.
i = 1
while i <= 3:
j = 1
while j <= 3:
print(f"{i},{j}", end=" ")
j += 1
print()
i += 1
The output is nine pairs arranged in three rows.
FAQ
When should I use a while loop instead of a for loop?
Use a while loop when you do not know how many iterations you need at the start. This happens with user input validation, reading until EOF, waiting for a condition to change, or implementing retry logic. Use a for loop when you are iterating over a known sequence or range.
What is the boolean value of 0 and None in a while condition?
Zero (0) evaluates to False. None evaluates to False. Every other integer evaluates to True. This means while n: will exit when n becomes 0, which is equivalent to while n != 0: but more compact.
Can I use a while loop to iterate over a sequence?
Yes. You can manually maintain an index variable and use it to access elements of a list or string. However, a for loop with enumerate is the cleaner approach for sequential iteration. Reserve while loops for situations where the iteration count is not known in advance.
How do I stop a while loop from running forever?
Make sure something inside the loop body changes the condition. A counter-based loop like i += 1 inside the body is the standard pattern. For condition-based loops, verify that the logic actually leads to the condition becoming False. If your loop depends on external state, add a maximum iteration limit or timeout as a safety net.

