Skip to content

Debugging

Debugging

Debugging is the process of identifying and fixing errors in your code.


Linting

  • Linting helps catch errors before running the code.
  • Tools:
  • Built-in support in IDEs/editors.
  • Command-line tools like pylint.
  • Following PEP8 guidelines ensures clean, readable code.

Reading Errors

Learn to understand common error messages: - SyntaxError → invalid Python syntax. - NameError → variable/function not defined. - TypeError → operation applied to the wrong type. - ZeroDivisionError → division by zero. - IndexError → accessing an invalid list index. - KeyError → accessing a missing dictionary key. - EOL (End of Line) → unexpected end of input.


PDB – Python Debugger

pdb is a built-in module that allows step-by-step debugging.

import pdb

def add(num1, num2):
    pdb.set_trace()   # set_trace lets you step through code line by line
    return num1 + num2

add(1, '2')              #gives type error, because we can't add int and str

Common PDB Commands

call parameters,

a(arguments) → show arguments of the current function n(next) → next line c(continue) → continue execution q(quit) → quit debugger l(list) → list source code around current line s(step into) → step into function calls r(return) → continue until function returns w(where) → show where you are in the stack help → show available commands clear → clear breakpoints

You can also change variable values while debugging by typing the variable name and assigning a new value.