Section 22.8 Debugging Loops
Here is an attempt to sum up all the even numbers from 0 to 100 that has a bug:
If you don’t already know what the correct answer should be, it is hard to tell that this program does not work correctly. How do we know what’s really going on in this program? If we had written it, what could we do to verify it?
Here are some things we could do to check our program:
Verify the algorithm on a smaller set of data that we can check by hand. Change the program to use range(0, 10, 2)
and try to sum up the even numbers from 0-10. This answer is small enough to be checked by hand.
Try running the program using Codelens one step at a time to check what it is doing. This is much easier if you have already modified the program to work on a smaller range of data.
Try printing out each number that we iterate through. Try adding this line to the start of the loop body (line 5): print("number is", number)
. This works with the full original range, but the output will be easier to read if you work with a smaller range of data.
Use those techniques to figure out what is wrong with the code and try to fix it.
Checkpoint 22.8.1.
What is the flaw in the original program?
The loop starts too early (skips one or more numbers at the start)
We would want to include 100.
The loop goes too far (adds one or more extra numbers at the end)
If we stop BEFORE 101, we include 100.
The loop stops too early (skips one or more numbers at the end)
Correct. To read 100, we need the upper bound of the range to be 101 or 102.
The loop is not actually iterating through even numbers
Try using one of the strategies… You should see only even numbers
You have attempted
of
activities on this page.