← Python lessons

Debugging

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

Debugging means finding why a program does the wrong thing, fixing the cause, and checking the fix.

Use a repeatable process

  1. Decide what the program should print for a small example.
  2. Run it and note what it actually prints.
  3. Read any error message: its type and its line number.
  4. Find the first line where a value goes wrong.
  5. Change one thing at a time.
  6. Run the example again, then try other inputs.

Recognise the kind of problem

  • Syntax error: Python cannot read the code, so nothing runs. A missing colon after def or if is common.
  • Runtime error: the code starts but stops on one line.
  • Logic error: the code runs but gives the wrong answer.

This program has a runtime error:

print("start")
print("4" + 1)

start prints, then Python stops with this message:

TypeError: can only concatenate str (not "int") to str

The message names the line and says text and a number cannot be added. int("4") + 1 fixes it.

Find a logic error

This line should print the average of 3 and 5, which is 4:

print(3 + 5 / 2)

It prints 5.5. Division happens before addition, so only 5 is halved. Brackets fix the cause:

print((3 + 5) / 2)

Now it prints 4.0.

Inspect a value without changing the calculation

This loop should total the scores, but it prints 2, not 10. A temporary print() inside the loop shows each step:

total = 0for score in [3, 5, 2]:    total = score    print("score:", score, "total:", total)print(total)

total never grows: it is replaced by each score. The fix is total = total + score. Remove temporary prints when the bug is fixed.

Note: a return inside a loop ends the function as soon as that return executes. If it is inside an if, that may happen on a later pass or not at all. See Stopping a Search with return.

See also: Tracing Code, The range() Function, Parameters & Return.

Your turn

sum_up_to(limit) should add the numbers from 1 up to and including limit. Fix the bug so both calls print the right total.

🎯 Goal — make it print exactly:
6
1
def sum_up_to(limit):    total = 0    # fix the range so it includes limit    for number in range(1, limit):        total = total + number    return totalprint(sum_up_to(3))print(sum_up_to(1))

Advanced reading