Chapter 8: Debugging your code

Debugging exercise

face Josiah Wang

Harry has just learned to write programs in Python.

He has been given the task of writing a program.

The program reads in an integer N from the user.

  • If N is an even number, the program will print out the sum of all even numbers from 1 to N (inclusive).
  • If N is an odd number, the program will print out the sum of all odd numbers from 1 to N (inclusive).

For example, when N is 10, the output should be 30 (2+4+6+8+10). When N is 9, the output should be 25 (1+3+5+7+9).

Harry got excited and jumped straight into coding, forgetting his lecturer’s advice to understand the problem and to think carefully about the algorithm first. He also did not follow his lecturer’s advice to “test as you code”, and so ended up writing the whole code in one go. When he finally ran his program after completing his code, he received a Python error, and did not know how to fix it.

Your task: get Harry’s code working correctly (and teach him the correct way to program!)

There are both syntax errors and semantic/logical errors in the code. Test and make sure that the corrected program works correctly for both odd and even numbers. Also, feel free to redesign the algorithm so that the code is more efficient and/or readable.

By the end of this exercise, you might have realised that debugging can sometimes be more than just ‘fixing the code’. Hopefully you will appreciate the importance of incremental development (or “test as you code”), and having a clear algorithm before starting to code! These will reduce the chances of you having to debug codes like these!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
number = int(input("Enter an integer: "))

i = 1

while i < nomber:
    if number % 2 = 0:
        total = total + number
    i = i + 1

print(total)