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.
Line 5: The
whileheader checks ifcurrent_temperatureis less thantarget_temperature. This line runs only if the condition isTrue.Lines 6–7: We increment
current_temperature. This is critical: if the variable never changes, the condition never becomesFalse.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:
Initialization: Setting a variable before the loop starts.
Condition: Checking that variable in the
whilestatement.Update: Modifying the variable inside the loop body.
Line 1: We initialize
attemptsto 1 andmax_retriesto 3.Line 4: The loop runs as long as
attemptsis less than or equal tomax_tries.Line 7: We increment
attemptsby 1. Without this line,attemptswould stay 1 forever.
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
whileloop, 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.")Line 2: We capture the initial input. If the user types "stop" immediately, the loop never runs.
Line 4: The loop checks if the
commandmatches 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
commandvariable 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.