MGU Computer Science Series — Programming with Python
Part II: Control Flow and Program Logic
Repetition · Iteration · Counters · Accumulators · Tracing
Chapter 7 of 30
7
MGU Computer Science Series  ·  Programming with Python  ·  Library Textbook Edition

Chapter 7:
Loops and
Repetition

How programs do the same work again and again — loop bodies, iteration, loop variables, counters, accumulators, and the discipline of tracing repeated execution

■ Part II of VII ■

■ 10 Sections  •  Chapter 7 of 30 ■

Builds on Chapters 5–6 — Booleans, comparisons, and conditional execution

Chapter Purpose

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.

Why This Chapter Comes First

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.

10Sections
12Key Terms
6Mini-Projects
30Total Chapters

Sections at a Glance

Sections 7.1 – 7.2
Why Programs Repeat: Motivation and Everyday Patterns
Scaling Work · Recognizing Repetition in Ordinary Life

Why Programs Repeat Work

Most 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.

Repetition in Everyday Algorithms

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.

Pattern 1
Repeat a Fixed Number of Times
Stirring batter fifty times. You know the exact count before you begin.
Pattern 2
Repeat While a Condition Is True
Pushing a door until it opens. You do not know how many pushes it will take.
Pattern 3
Repeat Once for Each Item
Reading every problem on a test. You work through a known collection, one item at a time.

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.

Sections 7.3 – 7.5
Loop Anatomy: Bodies, Iterations, and Loop Variables
Loop Header · Loop Body · Indentation · One Iteration at a Time

Loop Bodies

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
Output
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.

Critical Rule

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.")
Output
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.

Iteration

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:

  • "The loop iterates three times" means the body runs three times.
  • "On the second iteration" means during the second time the body runs.
  • "Iterating over a list" means going through each item in the list one at a time.

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.

Example 7.4.1
Counting iterations
count = 0
while count < 5:
    print(count)
    count = count + 1
  • Iteration 1count is 0. Is 0 < 5? Yes. Run the body.
  • Iteration 2count is 1. Is 1 < 5? Yes. Run the body.
  • Iteration 3count is 2. Is 2 < 5? Yes. Run the body.
  • Iteration 4count is 3. Is 3 < 5? Yes. Run the body.
  • Iteration 5count is 4. Is 4 < 5? Yes. Run the body.
  • Check againcount is 5. Is 5 < 5? No. Stop.

The loop completes five iterations. It prints the values 0, 1, 2, 3, and 4.

Loop Variables

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:

  • Keep track of how many times the loop has run.
  • Move through a range of numbers (1 through 10, for example).
  • Refer to each item in a collection one at a time.
  • Accumulate a running total.

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.

Example 7.5.1
A loop variable that changes what is printed
number = 1
while number <= 5:
    print(number * number)
    number = number + 1
Output
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.

Study Note

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.

Sections 7.6 – 7.7
Building Information Across Iterations: Counters and Accumulators
Counting Events · Running Totals · The Initialize-Update Pattern

Counters

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.

Example 7.6.1
Counting even numbers entered by a user

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.

The Counter Shortcut

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

Accumulators

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.

Example 7.7.1
Totaling a series of numbers
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:

Iterationnumber enteredtotal after adding
11010
22030
33060
440100
550150

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.

Beyond Addition

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.

Example 7.7.2
Accumulating a string
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.

Pattern Note

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.

Sections 7.8 – 7.9
Choosing and Verifying Loops
Definite vs. Indefinite Repetition · Tracing Tables

Definite and Indefinite Repetition

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.

Definite Repetition

A loop uses definite repetition when you know in advance exactly how many times it will iterate.

  • Print a message exactly ten times.
  • Process exactly thirty student scores.
  • Repeat an animation frame exactly sixty times.
  • Go through every number from 1 to 100.

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.

Indefinite Repetition

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.

  • Keep asking the user for input until they enter a valid number.
  • Keep reading data from a file until the file ends.
  • Keep running a simulation until a certain result occurs.
  • Keep prompting a menu until the user chooses to quit.

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 Important Distinction

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 Repeated Execution

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.

How to Trace a Loop

Procedure
Six steps to trace any loop
  • Step 1Write down the initial values of all variables before the loop starts.
  • Step 2Check the loop condition. If it is false, the loop does not run. If it is true, proceed.
  • Step 3Step through the loop body line by line, updating each variable as you go.
  • Step 4At the end of the body, return to step 2.
  • Step 5Repeat until the condition is false.
  • Step 6Note any output the loop produces on each iteration.

A tracing table organizes this process. Each row represents one iteration.

Example: Trace This Loop

x = 10
while x > 0:
    print(x)
    x = x - 3

Before the loop: x = 10

