Back to Blog Page
Programming

Python ZeroDivisionError: division by zero [Fixed]

Python ZeroDivisionError: division by zero [Fixed]

Written by Kolade Chris | Oct 26, 2024 | #Error #Python | 2 minutes Read

When working with numbers in Python, you might need to divide one number by another. It’s a common task but can quickly become tricky if you aren’t careful about what you’re dividing by.

The main culprit? ZeroDivisionError exception, or error (if you prefer it that way).

Let’s look at the cause of the ZeroDivision exception in Python and how to fix it.

What Causes the ZeroDivisionError Error in Python?

ZeroDivision error happens when you attempt to divide a number by 0:

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

This happens because in math, dividing by zero is undefined. TO account for that, Python throws the ZeroDivisionError exception when you try to devide a number by 0.

Here’s a better example with a function:

1
def divideTwoNums(x, y):
2
return x / y
3
4
print(divideTwoNums(6, 2)) # 3.0
5
print(divideTwoNums(4, 0)) # ZeroDivisionError: division by zero

How to Fix the ZeroDivision Error in Python

Fixing this error means you should make sure a number is not divided by 0. But since you might be accepting user inputs in your apps, it’s possible errors like ZeroDivision will happen.

To avoid ZeroDivisionError error, you can use an if statement to check for it and display a custom message to the user:

1
def divideTwoNums(x, y):
2
if y == 0:
3
return "You can't divide a number by zero!"
4
else:
5
return x / y
6
7
print(divideTwoNums(6, 2)) # 3.0
8
print(divideTwoNums(6, 0)) # You can't divide a number by zero!

The Python way to handle to prevent the ZeroDivisionError error is to use try…except instead of if…else:

1
def divideTwoNums(x, y):
2
try:
3
return x / y
4
except:
5
return "You can't divide a number by zero!"
6
7
print(divideTwoNums(6, 2)) # 3.0
8
print(divideTwoNums(6, 0)) # You can't divide a number by zero!

You can take that further by specifically looking for the ZeroDivisionError exception:

1
def divideTwoNums(x, y):
2
try:
3
return x / y
4
except ZeroDivisionError:
5
return "You can't divide a number by zero!"
6
7
print(divideTwoNums(6, 2)) # 3.0
8
print(divideTwoNums(6, 0)) # You can't divide a number by zero!

Thank you for reading!