
Debugging Code in Python: A Complete Guide to Fixing Common Errors
Python is one of the most versatile programming languages, but no matter how experienced you are, errors are unavoidable. The real skill lies in debugging code in Python efficiently—understanding what went wrong and applying the right fix.
In this guide, we’ll explore what debugging in Python means, review the most common errors, and show you practical ways to debug Python code like a professional.
Table of Contents
Syntax Error – The Typo Problem
Indentation Error – Whitespace Gone Wrong
1. SyntaxError – The Typo Problem
Occurs when Python cannot interpret your code due to formatting mistakes.
print("Hello World') # mismatched quotes
Pythonprint("Hello World')
^
SyntaxError: unterminated string literal (detected at line 1)
✅ Fix: Use matching quotes and check for missing colons.
print(“Hello World”)
2. IndentationError – Whitespace Gone Wrong
Python depends on indentation to structure blocks. Misaligned spaces or tabs lead to issues.
def greet():
print("Hello") # not indented
Pythonprint("Hello") # not indented ^ IndentationError: expected an indented block after function definition on line 1
✅ Fix: Stick to 4 spaces consistently.
def greet():
print(“Hello”)
3. NameError – Undefined Variables
Happens when trying to use a variable that doesn’t exist.
print(username)
Python---------------------------------------------------------------------------
NameError Traceback (most recent call last)
----> 1 print(username)
NameError: name 'username' is not defined
✅ Fix: Define variables before use and check spelling.
username=’Python’
print(username)
4. TypeError – Mixing Incompatible Types
Occurs when incompatible data types are combined.
age = 25
print("Age: " + age)
Python---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 age = 25
----> 2 print("Age: " + age)
TypeError: can only concatenate str (not "int") to str
✅ Fix: Convert explicitly with str()
, int()
, or float()
.
age = 25
print(“Age: ” + str(age))
5. IndexError – Out of Range
Triggered when accessing an invalid index in a list.
colors = ["red", "blue", "green"]
print(colors[3])
Python---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
1 colors = ["red", "blue", "green"]
----> 2 print(colors[3])
IndexError: list index out of range
✅ Fix: Use len(list) to stay within range. In python list index starts from 0 and ends with length -1
colors = [“red”, “blue”, “green”]
print(colors[2])
6. KeyError – Dictionary Lookup Fails
Raised when a dictionary key doesn’t exist.
student = {"name": "Alice"}
print(student["age"])
Python---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
1 student = {"name": "Alice"}
----> 2 print(student["age"])
KeyError: 'age'
✅ Fix: Use .get(key, default) for safe lookups.
student = {“name”: “Alice”}
student.get(‘name’)
print(student[“name”])
7. AttributeError – Wrong Method or Attribute
Occurs when calling a method that doesn’t exist for an object.
text = "hello"
text.push("world")
Python
✅ Fix: Use correct string methods like .find() or .replace(). You can write the string then “.” and pres “Tab” to know all the function from Jupyter notebook.
8. ValueError – Invalid Input
Happens when a valid type but invalid value is passed.
int("ten")
Python---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
----> 1 int('ten')
ValueError: invalid literal for int() with base 10: 'ten'
✅ Fix: Validate input before conversion or wrap in try/except.
try:
num = int("ten")
except ValueError:
num = 0
Python9. ZeroDivisionError – Dividing by Zero
Python doesn’t allow division by zero—it’s mathematically undefined. Occurs in financial or scientific calculations when denominators are unexpectedly 0.
x = 5 / 0
Python---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
----> 1 x=5/0
ZeroDivisionError: division by zero
✅ Fix: Always check denominator before dividing.
denominator = 0
if denominator != 0:
print(5 / denominator)
else:
print("Cannot divide by zero")
Python10. ImportError / ModuleNotFoundError – Missing Libraries
Triggered when modules are missing or misspelled. Occurs when Python can’t find the module you’re trying to import.
import numppy
Python---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
----> 1 import numppy
ModuleNotFoundError: No module named 'numppy'
✅ Fix: Install with pip install numpy and check spelling.
pip install numpy
Pro Debugging Tips
To truly debug Python code like an expert:
- Use print() for quick checks.
- Apply logging for structured debugging.
- Use IDEs like VS Code or PyCharm for breakpoints.
- Write unit tests with pytest to prevent repeat issues.
Final Thoughts
So, what is debugging in Python? It’s the process of identifying and fixing errors so your code runs smoothly. You need to debug and correct the error befording doing the testing. From SyntaxError to ZeroDivisionError, the key is learning how to debug the Python code systematically.
The next time you face an error, don’t panic. Treat it as a guide toward writing more reliable, efficient, and professional code.
Pingback: Unittest Vs PyTest: Ultimate Guide to Python Testing Framework