Chapters
Python114 chapters

Exercises

Try...Except

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Add up the numbers, skipping anything that will not convert, and print the total.

Python
values = ["10", "x", "30"]
total = 0
# add what you can
print(total)
Exercise 2

Return a different message for dividing by zero and for non-numbers.

Python
def divide(a, b):
    # handle both problems
    return a / b

print(divide(10, 2))
print(divide(10, 0))
print(divide(10, "x"))
Exercise 3

Print parsed on success, could not parse on failure, and done either way.

Python
def parse(text):
    # try, except, else and finally
    pass

parse("42")
parse("x")