Functions · Lesson 23 of 27
Handling errors
When something goes wrong, Python raises an error (an exception) and stops. Common ones:
ValueError:int("abc")ZeroDivisionError:10 / 0IndexError:[1, 2][5]NameError: using a variable that doesn't exist
Use try / except to handle an error instead of crashing:
try:
n = int(input())
print(100 // n)
except ValueError:
print("Please enter a number")
except ZeroDivisionError:
print("Can't divide by zero")The code in try runs first. If an error happens, Python jumps to the matching except.
Read error messages from the last line. It tells you the error type and what went wrong.
Your task
Read two lines, a and b. Print a // b as a whole number.
- If
bis 0, printCannot divide by zero - If either value is not a number, print
Invalid input