Python TypeError · Examples
Core Python

Python TypeError Examples

Short, runnable programs that show python typeerror: what it means and how to fix it in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python TypeError: What It Means and How to Fix It lesson.

1Missing or extra arguments

The message names the function and says exactly what was missing or how many arguments were too many. Compare it with the def line.

Missing or extra arguments
def greet(name, greeting):
    return f"{greeting}, {name}!"

try:
    greet("Asha")
except TypeError as err:
    print("TypeError:", err)

try:
    greet("Asha", "Hi", "!")
except TypeError as err:
    print("TypeError:", err)

print(greet("Asha", "Hi"))
Expected outputTypeError: greet() missing 1 required positional argument: 'greeting'
TypeError: greet() takes 2 positional arguments but 3 were given
Hi, Asha!

2A list can't be a dictionary key

Dictionary keys must be unchangeable (hashable). A list can change, so it is refused, but a tuple with the same values works.

A list can't be a dictionary key
visits = {}
point = [3, 4]

try:
    visits[point] = 1
except TypeError as err:
    print("TypeError:", err)

visits[tuple(point)] = 1
print(visits)
Expected outputTypeError: unhashable type: 'list'
{(3, 4): 1}

3A function that forgets to return

A function without a return statement gives back None. The TypeError appears later, on the line that uses the result, so trace the None back to the function.

A function that forgets to return
def order_total(prices):
    total = sum(prices)
    # forgot: return total

result = order_total([4, 6])
print("Got:", result)

try:
    print(result + 5)
except TypeError as err:
    print("TypeError:", err)

def order_total_fixed(prices):
    return sum(prices)

print(order_total_fixed([4, 6]) + 5)
Expected outputGot: None
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
15

4Accepting numbers or text with isinstance()

When a value might arrive as a string or a number, isinstance() lets you convert only when needed, so the maths never sees the wrong type.

Accepting numbers or text with isinstance()
def add_tax(amount):
    if isinstance(amount, str):
        amount = float(amount)
    return round(amount * 1.2, 2)

for value in [10, "25.50", 7.5]:
    print(repr(value), "->", add_tax(value))
Expected output10 -> 12.0
'25.50' -> 30.6
7.5 -> 9.0

Practise next

Python TypeError: What It Means and How to Fix It exercises → Back to the lesson

Python Data Types examplesPython Input and Output examplesPython Exceptions: try, except, else and finally examplesPython KeyError: What It Means and How to Fix It examples