Skip to content
IT Vizag
← Functions & Clean Code

▶ Sign up free for the video, slides & prompts

The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.

Checking…

Debugging step by step

Lesson 6 of 9 · 2 min read

print debugging, reading tracebacks and the Colab debugger.

🎬 Video version coming soon — read it now

Every programmer writes bugs. Good programmers find them quickly, with a routine instead of guesswork.

1. Reproduce it

Find the exact input that causes the problem. "It sometimes gives the wrong total" is hard. "It gives 0 when the list has one item" is half-solved.

2. Read the traceback bottom-up

🔒 Code example: sign up free (above) to unlock it.

The last line says what went wrong. The lines above show the chain of calls: line 14 called average, and line 3 inside it failed. So scores was empty. Why?

3. Print to see what's really happening

🔒 Code example: sign up free (above) to unlock it.

Most bugs come from a variable not holding what you think it holds. Print it, along with its type. Remove the debug prints when you're done.

4. Narrow it down

If a 50-line program fails, comment out half and check whether the bug remains. Keep halving. This is binary search, which you met in the guessing game, applied to bugs.

5. Use the debugger

Colab and VS Code have a debugger. In Colab:

🔒 Code example: sign up free (above) to unlock it.

At the pause, type a variable name to see its value, n to run the next line, c to continue and q to quit.

6. Rubber-duck it

Explain your code out loud, line by line, to a friend, a rubber duck or an empty chair. Very often you'll hear yourself say "...and then this adds one, wait, it shouldn't".

Classic beginner bugs

  • = where you meant ==
  • An off-by-one in range()
  • Forgetting int() around input()
  • A total reset inside a loop instead of before it
  • Code indented one level too deep or too shallow
  • A function that prints instead of returning
Tip: Before changing anything, write down what you expect to happen and what actually happened. The gap between them is where the bug lives.

In one line

Reproduce the bug, read the traceback from the bottom, print what variables really hold, and narrow it down one step at a time.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend