Search⌘ K
AI Features

While Loops and Counters

Explore how to use Python while loops to repeatedly execute code based on dynamic conditions. Learn to control iteration with counters for fixed repetitions and process input with sentinel values to manage user-driven loops. Understand common pitfalls like infinite loops and how to avoid them by properly updating loop variables.

So far, we have learned how to write programs that make decisions using if statements. However, these programs still execute from top to bottom only once. To build true automation, such as programs that process large amounts of data or continue running until a user chooses to stop, we need a way to repeat actions. This repetition is called iteration.

The Python while loop enables iteration by repeatedly executing a block of code as long as a specified condition remains true. By using loops, we transform programs from simple, one-time instructions into continuous processes that can respond dynamically to changing data.

The structure of a while loop

A while loop works like a repeating if statement. When learning how to use a while loop in Python, remember it evaluates a boolean condition; if the condition is True, it executes the indented block of code. Once the block finishes, Python loops back to the top and rechecks the condition. This cycle continues until the condition becomes False.

The syntax relies on the while keyword followed by a condition and a colon.

Python 3.14.0
current_temperature = 25
target_temperature = 28
# Keep heating until the target is reached
while current_temperature < target_temperature:
print(f"Heating... Current temp: {current_temperature}")
current_temperature += 1 # Change the condition variable
print(f"Target reached: {current_temperature}")
  • Line 5: The while header checks if current_temperature is less than target_temperature. This line runs only if the condition is True.

  • Lines 6–7: We increment current_temperature. This is critical: if the variable never changes, the condition never becomes False.

  • Line 9: This line runs only after the loop condition becomes False (when the temperature hits 28).

Controlled iteration with counters

Often, we want to repeat an action a specific number of times. Since while loops do not automatically track how many times they have run, we must manage this manually using a counter. A counter loop consists of three parts:

  1. Initialization: Setting a variable before the loop starts.

  2. Condition: Checking that variable in the while statement.

  3. Update: Modifying the variable inside the loop body.

Python 3.14.0
attempts = 1
max_retries = 3
while attempts <= max_retries:
print(f"Connection attempt {attempts} of {max_retries}...")
# Simulate connection logic here
attempts += 1
print("Finished attempts.")
  • Line 1: We initialize attempts to 1 and max_retries to 3.

  • Line 4: The loop runs as long as attempts is less than or equal to max_tries.

  • Line 7: We increment attempts by 1. Without this line, attempts would stay 1 forever.

Flow chart to while loops
Flow chart to while loops

The infinite loop pitfall

The most common error with while loops is the infinite loop. This happens when the condition never becomes False, usually because we forgot to update the variable being evaluated. For example, try omitting attempts += 1 in the previous example, attempts would remain 1, the condition 1 <= 3 would never become False, and and the program would print 'Connection attempt...' forever. Later, we will learn how to break out of a loop in Python using specialized keywords to stop these runaway processes.

Tip: When writing a while loop, we must always ask, "Does the code inside the loop change the variables used in the condition?"

Processing input with sentinel values

We often do not know in advance how many times a loop should run. For example, we might want a menu to keep reappearing until the user types "exit". In this scenario, we use a sentinel value—a specific value that signals the loop to terminate.

Unlike languages with a do-while loop that guarantees code runs at least once, Python evaluates the condition immediately upon encountering the loop. This creates a strict requirement: the variable used in the condition must be initialized before the loop begins, so that the very first check has data to evaluate.

To handle this, we use a priming read pattern. We read the input once before the loop (to "prime" the variable), and then again at the very end of the loop body (to prepare for the next check).

# Priming read: Get the first input so 'command' exists
command = input("Enter command (type 'stop' to quit): ")

while command != "stop":
    print(f"System is executing: {command}")
    
    # Update read: Get the next input to test in the next iteration
    command = input("Enter command (type 'stop' to quit): ")

print("System shutdown complete.")
The standard priming read pattern for handling user input in Python
  • Line 2: We capture the initial input. If the user types "stop" immediately, the loop never runs.

  • Line 4: The loop checks if the command matches the sentinel value using Python boolean expressions to determine if the cycle should continue or stop.

  • Line 5: We process the valid command.

  • Line 8: We ask for input again. This updates the command variable so the condition can be re-evaluated at the start of the next iteration.

This pattern ensures we never process the "stop" command itself as an action, effectively replicating do-while logic using Python’s standard while loop.

The while loop gives us the power of conditional repetition. In the next lesson, we will dive into Python for loop to see how to automate iteration over collections of data using Python nested loops. Whether we are counting up to a limit or waiting for a specific user signal, the mechanism is the same: check, execute, update, repeat. We must explicitly manage our variables to ensure the loop eventually terminates.