How programs do the same work again and again — loop bodies, iteration, loop variables, counters, accumulators, and the discipline of tracing repeated execution
Programs are not just sequences of instructions that run once and stop. Many useful programs need to repeat the same work dozens, hundreds, or thousands of times. A program that prints five messages by copying the same line five times is brittle, tedious to write, and impossible to scale. A program that prints five hundred messages that way is not practical at all.
Repetition is one of the most powerful ideas in programming. When you understand loops, programs stop being a fixed sequence of steps and become flexible tools that can handle any amount of work. A single well-written loop can process ten inputs or ten million inputs without changing a line of code.
This chapter introduces the concept of repetition in Python programs. You will learn what a loop is, what makes a loop work, how to trace what a loop is doing, how counters and accumulators work inside loops, and how to distinguish between loops that repeat a fixed number of times and loops that repeat as long as a condition is true.
This chapter builds the conceptual foundation. Chapters 8 and 9 will teach you the two main loop types in Python — while loops and for loops — with full detail. This chapter prepares you to understand both by focusing on the ideas that every loop shares, before you learn the specific Python syntax for each kind.
+= shorthand; counting events that occur inside a loopMost useful tasks involve doing the same kind of thing more than once.
Think about calculating a class average. You need to add up every student's score. If there are thirty students, you need thirty additions. A program that only adds one number is not useful. A program that repeats the addition thirty times — adjusting which number it adds each time — is exactly what you need.
Think about asking a user to enter a valid number. If the user types something wrong, you need to ask again. And if they type something wrong again, you need to ask again. You do not know in advance how many times you will need to ask. You keep asking until they get it right.
Think about a program that prints a multiplication table. You need to produce many lines of output, each slightly different — line one multiplies by one, line two multiplies by two, and so on. Writing that by hand is tedious. A loop produces all of it automatically.
These three examples represent different loop situations, but they share the same core idea: doing something repeatedly so the program can handle real quantities of work.
Without loops, programming would be extremely limited. You could only process exactly as many things as you wrote instructions for. With loops, programs can scale.
You already know what repetition means in everyday life. You have followed repeated instructions many times without calling them loops.
When a recipe says "stir the batter fifty times," that is repetition with a counter. You stir once, then again, then again, keeping track of how many times you have stirred.
When a door says "push until open," that is repetition with a condition. You push once, check if the door is open, push again if it is not, and stop when it is.
When a teacher says "read every problem on the test before answering," that is repetition over a collection. You read problem one, then problem two, then problem three, working through the whole set.
Python has tools for all three, and you will study them over the next several chapters. For now, notice that repetition is not a strange abstract concept. It is a pattern you already understand from ordinary experience.
A loop in Python has two main parts: the loop header and the loop body.
The loop header describes the conditions under which the loop runs — how many times, or while what is true, or for which items.
The loop body contains the instructions that run each time the loop repeats. The loop body is indented under the loop header, just as the body of an if statement is indented under its condition.
Here is a simple loop written in Python:
count = 1
while count <= 3:
print("Hello")
count = count + 1
Hello Hello Hello
The loop header is while count <= 3. It tells Python to keep running the body as long as count is less than or equal to 3.
The loop body is the two indented lines:
print("Hello")
count = count + 1
Every time the loop body runs, it prints Hello and then adds 1 to count. After three repetitions, count reaches 4, the condition count <= 3 becomes False, and the loop stops.
The loop body can contain any number of statements. Every statement in the loop body runs once per repetition of the loop. If the loop body has five statements and the loop runs ten times, those five statements collectively run fifty times.
The indentation is not optional. Python uses indentation to know which lines belong to the loop body. A line that is not indented is not part of the loop. It runs after the loop finishes.
count = 1
while count <= 3:
print("This is inside the loop.")
count = count + 1
print("This is outside the loop.")
This is inside the loop. This is inside the loop. This is inside the loop. This is outside the loop.
The last print runs exactly once, after the loop has completed all its repetitions.
Each time a loop body runs from beginning to end, that is called one iteration.
If a loop runs ten times, it completes ten iterations. If a loop runs once, it completes one iteration. If the loop condition is false before the loop even starts, the loop completes zero iterations — the body never runs at all.
The word "iterate" comes from a Latin word meaning "to do again." In programming, iteration means repeating a process.
You will hear iteration used in several related ways:
Counting iterations is a useful habit when tracing loops. Before you run a loop in your head, ask: how many times will this loop iterate? Then trace each iteration carefully.
count = 0
while count < 5:
print(count)
count = count + 1
count is 0. Is 0 < 5? Yes. Run the body.count is 1. Is 1 < 5? Yes. Run the body.count is 2. Is 2 < 5? Yes. Run the body.count is 3. Is 3 < 5? Yes. Run the body.count is 4. Is 4 < 5? Yes. Run the body.count is 5. Is 5 < 5? No. Stop.The loop completes five iterations. It prints the values 0, 1, 2, 3, and 4.
A loop variable is a variable that changes each time the loop iterates. Loop variables are how loops do something slightly different on each iteration rather than repeating exactly the same thing over and over.
In the example above, count is a loop variable. It starts at 0 and increases by 1 each iteration, so each iteration uses a different value.
Loop variables allow loops to:
The loop variable does not have to be called count. You can use any valid Python name. Common loop variable names include i, n, number, index, item, value, and descriptive names based on what the variable represents.
number = 1
while number <= 5:
print(number * number)
number = number + 1
1 4 9 16 25
Here number goes through the values 1, 2, 3, 4, 5 on successive iterations. Each iteration prints number * number, so the loop prints the squares of 1 through 5.
The loop variable number controls both when the loop stops and what value is used inside the body. This is very common: loop variables serve double duty as progress trackers and as the values the loop works with.
A counter is a variable used to keep track of how many times something has happened. Counters are updated by adding 1 each time the thing you are counting occurs.
The most basic counter pattern looks like this:
counter = 0 # ... something happens ... counter = counter + 1
You initialize the counter to 0 before anything has been counted. Then, every time the event you care about occurs, you add 1 to the counter.
Suppose you want to count how many of five numbers entered by the user are even. Here is one way to do that with a counter:
count = 0
total_entered = 0
while total_entered < 5:
number = int(input("Enter a number: "))
if number % 2 == 0:
count = count + 1
total_entered = total_entered + 1
print("Even numbers entered:", count)
count is the counter. It starts at 0. Each time the user enters an even number (one where number % 2 == 0 is true), the counter increases by 1.
total_entered is a separate loop variable that tracks how many numbers have been entered so far, controlling when the loop stops.
After five iterations, the program prints how many of the five inputs were even.
Python programmers often write counter = counter + 1 as counter += 1. These two lines do exactly the same thing. The += operator is a shorthand for "add the value on the right to the variable on the left." You will see both forms throughout this book.
counter = 0 counter += 1 # same as: counter = counter + 1 counter += 1 counter += 1 print(counter) # prints: 3
A counter keeps track of how many times something happens. An accumulator keeps track of a running total of values.
The accumulator pattern looks like this:
total = 0 # ... inside a loop ... total = total + some_value
You initialize the accumulator to 0 before the loop begins. Each iteration adds a new value to the accumulator. After the loop, the accumulator holds the sum of all the values that were added.
total = 0
count = 1
while count <= 5:
number = int(input("Enter number " + str(count) + ": "))
total = total + number
count += 1
print("Total:", total)
If the user enters 10, 20, 30, 40, and 50, the program prints Total: 150.
Trace what the accumulator holds after each iteration:
| Iteration | number entered | total after adding |
|---|---|---|
| 1 | 10 | 10 |
| 2 | 20 | 30 |
| 3 | 30 | 60 |
| 4 | 40 | 100 |
| 5 | 50 | 150 |
Each iteration adds the newly entered number to whatever total was built up in previous iterations. After five iterations, total holds the sum of all five entries.
Accumulators are not limited to addition. An accumulator could build up a string by concatenation, or keep a running product by multiplication, or track the maximum value seen so far. The key idea is that the variable accumulates information across iterations.
result = ""
count = 1
while count <= 4:
word = input("Enter a word: ")
result = result + word + " "
count += 1
print("Your sentence:", result)
If the user enters "The", "dog", "runs", "fast", the output is:
Your sentence: The dog runs fast
result starts as an empty string "" and each iteration appends a word and a space.
Counters and accumulators often appear together. In many programs, you need both: a counter to control the loop and an accumulator to build a total.
All loops fall into one of two broad categories: definite repetition and indefinite repetition. Understanding the difference helps you choose the right kind of loop for each situation.
A loop uses definite repetition when you know in advance exactly how many times it will iterate.
In each case, the number of iterations is fixed and known before the loop starts. The loop does not need to check a changing condition to decide when to stop; it just needs to count to a predetermined number.
Python's for loop (Chapter 9) is designed primarily for definite repetition. The range() function lets you say exactly how many times to iterate.
A loop uses indefinite repetition when the number of iterations depends on something that changes during execution — usually a condition that the loop keeps checking.
In each case, you do not know in advance how many times the loop will run. The loop continues until some condition becomes false.
Python's while loop (Chapter 8) is designed primarily for indefinite repetition. The loop condition is evaluated before every iteration, and the loop stops as soon as the condition is false.
The question to ask when designing a loop is: Do I know how many times this loop will run before it starts?
Yes → consider definite repetition (usually a for loop).
No → consider indefinite repetition (usually a while loop).
Both types of loop are important. Many programs use both types in different parts of the code.
Tracing a loop means stepping through it one iteration at a time, recording what every variable holds after each iteration, and confirming what the loop produces.
Tracing is essential for beginners. Loops are the place where programs most often behave unexpectedly, and tracing lets you discover exactly what is happening.
A tracing table organizes this process. Each row represents one iteration.
x = 10
while x > 0:
print(x)
x = x - 3
Before the loop: x = 10
| Iteration | x at start | Condition x > 0 | Output | x after update |
|---|---|---|---|---|
| 1 | 10 | True | 10 | 7 |
| 2 | 7 | True | 7 | 4 |
| 3 | 4 | True | 4 | 1 |
| 4 | 1 | True | 1 | -2 |
| 5 | -2 | False | (stop) | — |
The loop prints: 10, 7, 4, 1.
Notice that after the fourth iteration, x becomes -2, which makes the condition false, so the loop stops before a fifth iteration runs.
total = 0
n = 1
while n <= 4:
total = total + n
n += 1
print(total)
Before the loop: total = 0, n = 1
| Iteration | n | Condition n <= 4 | total before | total after | n after |
|---|---|---|---|---|---|
| 1 | 1 | True | 0 | 1 | 2 |
| 2 | 2 | True | 1 | 3 | 3 |
| 3 | 3 | True | 3 | 6 | 4 |
| 4 | 4 | True | 6 | 10 | 5 |
| 5 | 5 | False | — | — | — |
The program prints 10 (which is 1 + 2 + 3 + 4).
Tracing tables take a little time to fill out, but they eliminate guessing. Once you can trace loops correctly, debugging becomes much easier because you know exactly what the loop is doing at every step.
Beginners make certain kinds of mistakes with loops very consistently. Knowing about these in advance helps you recognize and fix them faster.
An off-by-one error occurs when a loop runs one time too many or one time too few.
These errors usually come from confusion about whether the loop condition should use < or <=, or whether a starting value should be 0 or 1.
count = 1
while count < 5:
print(count)
count += 1
This prints: 1, 2, 3, 4 — four values.
count = 1
while count <= 5:
print(count)
count += 1
This prints: 1, 2, 3, 4, 5 — five values.
If you need exactly five iterations and you got four, check whether < should be <=. If you got six when you expected five, check the opposite.
When in doubt, trace the first and last iterations carefully and count.
If you forget to update the variable that the loop condition checks, the loop will run forever. This is called an infinite loop.
count = 1
while count <= 5:
print(count)
# Missing: count += 1
count is never updated, so count <= 5 is always true, and the loop never stops. If you accidentally run an infinite loop, press Control+C in the terminal to stop the program.
Always check: does each iteration bring the loop variable closer to making the condition false?
Variables that appear in the loop body need to exist before the loop starts. If you forget to initialize a variable, Python raises a NameError.
while count < 5: # NameError: count is not defined
print(count)
count += 1
The fix is to initialize count before the loop:
count = 0
while count < 5:
print(count)
count += 1
Always check: have all variables the loop uses been assigned a value before the loop begins?
Sometimes a loop condition is logically reversed. The loop runs when it should stop, or stops when it should run.
count = 10
while count < 5: # This condition is already false; the loop never runs.
print(count)
count -= 1
If count starts at 10 and the condition is count < 5, the loop body never executes because 10 is already not less than 5.
Check: does the starting value satisfy the loop condition? Trace the first iteration to confirm the loop runs at all.
The order of statements inside the loop body matters. If the update to the loop variable happens before or after the wrong statement, the loop may produce incorrect results.
count = 1
while count <= 3:
count += 1 # Update happens before the print
print(count)
2 3 4
The programmer probably intended to print 1, 2, 3. But because count is updated before the print, the output is 2, 3, 4.
The corrected version:
count = 1
while count <= 3:
print(count)
count += 1 # Update happens after the print
1 2 3
When tracing loops, always pay attention to the order of statements inside the body.
Here is a complete example showing how to design a simple loop program from thinking to finished code.
Problem: Ask the user to enter five temperatures in Celsius and print the average.
count tracks how many temperatures have been entered (starts at 1, goes up to 5). total accumulates the sum (starts at 0). temperature holds the current value entered by the user.count = 1 and total = 0 before the loop. Loop while count <= 5. Inside the loop, get temperature, add it to total, add 1 to count. After the loop, calculate the average.count = 1
total = 0
while count <= 5:
temperature = float(input("Enter temperature " + str(count) + ": "))
total = total + temperature
count += 1
average = total / 5
print("Average temperature:", average)
Suppose the user enters: 20.0, 22.5, 19.0, 24.0, 21.5
| Iteration | count | Temperature | total after | count after |
|---|---|---|---|---|
| 1 | 1 | 20.0 | 20.0 | 2 |
| 2 | 2 | 22.5 | 42.5 | 3 |
| 3 | 3 | 19.0 | 61.5 | 4 |
| 4 | 4 | 24.0 | 85.5 | 5 |
| 5 | 5 | 21.5 | 107.0 | 6 |
After the loop: average = 107.0 / 5 = 21.4
Average temperature: 21.4
If the user enters 10.0 for all five temperatures, the total should be 50.0 and the average should be 10.0. Running the program mentally confirms this works.
+= 1, tracks how many times an event has occurred.for loop. Indefinite repetition depends on a condition that may change and typically uses a while loop.Read each program carefully. Answer the question below it without running the code.
x = 1
while x <= 4:
print(x * 2)
x += 1
What does this program print?
count = 10
while count > 0:
count -= 3
print(count)
What is the value of count when this program finishes?
total = 0
n = 1
while n < 6:
total += n
n += 2
print(total)
What does this program print? Hint: trace which values n takes.
word = ""
count = 0
while count < 4:
word += "ab"
count += 1
print(word)
What does this program print?
a = 5
b = 0
while a > 0:
b += a
a -= 1
print(b)
What does this program print?
Use a tracing table to trace each loop. Record every variable's value at the start of each iteration.
count = 1
while count <= 5:
if count % 2 == 0:
print(count, "is even")
else:
print(count, "is odd")
count += 1
| Iteration | count | Condition | Output |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 | |||
| 5 |
total?total = 100
count = 1
while count <= 4:
total = total - count
count += 1
print(total)
| Iteration | count | total before | total after | count after |
|---|---|---|---|---|
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 |
n = 1
while n < 5:
print(n * n)
n += 1
For each program, predict the complete output.
i = 0
while i < 3:
print("Line", i + 1)
i += 1
x = 2
total = 0
while x <= 8:
total += x
x += 2
print(total)
count = 5
while count >= 1:
print(count)
count -= 1
print("Done!")
n = 1
while n * n < 50:
print(n)
n += 1
count and total hold after each iteration of this loop.count = 0
total = 0
n = 1
while n <= 6:
if n % 3 == 0:
total += n
count += 1
n += 1
print("Count:", count)
print("Total:", total)
if block run?product = 1
n = 1
while n <= 5:
product = ____________
n += 1
print(product)
Answer these questions in complete sentences.
n = 0
while n < 10:
print(n)
n += 1
Each program below contains one or more errors. Identify each error, explain what it causes, and write a corrected version.
while count < 5:
print(count)
count += 1
count = 1
total = 0
while count < 6:
total = count
count += 1
print(total)
(This runs without an error message but produces the wrong answer. What is wrong?)
count = 1
while count <= 10:
print(count)
count += 1
(Hint: look carefully at the indentation.)
n = 1
while n > 0:
print(n)
n += 1
(What will happen when this runs?)
total = 0
n = 5
while n >= 1:
total += n
n -= 1
print(total)
(Two errors are present. Find both.)
5 4 3 2 1 Go!
6 x 1 = 6 6 x 2 = 12 6 x 3 = 18 ... 6 x 10 = 60
These questions reinforce concepts from earlier chapters alongside this chapter's material.
total = total + number. What type of programming pattern does this represent? What must be true about total before the loop begins? (Section 7.7)while score != -1. Is this an example of definite or indefinite repetition? Explain your reasoning. (Section 7.8)count = 1
while count <= 100:
print(count)
count += 1
Without running the program, how many lines of output will it produce? How do you know?
total = 0 before using it as an accumulator? What would happen if you forgot this initialization?Chapter 8 teaches Python's while loop in full detail. You have seen while loops used informally in this chapter, but Chapter 8 will give you a thorough understanding of exactly how loop conditions work, how to write loops that are guaranteed to stop, how to handle sentinel values and input validation, and how to use break and continue for special loop control situations. The conceptual foundation you have built in this chapter — loop bodies, iterations, loop variables, counters, accumulators, and tracing — applies directly to everything in Chapter 8. You are ready to move into the details.