A while loop runs a block of code repeatedly for as long as a condition stays true. It is one of the two main loop types in Python, and it is the right tool whenever you do not know ahead of time how many times the loop needs to run.
Python evaluates the condition before each pass through the loop. If the condition is True, the indented body runs. If it is False, Python skips the body and continues with whatever code follows the loop. This means if the condition is false from the very start, the body never runs at all.
The while Loop Syntax
The structure of a while loop in Python is straightforward. The while keyword is followed by a Boolean expression, a colon, and then an indented block of code that forms the loop body.
while condition:
# body runs as long as condition is True
# update something so condition eventually becomes False
Here is a concrete first example. The loop prints numbers from 1 to 5 and stops when count reaches 6.
count = 1
while count <= 5:
print(count)
count += 1
# Output:
# 1
# 2
# 3
# 4
# 5
Indentation in Python is not optional. Every line inside the loop body must be indented consistently, typically four spaces. The first line that returns to the original indentation level marks the end of the loop body.
The while True pattern
Writing while True creates a loop that will run indefinitely unless something inside the body forces an exit. This pattern is common when you want to keep prompting a user until they provide valid input.
while True:
answer = input("Type 'quit' to exit: ")
if answer == "quit":
break
print("You typed:", answer)
Any while loop that never reaches a False condition and has no break statement will run forever. In a script this freezes the program. Press Ctrl+C in the terminal to interrupt a runaway loop.
Build a correct while loop that prints numbers starting at 1. Arrange the tokens in the right order:
while loop starts with the keyword while, not for. The counter variable count must be initialized to 1 before the loop, checked in the condition count <= 5:, and incremented with count += 1 inside the body. Using count -= 1 would count downward and never reach the exit condition.
Counters and Condition Variables
The condition in a while loop can test any expression that evaluates to True or False. A counter variable is the most common approach for beginners, but a loop can also watch a boolean flag, check the length of a list, or test any other changing value.
Counter variable pattern
i = 10
while i >= 0:
print(i)
i -= 2
# Output: 10, 8, 6, 4, 2, 0
Boolean flag pattern
A boolean flag is a variable that starts as True and is flipped to False when a condition inside the loop is met.
found = False
items = [3, 7, 12, 5, 9]
index = 0
while not found:
if items[index] == 12:
found = True
index += 1
print("Found at index", index - 1) # Found at index 2
Three things must work together for a safe while loop: a variable initialized before the loop, a condition that tests that variable, and an update to that variable inside the body. Miss any one of these and the loop either never runs or runs forever.
- Best for
- Unknown number of iterations; running until a condition changes
- Danger
- Can become infinite if the condition never turns False
- Best for
- Iterating over a known sequence such as a list, string, or range
- Danger
- Modifying the sequence being iterated over can cause unexpected behavior
- Best for
- Event loops, input validation, and retry logic where the exit condition is tested mid-loop
- Danger
- Forgetting the break statement causes an infinite loop
Using break and continue
Two keywords give you precise control over loop flow without changing the condition expression: break and continue.
break
break exits the loop immediately. Python stops checking the condition and moves past the loop entirely. It is most useful when you are searching for something and want to stop once you find it.
secret = 42
guess = 0
while True:
guess += 1
if guess == secret:
print("Found it at", guess)
break
# Found it at 42
continue
continue skips the rest of the current iteration and returns to the condition check. The loop keeps running — it just does not execute any code below continue for that pass.
n = 0
while n < 10:
n += 1
if n % 2 == 0:
continue # skip even numbers
print(n)
# Output: 1, 3, 5, 7, 9
The while-else clause
Python supports an else clause on while loops. The else block runs only when the condition becomes False naturally. If the loop exits because of a break, the else block is skipped entirely.
attempts = 0
max_attempts = 3
password = "python"
while attempts < max_attempts:
entry = input("Password: ")
if entry == password:
print("Access granted")
break
attempts += 1
else:
print("Too many failed attempts")
"Explicit is better than implicit." — The Zen of Python, Tim Peters
This loop is supposed to print the numbers 1 through 5. One line contains a bug that causes an infinite loop. Click the line you think is wrong, then hit check.
count -= 1 to count += 1. Subtracting 1 from count each iteration makes the value smaller on every pass, so the condition count <= 5 stays True forever and the loop never exits.
How to Write a while Loop in Python
Follow these steps to write a while loop that runs correctly without accidentally running forever.
-
Initialize a variable to control the condition
Declare and assign a starting value to the variable that will be tested. For example, write
count = 0on the line immediately before the loop. Python needs this value to evaluate the condition on the very first pass. -
Write the while keyword and condition
Type
whilefollowed by a Boolean expression and a colon. For example:while count < 5:. Python will test this expression before every iteration. -
Indent the loop body
Write all code that should execute each iteration indented four spaces under the
whileline. Any line at the original indentation level is outside the loop and only runs after the loop finishes. -
Update the condition variable inside the loop
The variable tested in the condition must change during each iteration so the condition eventually becomes
False. For a counter, writecount += 1at the end of the body. This is the step beginners forget most often. -
Use break or continue when needed
Add a
breakstatement to exit the loop early when a specific condition is met. Addcontinueto skip the rest of the current iteration and return to the condition check. Both are optional — use them only when the logic calls for it.
Python Learning Summary Points
- A
whileloop tests its condition before every iteration. The body runs only when the condition isTrue. - Always update the variable being tested inside the loop body; failing to do so produces an infinite loop.
breakexits the loop immediately regardless of the condition.continueskips to the next iteration without leaving the loop.- The optional
elseclause on awhileloop runs when the condition becomesFalse, but is bypassed entirely whenbreakis used. - Use
while Truewith an explicitbreakwhen the exit condition is best checked in the middle of the loop body rather than at the top.
The while loop is a foundational piece of Python control flow. Once you can write a loop that initializes a variable, checks a condition, performs work, and reliably updates its exit condition, you have the core mechanics needed for retry logic, input validation, event processing, and much more.
Frequently Asked Questions
A while loop in Python is a control flow statement that repeatedly executes a block of code as long as a specified condition evaluates to True. When the condition becomes False, the loop stops and execution moves to the next statement after the loop.
Write the keyword while followed by a condition and a colon, then indent the body code beneath it. For example: while count < 5: followed by an indented block. Python evaluates the condition before each iteration.
An infinite loop occurs when the while loop condition never becomes False. This commonly happens when the variable being tested is never updated inside the loop body, or when the condition is written as while True without a break statement to exit.
The break statement immediately exits the while loop, regardless of whether the condition is still True. Execution jumps to the first statement after the loop body.
The continue statement skips the remaining code in the current iteration and jumps back to the while condition check. The loop continues running if the condition is still True.
Python allows an else clause attached to a while loop. The else block runs only when the loop condition becomes False naturally — it does not run if the loop was exited with a break statement.
A for loop iterates over a known sequence of items a fixed number of times. A while loop runs as long as a condition is True, which makes it better suited for situations where the number of iterations is not known in advance.
Use while True and read input inside the loop. Check the input value with an if statement and call break when the user enters the expected exit value, such as "quit" or an empty string.
Yes. A counter variable is initialized before the loop, tested in the condition, and incremented or decremented inside the loop body. For example: count = 0, while count < 10:, count += 1 inside the body.
Yes. Python uses indentation to define the loop body. Any line indented under the while statement is part of the loop. A line at the original indentation level marks the end of the loop body.