Intro to Computer Science / Unit 6: Loops
6.5 Tracing Loops
Notes
Tracing means following a program step by step and recording variable values in a table. It is the best way to find what a loop does or where a bug is.
- Example:
x = 1thenwhile x < 20: x = x * 2thenprint(x). - Trace x: 1, 2, 4, 8, 16, 32. When x is 32, 32 < 20 is False, so the loop stops and
32is printed. - Watch for off-by-one errors:
range(5)stops at 4, and<versus<=changes the count. - Check the first pass, the last pass, and what happens if the loop runs zero times.
Practice
What does
x = 1; while x < 20: x = x * 2 end with after the loop, if x is printed?x goes 1, 2, 4, 8, 16, 32. At 16 the condition is still True, so it doubles once more to 32.
Start with
n = 10 and count = 0. A loop while n > 0: has the body n = n - 3 and count += 1. After the loop ends, print(count) runs. What is displayed?n goes 10, 7, 4, 1, -2. That takes 4 subtractions, so count is 4.
A student wants to print the numbers 1 through 10 but writes
for i in range(1, 10): print(i). What is the bug?Use range(1, 11) to include 10.
Ready for more? Take the Unit 6 test.