Python TypeError · Exercises
Core Python

Python TypeError Exercises

4 exercises that build on the Python TypeError: What It Means and How to Fix It lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A TypeError means Python was asked to do something with a value whose type doesn't support it, such as adding a number to text or calling something that isn't a function. By the end you can read a TypeError message and its traceback, recognise the five most common causes and fix each one. You will practise: Fix the score message; Predict the mixed total; Add up mixed prices; Two TypeErrors in one function.

0 / 4 completed

Python TypeError practice exercises

1. Fix the score message

Fix the bug Easy

This code should store "Your score is 87 points" in message and print it, but it raises a TypeError. Fix it without changing the value of score.

Your code
score = 87
message = "Your score is " + score + " points"
print(message)

2. Predict the mixed total

Predict the output Easy

Read the code and type exactly what it will print. Then press Check to compare.

Read this code
values = [10, "5", 2.5]
total = 0

for v in values:
    try:
        total = total + v
        print("added", v)
    except TypeError:
        print("skipped", repr(v))

print(total)

3. Add up mixed prices

Write code Medium

Prices arrive from a form as a mix of strings and numbers, e.g. ["2.50", 3, "4"]. Change total_cost(prices) so it converts every price to a float before adding, and returns the total rounded to 2 decimal places. An empty list should give 0.

Your code
def total_cost(prices):
    return sum(prices)

print(total_cost(["2.50", 3, "4"]))

4. Two TypeErrors in one function

Fix the bug Hard

count_points(points) should count how often each [x, y] point appears and return a dictionary whose keys are (x, y) tuples, e.g. {(1, 2): 2, (3, 4): 1}. There are two separate TypeErrors hiding here: fix the first, run again, then fix the second.

Your code
def count_points(points):
    counts = {}
    for point in points:
        counts[point] = counts.get(point, 0) + 1

result = count_points([[1, 2], [3, 4], [1, 2]])
print(result[(1, 2)])

Next lessonPython KeyError: What It Means and How to Fix It

More Python TypeError: What It Means and How to Fix It examples · All Python exercises