Python while Loops
Learn how Python while loops repeat code while a condition is true, using counters, sentinel values, input, and safe loop termination.
A while loop repeatedly executes a block of code while a condition evaluates to True. It is useful when you want repetition controlled by a condition rather than by a fixed number of items.
Code outside a loop runs once when execution reaches it. Code inside a while loop can run many times. When the condition eventually evaluates to False, Python skips the loop body and continues with the first statement after the loop.
While Loop Syntax
The general form of a while loop is:
while condition:
statement
another_statement
whileis the loop keyword.conditionis an expression that produces a Boolean result:TrueorFalse.- The colon marks the beginning of the loop body.
- Indentation identifies the statements belonging to the loop body.
Python checks the condition before every iteration. An iteration is one complete execution of the loop body. If the condition is false at the first check, the body does not run at all.
A first example
temperature = 20
while temperature < 23:
print(temperature)
temperature += 1
print("Loop finished")
The loop prints 20, 21, and 22. After the update, temperature becomes 23, so temperature < 23 is false. Python then prints Loop finished.
Counter-Controlled while Loops
A counter is a variable that tracks progress through repeated iterations. A common pattern is to initialize a counter to zero, continue while it is below a limit, use its current value, and then update it.
x = 0
while x < 10:
print(x)
x += 1
x = 0 is the initialization. The condition is x < 10, and x += 1 is an augmented assignment that increases x by one. The output is:
0
1
2
3
4
5
6
7
8
9
The value 10 is not printed because the condition is checked before the iteration that would use it.
Execution trace
| Iteration | x before condition check | Condition: x < 10 | Value printed | x after x += 1 |
|---|---|---|---|---|
| 1 | 0 | True | 0 | 1 |
| 2 | 1 | True | 1 | 2 |
| 3 | 2 | True | 2 | 3 |
| ... | ... | True | ... | ... |
| 10 | 9 | True | 9 | 10 |
| Exit check | 10 | False | None | Loop ends |
The flow is always: initialize state, evaluate the condition, run the body if it is true, update the state, and evaluate the condition again.
Loop Progress and Termination
A loop must make progress toward a false condition. In the counter example, the relevant state is x. The increment statement changes that state so it eventually reaches 10.
If you omit the update, the loop becomes an infinite loop:
x = 0
while x < 10:
print(x)
# x += 1 is missing
x remains 0, so x < 10 remains true forever. To stop a runaway program, use the stop or interrupt command provided by your editor or terminal; in many terminals, Ctrl+C interrupts the running Python process.
Sentinel-Controlled Input Loops
A sentinel value is a special value that tells a loop to stop. In this example, entering 0 ends the loop. Every nonzero integer is multiplied by 10 and displayed.
number = int(input("Enter an integer (0 to quit): "))
while number != 0:
result = number * 10
print(number, "times 10 is", result)
number = int(input("Enter an integer (0 to quit): "))
print("Finished")
The first input occurs before the loop because Python needs a value to test in number != 0. The repeated input belongs inside the body because the program needs a new value after each processed entry.
For example, entering 4, then -2, then 0 produces results for 4 and -2. The 0 is not processed as an ordinary value; it only ends the loop.
| Loop type | State being checked | How the state changes | Termination condition | Typical use |
|---|---|---|---|---|
| Counter loop | A numeric counter | An increment or decrement, such as x += 1 | The counter reaches a limit | A known range of repetitions |
| Sentinel loop | The latest input or other state | New input is obtained during each iteration | The state equals a special value, such as 0 | Repeated interaction until the user quits |
Condition Evaluation and Iteration Flow
- Initialize the variables needed by the loop.
- Evaluate the condition.
- If it is true, execute every statement in the indented loop body.
- Update the state, or obtain a new state such as another input value.
- Return to the condition and evaluate it again.
- If it is false, skip the body and continue after the loop.
A condition can be true when the loop begins and become false only after a later update. Conversely, it can already be false at loop entry, in which case there are zero iterations.
Indentation and the Loop Body
Indentation is leading whitespace that defines a code block in Python. All statements aligned under the while header belong to the loop body.
x = 0
while x < 2:
print("inside the loop")
x += 1
print("outside the loop")
The first two indented statements repeat. The final print statement is unindented, so it runs once after the loop ends. Use consistent indentation, conventionally four spaces.
Troubleshooting while Loops
The loop never stops
The counter or another condition-related value may not be updated. Check every variable in the condition and confirm that a reachable statement changes it. Add or correct the update, or revise the termination logic.
The loop body does not run
The initial condition is false. Inspect the initialized value and evaluate the comparison manually. Choose a suitable initial value or adjust the condition to match the intended range.
Indentation errors or unexpected execution
Statements may not be consistently indented beneath the while header. Align all body statements, and unindent statements that should run after the loop.
Non-numeric input causes an error
int(input(...)) converts entered text to an integer. Text such as hello cannot be converted, so Python raises a conversion exception. For this introductory example, enter integers. A more robust program can validate input with exception handling; see try and except statements if available in your course materials.
The sentinel is processed
The calculation may occur before the program checks for the sentinel. Put the sentinel comparison in the while condition, as in while number != 0:. Only non-sentinel values then enter the body.
Related Loop Structures
while-else
A loop can have an optional else clause. The else block runs when the loop finishes normally because its condition becomes false. It does not run when the loop exits through break. This is a follow-on topic; see using else statements in loops.
Nested loops
A nested loop is a loop inside another loop. The inner loop completes its iterations for each iteration of the outer loop. Additional indentation makes the two levels clear. Learn more with nested loop statements.
Key Points
- A while loop repeats its indented body while its condition is true.
- The condition is checked before every iteration.
- Initialization happens before the first check.
- A counter update such as
x += 1can make a bounded loop terminate. - A sentinel loop stops when input reaches a special value such as zero.
- Without progress toward a false condition, a loop may be infinite.
- When the condition becomes false, execution continues with the statement after the loop.