Loop Control Variables
What you'll learn: How to use variables to steer your loops and understand how their values change with each iteration.
The Steering Wheel of Your Loop
When you learned about the while loop, you saw that it keeps running as long as a condition remains true. But how does that condition eventually become false? This is where loop control variables come in—they're the variables that change during each pass through the loop, eventually causing it to stop.
Think of a loop control variable like the page counter when reading a book: you start at page 1, and after each page you increment the counter. When the counter reaches the last page, you stop reading. The counter controls when you finish.
How They Work
A loop control variable typically follows this pattern:
- Initialize the variable before the loop starts
- Check the variable in the loop's condition
- Update the variable inside the loop body
For example, if you want to count from 1 to 5:
counter = 1
while counter <= 5:
print(counter)
counter = counter + 1
Here, counter is the loop control variable. It starts at 1, and each iteration increases by 1. When counter reaches 6, the condition counter <= 5 becomes false, and the loop stops.
Why This Matters
Understanding loop control variables helps you:
- Prevent infinite loops (forgetting to update the variable)
- Control exactly how many times a loop runs
- Track progress through repetitive tasks
Key Takeaway: Loop control variables are the changing values that determine when a loop continues or stops—you initialize them before the loop, check them in the condition, and update them inside the loop body.