10.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 wrote 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 check 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.
A common feature of these techniques is that If you are writing a program that is going to calculate the GPA for 10,000 students, test it on just a few students and fix all the bugs you can.
Whenever possible, debug on as small a problem as possible. Debugging is hard. You can make it easier by limiting your debugging to small chunks of code (by testing parts of your program as you go) and debugging on small sets of data (testing your algorithm on just a few values instead of on the large program you want to solve.)