← Python for Beginners
0 of 27 lessons done0%

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 / 0
  • IndexError: [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 b is 0, print Cannot divide by zero
  • If either value is not a number, print Invalid input