Sign in

Intro to Computer Science / Unit 6: Loops

6.5 Tracing Loops

3 practice questionsNot yet reviewed

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 = 1 then while x < 20: x = x * 2 then print(x).
  • Trace x: 1, 2, 4, 8, 16, 32. When x is 32, 32 < 20 is False, so the loop stops and 32 is 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?
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?
A student wants to print the numbers 1 through 10 but writes for i in range(1, 10): print(i). What is the bug?

Ready for more? Take the Unit 6 test.