Chapter 6 Loop Statement
6.5 Loop Debugging¶
With branching and looping statement, the dynamic execution sequence of a program can be very different from the static program itself. Programming mistakes can happen when the Boolean conditions for loops and branches are incorrect, or certain factors in the dynamic control flow are overloaded. In order to find potential errors in a program, it is useful to trace the dynamic execution of the program, monitoring the values of variables in the process, and this task is called debugging.
Tracing refers to the monitoring of variable values in a dynamic execution process. It helps to understand the dynamic execution sequence of a piece of code. For example, suppose that guess_break.py intended to allow the user to enter up to 8 guesses. However, execution of the program only allows 7 guesses. In order to figure out the dynamic execution of the code, on can trace the values of guesses and limit in each loop iteration by adding a print statement.
# [guess_break.py]
import random
answer = random.randint(1, 100)
limit = 7
guesses = 0
while guesses < limit:
print ('TRACE:', guesses , limit)
guess = int(input('Your guess is: '))
guesses += 1
if guess == answer:
print ('You win!')
break
else:
if guess > answer:
print ('Too large ')
else:
print ('Too small ')
if not(guesses < limit):
print ('You lose.')
An execution of the program can lead to the following output:
TRACE: 0 7
Your guess is: 50
Too large
TRACE: 1 7
Your guess is: 25
Too large
TRACE: 2 7
Your guess is: 13
Too small
TRACE: 3 7
Your guess is: 17
Too small
TRACE: 4 7
Your guess is: 20
Too small
TRACE: 5 7
Your guess is: 23
Too large
TRACE: 6 7
Your guess is: 21
You lose!
The trace information shows that the value of guesses increases from 0 to 6 in 7 dynamic interactions. A further check of the looping condition reveals that the problem is that the value becomes 7 after the last iteration, dissatisfying guesses < limit. This can be fixed by setting the Boolean condition to guesses ≤ limit.
As another example of tracing, conditional_print.py, can be debugged by printing out the values of i at each iteration, ensuring the correct range of the loop variable.
# [conditional_print.py]
i=1
while i<100:
print ('TRACE:i=%d'%i)
if i%3==0:
print (i)
i+=1
After debugging, the trace print can be deleted or commented out.
© Copyright 2024 GS Ng.