ValueError · Exercises
Core Python

ValueError Exercises

4 exercises that build on the Python ValueError 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 ValueError means a function received a value of the correct type but with content it cannot accept, such as int() given the text "abc". By the end you can read a ValueError message, fix the six most common causes, and validate or raise ValueError in your own code. You will practise: Fix the price conversion; Predict which values are accepted; Validate a quantity; Average the valid numbers.

0 / 4 completed

ValueError practice exercises

1. Fix the price conversion

Fix the bug Easy

The text "12.50" should become the number 12.5 in price, and total should be the cost of 2 items. The code raises a ValueError. Fix the line that converts price_text.

Your code
price_text = "12.50"
price = int(price_text)
total = price * 2
print(total)

2. Predict which values are accepted

Predict the output Easy

Read the code and type exactly what it prints. Remember what int() accepts and what it rejects.

Read this code
values = ["10", "x", "7.5", " 4 ", "-2"]
total = 0

for v in values:
    try:
        total += int(v)
    except ValueError:
        print("bad", repr(v))

print(total)

3. Validate a quantity

Write code Medium

Write parse_quantity(text). Strip spaces, convert to int and return it. If the text is not a whole number, let the ValueError from int() happen. If the number is zero or negative, raise ValueError("quantity must be positive").

Your code
def parse_quantity(text):
    return int(text)

print(parse_quantity(" 3 "))

4. Average the valid numbers

Write code Hard

Write safe_average(values). values is a list of strings. Convert each with float(), ignoring the ones that raise ValueError. Return a tuple (average, skipped): the average of the valid numbers rounded to 2 decimals, and the list of skipped strings in their original order. If no value is valid, raise ValueError("no valid numbers").

Your code
def safe_average(values):
    return (0, [])

print(safe_average(["10", "x", "20.5"]))

Next lessonPython AttributeError

More Python ValueError examples · All Python exercises