Skip to content

Module 6 · Loops and Iteration — topic 5 of 12

Loop execution

Trace exactly how Python runs a loop step by step: when the condition or next item is checked, how variables change each iteration, and how to use trace tables to predict and debug loops.

Beginner 12 min read·Lesson 74 of 306 in Python Programming

Learning objectives

  • Trace a loop iteration by iteration
  • Build a trace table of changing variables
  • Predict the final state after a loop

Definition

Trace exactly how Python runs a loop step by step: when the condition or next item is checked, how variables change each iteration, and how to use trace tables to predict and debug loops.

Introduction

To understand or debug a loop you need to see what happens in each iteration: which values the variables hold before and after the body, and when the loop decides to stop. Writing this down in a trace table is a powerful habit.

Why it matters

Most loop bugs are off-by-one errors, wrong starting values or updates in the wrong place. Tracing a few iterations by hand, or by printing the variables, reveals these problems quickly instead of guessing.

Detailed explanation

A for loop asks the iterable for its next item. If there is one, it binds the loop variable and runs the body; if not, the loop ends.

A while loop evaluates its condition; if true it runs the body, then goes back to the condition.

In a trace table, each row is one iteration and each column is a variable. Fill in the values after each step.

Accumulator pattern: a variable such as total starts with a neutral value (0 for sums, 1 for products, "" for text, [] for lists) and is updated every iteration.

After a for loop the loop variable keeps its last value. After a while loop the condition is false; this tells you the final state.

Printing the variables inside the loop with a label, such as print(f"i={i} total={total}"), is the program version of a trace table.

Syntax

Python
total = 0
for value in values:
total += value
print(f"value={value} total={total}")
  • Initialise the accumulator before the loop.
  • Update it in the body.
  • A temporary print shows the state each iteration.

Code examples

Watching a sum grow

Python
total = 0
for value in [5, 10, 15]:
total += value
print(f"value={value} total={total}")
Output
value=5 total=5
value=10 total=15
value=15 total=30

State after the loop

Python
for i in range(3):
pass
print("last i:", i)
n = 1
while n < 50:
n *= 3
print("n after while:", n)
Output
last i: 2
n after while: 81

More examples

Tracing a digit reversal

Python
n = 1234
reversed_n = 0
step = 0
print("step n digit reversed")
while n > 0:
digit = n % 10
reversed_n = reversed_n * 10 + digit
n //= 10
step += 1
print(f"{step:<5} {n:<5} {digit:<5} {reversed_n}")
print("Result:", reversed_n)
Output
step  n     digit reversed
1     123   4     4
2     12    3     43
3     1     2     432
4     0     1     4321
Result: 4321

Step-by-step explanation

  • Each iteration takes the last digit with % 10.
  • reversed_n * 10 + digit shifts the reversed number left and appends the digit.
  • n //= 10 removes the last digit, moving towards the stopping condition n > 0 being false.
  • The printed table shows exactly how the three variables change in each step.

Expected output

Running “Tracing a digit reversal” prints exactly:

TextOutput
step n digit reversed
1 123 4 4
2 12 3 43
3 1 2 432
4 0 1 4321
Result: 4321

Practical applications

  • Debuggers display variable values after each step, an automated trace table.
  • Exam questions on algorithms often ask for trace tables.
  • Logging inside loops helps diagnose data-processing jobs that give wrong totals.

Best practices

  • Trace the first two and last iterations by hand.
  • Print labelled state while debugging, then remove the prints.
  • Choose the correct neutral starting value for accumulators.

Common mistakes

Initialising inside the loop

Avoid

for v in values:
total = 0
total += v

Prefer

total = 0
for v in values:
total += v

Resetting total every iteration keeps only the last value.

Wrong neutral value for products

Avoid

product = 0
for v in values:
product *= v

Prefer

product = 1
for v in values:
product *= v

Multiplying anything by 0 gives 0.

Key takeaways

  • A loop repeats: get next item or test condition, then run the body.
  • Trace tables record variable values per iteration.
  • Accumulators start at a neutral value before the loop.

Try it yourself

  1. 1
    Build a trace table by hand for: total = 1; for i in range(1, 5): total *= i.
  2. 2
    Add a labelled print inside a while loop that counts how many times 100 can be divided by 2 before it drops below 1.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic