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_loop

A 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:

  1. Initialization: give the counter a starting value.
  2. Condition: decide whether another iteration should begin.
  3. Body: print or process the current value.
  4. Update: change the counter so termination can eventually occur.
count = 0

while count < 10:
    print(count)
    count += 1

The 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

IterationCondition resultCounter before bodyBody outputCounter after update
10 < 3: True001
21 < 3: True112
32 < 3: True223
43 < 3: False3Body is skippedNot 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.

PatternCondition sourceState change requiredTypical use case
Counter-controlledCounter compared with a limitIncrement or decrement the counterRepeat a known range of values
Sentinel-inputLatest user input differs from a sentinelRead the next inputProcess values until a special value is entered
SearchIndex remains within the candidatesAdvance the index or use breakLook for a target
NestedOuter and inner countersUpdate both counters; reset the inner oneProcess 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 missing

count 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 pathWhat happensDoes while else run?
Condition becomes falseNormal completion; execution continues after the loopYes
break executesThe nearest loop ends immediatelyNo
Program is interruptedExecution stops because of an external interruptionNo 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 += 1

The 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; while tests before entering the body.
  • ValueError after 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 else block does not run: The loop probably ended with break. 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.py

For 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 while loop 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.
  • += 1 is 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 else block runs after normal condition-based completion, not after break.
  • In nested loops, the inner loop completes for each outer iteration, and its counter usually must be reset.
  • Prefer while for condition-controlled or unknown-length repetition and for for iterables or known ranges.