Python Programs

Handle Zero Division Error In Python

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

    numerator = float(input("Enter a numerator: "))
    denominator = float(input("Enter a denominator: "))
    result = numerator / denominator
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

#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:

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 🙂