Understanding
TypeErrors
Learn why Python raises TypeError, what causes it, and how to diagnose and fix the most common type mismatches in your code.
What Is a TypeError?
A TypeError is a runtime error that Python raises when you try to perform an operation on a value whose data type does not support that operation. It is Python's way of telling you: "these types don't work together."
Python's Type System
Every value in Python has a type. Python is dynamically typed: variables don't declare a type, but the values they hold always have one. Operations are only valid for compatible types.
Why TypeErrors Matter
TypeErrors are one of the most common errors beginners encounter. Understanding them helps you write robust code and debug faster. They reveal misunderstandings about how data flows through your program.
The Core Rule
When types are compatible, the operation succeeds. When they're incompatible, Python raises a TypeError.
Anatomy of the Error Message
TypeError vs ValueError
These two errors are often confused. The key difference: TypeError means the type itself is wrong, while ValueError means the type is correct but the actual value is inappropriate.
| TypeError | ValueError | |
|---|---|---|
| Cause | Wrong type for the operation | Right type, wrong value |
| Example | len(42) | int("hello") |
| Fix | Convert or change the type | Validate the value first |
| Analogy | Putting diesel in a gas car | Putting expired gas in a gas car |
The 5 Most Common Causes
How to Fix a TypeError
Example 1: String + Integer
Example 2: Non-Callable Object
Example 3: The None Trap
Type Conversion Flowchart
Wrong Argument Count
Common Mistakes
TypeError Cheat Sheet
| Error Message | Cause | Fix |
|---|---|---|
| unsupported operand type(s) | Mixing str with int/float | int(), float(), str() |
| 'X' object is not callable | Extra () on a non-function | Remove () |
| missing N required argument(s) | Too few arguments | Add args / defaults |
| 'NoneType' is not subscriptable | Using None as a list | Check return value |
| 'X' is not iterable | Looping over a non-sequence | Verify type first |
Question 1 of 5
What will the following code produce?
print("Score: " + 95)
Question 2 of 5
A student writes: x = [3,1,2].sort() then tries x[0]. What happens?
Question 3 of 5
Which of the following is the best way to fix this TypeError?
age = input("Age: "); born = 2024 - age
Question 4 of 5
You write list = [1, 2, 3] and later call list("hello"). What error do you get?
Question 5 of 5
What is the key difference between a TypeError and a ValueError?