Iterationx at startCondition x > 0Outputx after update
110True107
27True74
34True41
41True1-2
5-2False(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.

A More Complex Example

total = 0
n = 1
while n <= 4:
    total = total + n
    n += 1

print(total)

Before the loop: total = 0, n = 1

IterationnCondition n <= 4total beforetotal aftern after
11True012
22True133
33True364
44True6105
55False———

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.

Section 7.10
Where Loops Go Wrong
Off-by-One Errors · Infinite Loops · Initialization · Condition Logic · Statement Order

Common Loop Thinking Errors

Beginners make certain kinds of mistakes with loops very consistently. Knowing about these in advance helps you recognize and fix them faster.

Off-by-One Errors

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.

Forgetting to Update the Loop Variable

Infinite Loop Risk

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?

Forgetting to Initialize Before the Loop

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?

Wrong Condition Direction

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.

Putting the Update in the Wrong Place

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)
Output
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
Output
1
2
3
Study Habit

When tracing loops, always pay attention to the order of statements inside the body.

Planning a Loop from Scratch

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.

Design Process
From problem to working program
  • Step 1Identify the repetition. You need to ask for a temperature five times and add each to a running total. This is definite repetition (exactly five times) with an accumulator.
  • Step 2Identify the variables. 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.
  • Step 3Design the loop. Initialize 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.

Step 4: Write the Code

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)

Step 5: Trace the Loop

Suppose the user enters: 20.0, 22.5, 19.0, 24.0, 21.5

IterationcountTemperaturetotal aftercount after
1120.020.02
2222.542.53
3319.061.54
4424.085.55
5521.5107.06

After the loop: average = 107.0 / 5 = 21.4

Output
Average temperature: 21.4

Step 6: Test with a Simple Case

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.

Chapter Summary

Key Terms

accumulator
A variable that builds up a running total of values across iterations of a loop. An accumulator is initialized before the loop and updated on each iteration.
counter
A variable that tracks how many times something has occurred. A counter is initialized to zero and increased by one each time the counted event happens.
definite repetition
A loop that runs a fixed, predetermined number of times. The number of iterations is known before the loop starts.
indefinite repetition
A loop that runs until a condition becomes false. The number of iterations is not known before the loop starts.
infinite loop
A loop whose condition never becomes false, causing the loop to run without stopping. Usually caused by forgetting to update the loop variable.
iteration
One complete run of a loop body from beginning to end.
loop body
The indented block of statements that runs on each iteration of a loop.
loop header
The line that begins a loop and specifies the condition or range that controls how many times the loop runs.
loop variable
A variable that changes value on each iteration of a loop, allowing the loop to do something different each time.
off-by-one error
A logic error in which a loop runs one time too many or one time too few, usually caused by using < instead of <= or vice versa.
repetition
Executing the same instructions more than once. Loops are the programming tool for repetition.
tracing table
A table used to trace loop execution, with one row per iteration showing the values of all relevant variables.
PracticeCode Reading

Read each program carefully. Answer the question below it without running the code.

7-R1
x = 1
while x <= 4:
    print(x * 2)
    x += 1

What does this program print?

7-R2
count = 10
while count > 0:
    count -= 3
print(count)

What is the value of count when this program finishes?

7-R3
total = 0
n = 1
while n < 6:
    total += n
    n += 2
print(total)

What does this program print? Hint: trace which values n takes.

7-R4
word = ""
count = 0
while count < 4:
    word += "ab"
    count += 1
print(word)

What does this program print?

7-R5
a = 5
b = 0
while a > 0:
    b += a
    a -= 1
print(b)

What does this program print?

PracticeCode Tracing

Use a tracing table to trace each loop. Record every variable's value at the start of each iteration.

7-T1. Trace this loop and show the output.

count = 1
while count <= 5:
    if count % 2 == 0:
        print(count, "is even")
    else:
        print(count, "is odd")
    count += 1
IterationcountConditionOutput
1
2
3
4
5

7-T2. Trace this loop. What is the final value of total?

total = 100
count = 1
while count <= 4:
    total = total - count
    count += 1
print(total)
Iterationcounttotal beforetotal aftercount after
1
2
3
4

7-T3. This loop is supposed to print the squares of 1 through 5. Trace it and determine whether it works correctly. If not, explain the error.

n = 1
while n < 5:
    print(n * n)
    n += 1
PracticePredict the Output

For each program, predict the complete output.

7-P1
i = 0
while i < 3:
    print("Line", i + 1)
    i += 1
7-P2
x = 2
total = 0
while x <= 8:
    total += x
    x += 2
print(total)
7-P3
count = 5
while count >= 1:
    print(count)
    count -= 1
print("Done!")
7-P4
n = 1
while n * n < 50:
    print(n)
    n += 1
