The Python “ZeroDivisionError: float division by zero” is raised when we try to divide a float number and the second argument of this division is zero. You can solve this error by using an if statement or nesting your division within a try/except block.
Before going into details, let’s reproduce this error:
x = 20.0 #our float
y = 0
print(x/y) #ZeroDivisionError: float division by zero
Code language: Python (python)
This error is one of the many built-in errors for Python and exists because a division of a number by 0 tends toward infinity and this cannot be represented in a Python variable.
Table of Contents
Use an if statement
You can simply write your code inside an if statement to take care of this exception. This if statement will check that y (the second argument of our division) is not equal to zero to calculate the result. If it indeed equals to zero, we’ll assign 0 to our result, even though it theoretically cannot be calculated.
x = 20.0
y = 0
if y != 0:
result = x/y
print(f'The result is {result}')
else:
result = 0
print('The result cannot be calculated')
Code language: Python (python)
Our code gets longer, but it will run no matter the value of y. If you want to shorten it, you can use a shorter version:
x = 20.0
y = 0
result = y and x/y #0
Code language: Python (python)
This syntax is less known but actually easy to understand:
- Python first evaluates if y returns True. Remember that 0 is handled as a falsy value in Python:
z = 0
print(z == False) #True
Code language: Python (python)
- If y returns False (which is our case in our previous code), the value of y is returned (0)
- If it does not return False, then the result of x/y (our division) is returned
x = 20.0
y = 0
a = 10
b = 20
result_1 = y and x/y #0
result_2 = a and a/b #0.5
Code language: Python (python)
Use a try/except block
Another approach to fix this error is to handle the exception using a try/except block. You can either create a generic block catching all exceptions:
x = 20.0
y = 0
try:
result = x/y
except:
result = 0
Code language: Python (python)
Python will try to execute inside the try block and if it raises an error, it will then fall back to the except block. I’d recommend targeting a specific error type when you use this approach, to be sure to not catch another error accidentally:
x = 20.0
y = 0
try:
result = x/y
except ZeroDivisionError:
result = 0
Code language: PHP (php)