Handle Zero Division Error In Python

In this tutorial I will show you how to handle zero division error in python programming after following this article you will be able handle divide by zero exception in python.
Zero division error is thrown when you try to divide a number by 0 as we learned in maths that we cannot divide a number by 0.
So in programming when a user try to divide a number by zero we have to handle it. So let’s see how to handle it in python.
Python Program To Handle Divide By Zero Exception
try:
numerator = float(input("Enter a numerator: "))
denominator = float(input("Enter a denominator: "))
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("Cannot divide by zero.")
Above is python program for zero division error handling. You can test this program by running it on your computer or using this online compiler.
As you can see in the program I have used try and except statements. In the try block it will try to execute the code if any error it will be caught in the except block.
We are particularly catching the ZeroDivisionError by specifying it in the except. If anyone tried to divide by 0 it will print cannot divide by zero below is an example output.
# If divide by number other then 0
Enter a numerator: 12
Enter a denominator: 6
2.0
#If divide by zero
Enter a numerator: 12
Enter a denominator: 0
Cannot divide by zero.
As you can see we successfully created this program you can use it in your python program to catch ZeroDivisionError.
Here are some more python tutorials for you:
- Python program to check composite number.
- Python program to calculate gst.
- Python program for employee salary calculation.
I hope you found this tutorial helpful and useful. Do share it with someone who needs it and if you want updates of our tutorials join our telegram channel.
Thanks for reading, Have a nice day 🙂