Python ZeroDivisionError: division by zero [Fixed]
Written by Kolade Chris | Oct 26, 2024 | #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
:
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:
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:
The Python way to handle to prevent the ZeroDivisionError
error is to use try…except
instead of if…else
:
You can take that further by specifically looking for the ZeroDivisionError
exception:
Thank you for reading!