Loop Structures: For and While Loops
Iteration is the repeated execution of statements in a loop or recursive function, and understanding loop terminology is essential for writing correct loops.
Try it: while Loops, break and continue
How a while loop re-evaluates its condition before every pass, how break leaves the loop at once, how continue jumps back to the condition, how a sentinel value ends a while True loop, and why a loop whose condition never becomes False runs forever.
How it works
- Evaluate the condition. If it is False, skip the body and continue after the loop.
- If it is True, run the body from the top, then go back and evaluate the condition again.
- continue skips the rest of the body and goes straight back to the condition check.
- break leaves the loop immediately; the condition is not checked again (while True loops rely on it, e.g. stopping at a sentinel like 'done').
- If nothing in the body can make the condition False, the loop never ends; the lab's guard stops it after N iterations and says so.
Default run (21 steps): Ready: Countdown. A while loop checks its condition before every pass. … Finished after 5 iterations and 6 condition checks.
Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. input() returns the lines you type in the list, one per call (the prompt is not printed), and raises EOFError when they run out, like a closed keyboard stream. The guard is the lab's, not Python's.
Loading the simulation…
Why State Matters
Iteration means executing statements repeatedly in a loop or recursive function. Repetition becomes understandable when you track the state of the variables that control the loop. Before a loop begins, variables need starting values. During each iteration, those variables may be increased, decreased, or combined with new values. The loop can continue correctly only when these changes match the condition that controls repetition.
Tracing Variable State
A counter and an accumulator
Trace a loop with a counter that begins at 0 and increases by 1 on each iteration, together with an accumulator that begins at 0 and adds the values 4, 7, and 2 in successive iterations.
- 1Initialization
The counter starts at 0, and the accumulator starts at 0. Initialization assigns starting values before the loop begins.
- 2First iteration
The accumulator adds 4 and becomes 4. The counter increases by 1 and becomes 1.
- 3Second iteration
The accumulator adds 7 to its running total and becomes 11. The counter increases by 1 and becomes 2.
- 4Third iteration
The accumulator adds 2 and becomes 13. The counter increases by 1 and becomes 3.
After three iterations, the counter is 3 and the accumulator is 13. The counter records how many iterations occurred, while the accumulator records the running total of the values added.
| Point in the loop | Counter | Accumulator | Change made |
|---|---|---|---|
| Before iteration 1 | 0 | 0 | Starting values |
| After iteration 1 | 1 | 4 | Counter increases by 1; accumulator adds 4 |
| After iteration 2 | 2 | 11 | Counter increases by 1; accumulator adds 7 |
| After iteration 3 | 3 | 13 | Counter increases by 1; accumulator adds 2 |
A state trace separates the variable that counts iterations from the variable that builds a running total.
Control Variables
Initialization assigns a starting value to a variable before the loop begins. Counters commonly start at 0, and many accumulators also start at 0. The choice of starting value matters because every later state depends on it.
A counter tracks how many times an event occurs. It changes by a fixed amount on each iteration, commonly by 1. An accumulator has a different purpose: it builds a running total by adding values that may vary from one iteration to the next. Both variables may begin at 0, but their roles are different.
An increment increases a variable by a fixed amount, usually 1. A decrement decreases a variable by a fixed amount. In a loop, these operations update the state that will be used during a later condition check or iteration.
| Term | Role | Typical change | Question it answers |
|---|---|---|---|
| Initialization | Sets a starting value before the loop | Assigns the initial state | Where does the variable begin? |
| Counter | Tracks how many times an event occurs | Increases by 1 or another fixed amount | How many iterations or events have occurred? |
| Accumulator | Builds a running total | Adds varying values | What total has been built so far? |
| Increment | Raises a variable | Adds a fixed amount | How does the variable move upward? |
| Decrement | Lowers a variable | Subtracts a fixed amount | How does the variable move downward? |
These terms describe different jobs performed by variables and variable updates in loops.
For and While Control Flow
Both for and while loops repeat statements, so both require a clear view of the loop's state. A for-style loop is commonly traced through initialization, condition checking, the loop body, and an update before the next check. A while-style loop is commonly traced by checking the condition, executing the body when the condition permits it, and ensuring that the body or its control process changes the relevant state. In either structure, initialization comes before repetition, and updates determine what the next iteration will see.
Avoiding Endless Repetition
An infinite loop occurs when repetition does not reach a stopping condition. A common cause is a control variable that is never updated. Another cause is an update that moves the variable in the wrong direction or by an amount that prevents the condition from becoming false. To avoid endless repetition, identify the variable involved in the condition and trace its value after every iteration.
Common mistake Using a control variable without initializing it
What it looks likeThe loop begins by checking or updating a variable that has not been assigned a starting value.
Why it failsThe loop has no clearly defined initial state, making its behavior unreliable and difficult to trace.
Do this insteadAssign the starting value before the loop begins.
Common mistake Forgetting to update the control variable
What it looks likeThe condition depends on a counter, but the counter remains unchanged after each pass.
Why it failsThe condition may remain true indefinitely, producing an infinite loop.
Do this insteadAdd an effective increment or decrement that moves the control variable toward the stopping condition.
Common mistake Confusing a counter with an accumulator
What it looks likeA variable intended to count iterations is treated as though it should add changing values.
Why it failsThe variable no longer represents the number of events or iterations.
Do this insteadUse a fixed update for a counter and varying additions for an accumulator.
Common mistake Updating in the wrong direction
What it looks likeA control variable is decremented even though the stopping condition requires it to increase toward a boundary.
Why it failsThe variable can move away from the state that would end repetition.
Do this insteadTrace the variable after each iteration and choose an increment or decrement that progresses toward the stopping condition.
For every loop, write down the control variable, its initial value, its update, and the condition that determines continuation. If you cannot explain how the update changes the next condition check, the loop is not yet easy to verify.
Practice the Trace
Create a state trace for a loop whose counter starts at 0 and increases by 1 on each iteration. Track the counter after four iterations. Then create a second trace for an accumulator that starts at 0 and adds 3, 5, 1, and 6 during those iterations. Identify which variable is the counter, which is the accumulator, and what each variable represents after the fourth iteration.
Hints
- Write the initialization row before the first iteration.
- Increase the counter by the same fixed amount each time.
- Add the next input value to the accumulator at each iteration.
- The counter should describe how many iterations occurred; the accumulator should describe the running total.
A loop condition depends on a variable that starts at 5. The variable is never changed in the loop body. Explain why this may create an infinite loop, and describe the kind of update that would be needed to make progress toward a stopping condition.
Hints
- Compare the variable's value before and after one iteration.
- Ask whether the condition can become false if the value never changes.
- An increment or decrement should move the variable toward the state required for stopping.
Key Takeaways
- 1Iteration is the repeated execution of statements in a loop or recursive function.
- 2Initialization assigns starting values before repetition begins.
- 3A counter tracks occurrences through fixed updates, while an accumulator builds a running total from varying values.
- 4Incrementing increases a variable and decrementing decreases it; these updates affect the next loop condition check.
- 5An infinite loop can result when the control variable is uninitialized, unchanged, or updated in a direction that does not lead toward stopping.
At a glance
- Trace a loop from initialization through condition checking, the repeated body, and variable updates.
- Use counters to record how many events occur and accumulators to build running totals.
- Use increments and decrements deliberately because they determine the next state of the loop.
- Prevent infinite loops by ensuring that the control variable is initialized and updated toward a stopping condition.