VMware ESXi and vSphere Cluster Management
Python while Loops: Conditions, Repetition, else Clauses, and Nested Loops
Learn Python while loops with conditions, counters, user-input sentinels, infinite-loop prevention, while else, break, and nested loops.
What Is a while Loop?
A while loop is a control-flow statement that repeatedly runs an indented block while a condition is True. Each execution of the loop body is one iteration.
When the condition becomes False, Python skips the loop body and continues with the first statement after the loop. In contrast, ordinary sequential code runs once when execution reaches it.
temperature = 25
while temperature > 20:
print(temperature)
temperature -= 1
print("The loop has ended")Here, Python checks the condition before every iteration. Values from 25 through 21 are printed. When temperature becomes 20, the condition is false, so execution continues at the final print().
while Syntax and Indentation
The general structure contains the while keyword, a Boolean expression, a colon, and an indented loop body.
while condition:
statement_1
statement_2
statement_after_loopA condition is an expression that evaluates to either True or False. Python uses indentation to determine which statements belong to the loop body. The condition is tested before the body runs, so a loop can execute zero times if the initial condition is already false.
count = 10
while count < 10:
print(count)
print("This runs because the loop ran zero times")Counter-Controlled Loops
A counter is a variable that tracks progress through repeated work. A typical counter-controlled loop has four parts:
- Initialization: give the counter a starting value.
- Condition: decide whether another iteration should begin.
- Body: print or process the current value.
- Update: change the counter so termination can eventually occur.
count = 0
while count < 10:
print(count)
count += 1The augmented assignment count += 1 means “add 1 to the current value of count and assign the result back to count.” It is equivalent to count = count + 1. This example prints values from 0 through 9. After printing 9, the update makes the counter 10; the next condition test fails.
Execution Trace
| Iteration | Condition result | Counter before body | Body output | Counter after update |
|---|---|---|---|---|
| 1 | 0 < 3: True | 0 | 0 | 1 |
| 2 | 1 < 3: True | 1 | 1 | 2 |
| 3 | 2 < 3: True | 2 | 2 | 3 |
| 4 | 3 < 3: False | 3 | Body is skipped | Not updated |
The final failed test is important: Python checks the condition one more time before deciding that the loop is complete.
Updating Loop State
Loop state is the changing information that controls whether another iteration is needed. It might be a counter, a value read from the user, an index into a list, or another variable. Every expected path through the loop should change that state in a way that can eventually make the condition false.
| Pattern | Condition source | State change required | Typical use case |
|---|---|---|---|
| Counter-controlled | Counter compared with a limit | Increment or decrement the counter | Repeat a known range of values |
| Sentinel-input | Latest user input differs from a sentinel | Read the next input | Process values until a special value is entered |
| Search | Index remains within the candidates | Advance the index or use break | Look for a target |
| Nested | Outer and inner counters | Update both counters; reset the inner one | Process rows and columns |
Infinite Loops
An infinite loop is a loop whose condition never becomes false. A common cause is forgetting to update the controlling variable.
count = 0
while count < 3:
print(count)
# count += 1 is missingcount remains 0, so count < 3 remains true forever. If an accidentally infinite program is running in a terminal or interactive Python session, press Ctrl+C to interrupt it.
Before running a loop, ask: What state controls the condition? Where is that state initialized? Which statement changes it? Can every applicable path reach that change? A deliberate infinite loop can be useful for some programs, but it should include a clear exit mechanism such as break.
Sentinel-Controlled User Input
A sentinel value is a special value that means “stop” rather than “process this normally.” The following program reads integers and multiplies each nonzero value by 10. Entering zero ends the loop.
number = int(input("Enter an integer (0 to stop): "))
while number != 0:
print(number * 10)
number = int(input("Enter another integer (0 to stop): "))
print("Input complete")input() returns text, so int() converts that text to an integer. The initial input must be collected before the first condition check because the loop needs a value to compare with the sentinel. The next input is requested inside the loop; otherwise, number would never change and the loop could not respond to later user entries.
The while else Clause
A while loop may have an optional else block. The else block runs when the loop ends normally because its condition becomes false. It does not run when the loop exits through break.
numbers = [4, 7, 12, 15]
target = 9
index = 0
while index < len(numbers):
if numbers[index] == target:
print("Found the target")
break
index += 1
else:
print("The target was not found")The loop checks one list element at a time. If it finds the target, break exits the nearest enclosing loop and the else block is skipped. If the index reaches the list length without finding the target, the condition becomes false and the else block reports that the search was unsuccessful.
How a while Loop Ends
| Exit path | What happens | Does while else run? |
|---|---|---|
| Condition becomes false | Normal completion; execution continues after the loop | Yes |
break executes | The nearest loop ends immediately | No |
| Program is interrupted | Execution stops because of an external interruption | No normal completion |
Nested while Loops
A nested loop is a loop inside the body of another loop. The outer loop controls a larger repetition, while the inner loop performs all of its iterations for each outer iteration.
row = 1
while row <= 3:
column = 1
while column <= 4:
print(f"({row}, {column})")
column += 1
row += 1The output contains four coordinates for row 1, then four for row 2, and then four for row 3. The inner loop completes before the outer counter advances. Notice that column = 1 is inside the outer loop, so the inner counter is reset for every new row.
If the inner counter were initialized only once before the outer loop, it would already be 5 after the first row and later rows would produce no coordinates. The inner loop also needs its own update; otherwise, it can become infinite while the outer loop waits for it to finish.
Choosing while or for
Use while when repetition should continue until a changing condition is met, especially when the number of iterations is not known in advance. User input, searches, and “retry until valid” operations are common examples.
Use a for loop when you want to visit the items in an iterable, such as a list or string, or repeat over a known range with range().
# while: stop when a condition changes
attempts = 0
while attempts < 3:
print("Attempt", attempts)
attempts += 1
# for: iterate over a known range
for attempt in range(3):
print("Attempt", attempt)Common Problems and Fixes
- The loop never stops: The counter or other controlling state is not updated. Change the relevant state on every applicable path so the condition can eventually become false.
- The loop runs zero times: The initial condition is already false. Check the starting value and comparison operator;
whiletests before entering the body. ValueErrorafter input:int()received text that is not a valid integer. Enter numeric input for the basic example or add validation.- Only one user value is processed: The next input is not requested inside the loop. Read and assign a new value near the end of each iteration.
- A nested loop has incorrect rows or never completes: Reset the inner counter inside the outer loop and update it inside the inner loop.
- The
while elseblock does not run: The loop probably ended withbreak. The block is only for normal condition-based completion. - Syntax or membership errors: Add the colon after the condition and use consistent indentation for the loop body.
Running a Saved Example
Save a loop in a file such as loops.py, then run it from a terminal with:
python loops.pyFor more practice, connect these examples with the while loop lesson and related topics such as for loops, break, input validation, and exception handling.
Exam-Ready Summary
- A
whileloop evaluates its Boolean condition before every iteration. - The indented loop body runs only while the condition is true.
- Initialize loop state before the first condition test, then update it during the body.
+= 1is augmented assignment commonly used to increment a counter.- A missing update can create an infinite loop; use Ctrl+C to interrupt an accidental command-line loop.
- A sentinel is a special input value that ends processing.
- A
while elseblock runs after normal condition-based completion, not afterbreak. - In nested loops, the inner loop completes for each outer iteration, and its counter usually must be reset.
- Prefer
whilefor condition-controlled or unknown-length repetition andforfor iterables or known ranges.