Arithmetic operators · 4 / 18 Theory

Common arithmetic errors

Making mistakes is normal, and Python's error messages tell you exactly what happened. These are the three you will see most often when working with numbers.

ZeroDivisionError: dividing by zero

Dividing by zero makes no mathematical sense, and Python stops the program:

print(5 / 0)
# ZeroDivisionError: division by zero

It happens with /, // and %, and also if the divisor is 0.0.

ValueError: text that is not a number

It happens when you convert something that cannot be converted with int() or float():

int("abc")
# ValueError: invalid literal for int() with base 10: 'abc'

TypeError: mixing text and numbers

print("3" + 4)
# TypeError: can only concatenate str (not "int") to str

It usually means you forgot to convert the result of input().

How to read an error

Look at the last line: it gives the type of error and an explanation. The previous lines say which part of the program it happened in. With that you can almost always tell what to fix.

Avoiding the error: check first

The simplest way to avoid dividing by zero is to check the divisor before dividing:

x = int(input())
y = int(input())
if y == 0:
    print("You cannot divide by zero")
else:
    print(x / y)

Avoiding the error: try / except

Another option is to try the operation and catch the error if it happens. The program does not stop and you can show your own message:

x = int(input())
y = int(input())
try:
    print(x / y)
except ZeroDivisionError:
    print("You cannot divide by zero")

Practice in the exercise about division by zero.