PracticeCounter and Accumulator Practice

7-CA1. Write a tracing table showing what 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)
  1. How many iterations does the loop complete?
  2. How many times does the if block run?
  3. What does the program print?

7-CA2. A program is supposed to calculate the product (multiplication) of the numbers 1 through 5 (that is, 1 × 2 × 3 × 4 × 5 = 120). It uses an accumulator initialized to 1 (not 0, because multiplying by 0 would always give 0). Fill in the blank.

product = 1
n = 1
while n <= 5:
    product = ____________
    n += 1
print(product)

7-CA3. Write pseudocode (plain English step-by-step instructions, not Python) describing a loop that:

ReviewConcept Check

Answer these questions in complete sentences.

  1. 7-CC1. What is the difference between a counter and an accumulator? Give a real-world example of each.
  2. 7-CC2. What is the difference between definite and indefinite repetition? Give one example of a situation that calls for definite repetition and one that calls for indefinite repetition.
  3. 7-CC3. Why must the loop body be indented? What would happen if the indentation were removed?
  4. 7-CC4. If a loop variable is never updated inside the loop body, what will happen when you run the program?
  5. 7-CC5. A student writes the following loop and says "this prints the numbers 1 through 10." Is the student correct? Explain.
    n = 0
    while n < 10:
        print(n)
        n += 1
  6. 7-CC6. Explain in your own words what an off-by-one error is and describe one way it commonly occurs.
PracticeError Analysis

Each program below contains one or more errors. Identify each error, explain what it causes, and write a corrected version.

7-E1
while count < 5:
    print(count)
    count += 1
7-E2
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?)

7-E3
count = 1
while count <= 10:
    print(count)
count += 1

(Hint: look carefully at the indentation.)

7-E4
n = 1
while n > 0:
    print(n)
    n += 1

(What will happen when this runs?)

7-E5
total = 0
n = 5
while n >= 1:
    total += n
n -= 1
print(total)

(Two errors are present. Find both.)

PracticeShort Programming Tasks
  1. 7-SP1. Write a program that uses a loop to print the numbers from 1 to 20, one per line.
  2. 7-SP2. Write a program that uses a loop and an accumulator to calculate and print the sum of all integers from 1 to 100.
  3. 7-SP3. Write a program that asks the user to enter a number between 1 and 10. Use a loop to print a countdown from that number down to 1, then print "Go!".
    Example output (if the user enters 5)
    5
    4
    3
    2
    1
    Go!
  4. 7-SP4. Write a program that uses a loop to print the first ten multiples of a number entered by the user. For example, if the user enters 7, the program should print 7, 14, 21, 28, 35, 42, 49, 56, 63, 70.
  5. 7-SP5. Write a program that asks the user to enter exactly six numbers, uses a counter to count how many of those numbers are negative, uses an accumulator to total all the numbers, and after all six numbers are entered, prints the total and the count of negatives.
  6. 7-SP6. Write a program that prints a simple multiplication table for a number entered by the user. The table should show the number multiplied by 1 through 10.
    Example output (if the user enters 6)
    6 x 1 = 6
    6 x 2 = 12
    6 x 3 = 18
    ...
    6 x 10 = 60
ReviewReview Questions

These questions reinforce concepts from earlier chapters alongside this chapter's material.

  1. 7-RQ1. What is the purpose of indentation in a Python loop? How does Python use indentation to determine what is inside the loop and what is outside it? (Chapter 6 connection)
  2. 7-RQ2. A loop body contains this line: total = total + number. What type of programming pattern does this represent? What must be true about total before the loop begins? (Section 7.7)
  3. 7-RQ3. Explain in your own words what happens during one iteration of a loop. (Section 7.4)
  4. 7-RQ4. What is a tracing table, and why is it useful for debugging loops? (Section 7.9)
  5. 7-RQ5. A program uses the condition while score != -1. Is this an example of definite or indefinite repetition? Explain your reasoning. (Section 7.8)
  6. 7-RQ6. Look at this loop:
    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?
  7. 7-RQ7. A student says: "A counter and an accumulator do the same thing." Is this correct? What is the important difference between them?
  8. 7-RQ8. Why is it important to initialize total = 0 before using it as an accumulator? What would happen if you forgot this initialization?
Preview — Chapter 8
While Loops and Loop Control

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.

MGU Library Connection
  • Programming with Python — Appendix C: Python Syntax Quick Reference
  • Programming with Python — Appendix D: Common Python Error Messages
  • Programming with Python — Appendix E: Debugging Checklist
  • Companion resource: Loop Tracing Worksheet
  • Companion resource: Variable Tracing Worksheet
  • Next chapter: Chapter 8 — While Loops and Loop Control