Open In App
Related Articles

ZeroDivisionError: float division by zero in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, we will see what is ZeroDivisionError and also different ways to fix this error.

What is ZeroDivisionError?

A ZeroDivisionError in Python occurs when we try to divide a number by 0. We can’t divide a number by 0 otherwise it will raise an error. Let us understand it with the help of an example. In this example, we are dividing a number from 0 and we can see that it raises a ZeroDivisionError.

Python3
a=20
b=0
print(a/b)

Output:

Hangup (SIGHUP)
Traceback (most recent call last):
  File "Solution.py", line 3, in <module>
    print(a/b)
ZeroDivisionError: division by zero

How to Fix ZeroDivisionError in Python

Below are the following ways by which we can fix ZeroDivisionError in Python:

Checking if the value we are dividing by is not 0

The ZeroDivisionError can be fixed by using a conditional statement in which we can check whether the denominator is zero or not. If the denominator is zero then we print that the Denominator is zero otherwise normal calculation would be performed.

Python3
a=15.0
b=5.0
if b==0:
  print("Denominator is zero")
else:
  print(a/b)

Output
3.0

In this another example, we are checking if the denominator is zero or not. In this case, the denominator is 0 but by using if-else condition, we will handle the error.

Python3
a=15.0
b=0
if b==0:
  print("Denominator is zero")
else:
  print(a/b)

Output
Denominator is zero

Python fix ZeroDivisionError using a try/except Statement

We have used an exception handler here that sets the result to 0 if such an error occurs, and it then prints the result, which will be 0

Python3
a = 16.0
b = 0

try:
    result = a / b
except ZeroDivisionError:
    result = 0

print(result) 

Output
0

Handling user input with Python try/except Statement

This code takes an input number from the user and attempts to divide ‘a’ by it. If the user enters a valid number, it calculates and prints the result. However, it has an exception handler that catches two types of errors: ZeroDivisionError (if the user enters 0) and ValueError (if the user enters something that’s not a valid number). In case of either error, it prints a message asking the user to enter a number greater than zero.

Python3
a = 18.0

try:
    b= int(input('Enter a number: '))
    ans = a / b
    print(f'Answer is: {ans}')
except (ZeroDivisionError, ValueError):
    print('Please enter number greater than zero')

Output:

Screenshot-2023-09-14-at-44239-PM
Division by zero

Last Updated : 29 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Article Tags :
Practice Tags :
Additional Information