Exercises
Try...Except
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
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)Catch ValueError around the int() call.
values = ["10", "x", "30"]
total = 0
for text in values:
try:
total += int(text)
except ValueError:
pass
print(total)Exercise 2Passed
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"))Two except blocks: ZeroDivisionError and TypeError.
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "cannot divide by zero"
except TypeError:
return "those are not numbers"
print(divide(10, 2))
print(divide(10, 0))
print(divide(10, "x"))Exercise 3Passed
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")else runs when nothing was raised; finally runs either way.
def parse(text):
try:
value = int(text)
except ValueError:
print("could not parse")
else:
print("parsed", value)
finally:
print("done")
parse("42")
parse("x")