Lesson 5
Writing Reusable and Self-explanatory Programs
Chapter 10: Debugging and testing
Debugging exercise
Now, let’s get you to practice more debugging.
Below is a program that does not produce the expected output. Make it work correctly!
Hint: You need to add two things to the code.
You might notice a few things in the code that we have not yet covered - this is a sneak preview for the next lesson! See if you can understand what the code is doing just by reading it! It is also possible to write this code only with what we have covered so far (you can try this in your spare time).
Sample expected output:
user@MACHINE:~$ python prime_sum.py
Please enter an integer: 1
2
user@MACHINE:~$ python prime_sum.py
Please enter an integer: 2
5
user@MACHINE:~$ python prime_sum.py
Please enter an integer: 3
10
user@MACHINE:~$ python prime_sum.py
Please enter an integer: 4
17
user@MACHINE:~$ python prime_sum.py
Please enter an integer: 5
28
user@MACHINE:~$ python prime_sum.py
Please enter an integer: 6
41
The code to fix:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
|
No peeking at the solutions before fixing it yourself! 👀
Solution to the above problem:
- Add
return total
to Line 33 (with a 4-space indentation) - Add
current_number += 1
to Line 25 (with an 8-space indentation)