Ravindra BagaleCourses & study guides मराठी Track your progress

Python Errors and Exceptions: How to Use try, except, else and finally

P8.2 Common Python Errors in Data Work and Their Fixes

Why. A handful of errors cause 90% of beginner trouble. Know them by name.

Error Typical cause Quick fix
SyntaxError missing colon, bracket or quote check the line shown
IndentationError wrong spaces use 4 spaces consistently
NameError variable not defined or misspelled run the cell that defines it; check spelling
TypeError mixing types, e.g. "5" + 5 convert with int()/str()
ValueError bad content, e.g. int("abc") clean the text first
KeyError missing dict key / column check names, use .get()
IndexError position past the end check len()
ZeroDivisionError divide by 0 check the divisor first
FileNotFoundError wrong file name or folder check path and working folder

How to read this table: each row is one error type, why it usually happens and how to fix it.

How.

Fix an error step by step

  1. Read the error type.
  2. Find it in this table.
  3. Apply the quick fix.
  4. Run again; repeat if a new error shows.

Worked example A — A TypeError.

Step 1 — What we do. We add a text quantity to a number.

Step 2 — Type and run this code.

qty = "3"
print(qty + 2)

Step 3 — Output you should see.

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

Step 4 — What it means. Text and number cannot be added. Fix: int(qty) + 2.

Worked example B — An IndexError.

Step 1 — What we do. A list of 3 days, and we ask for the 5th.

Step 2 — Type and run this code.

days = ["Mon", "Tue", "Wed"]
print(days[4])

Step 3 — Output you should see.

IndexError: list index out of range

Step 4 — What it means. Valid indexes are 0, 1, 2. Check len(days) first.

Worked example C — A ZeroDivisionError.

Step 1 — What we do. Average order value for a day with no orders.

Step 2 — Type and run this code.

revenue = 0
orders = 0
print(revenue / orders)

Step 3 — Output you should see.

ZeroDivisionError: division by zero

Step 4 — What it means. Dividing by zero is not allowed. We handle this properly in the next section.

Ravindra Bagale's Tip

In Jupyter, a NameError often means you restarted the kernel and did not re-run the earlier cells. Use Run All.