33

I faced an error when I run my program using python: The error is like this:

ZeroDivisionError: division by zero

My program is similar to this:

In [55]:

x = 0
y = 0
z = x/y
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-55-30b5d8268cca> in <module>()
      1 x = 0
      2 y = 0
----> 3 z = x/y

ZeroDivisionError: division by zero

Thus, I want to ask, how to avoid that error in python. My desired output is z = 0

2
  • 2
    What value do you want for 1/0? For 0/0, any value at all makes some sense (because x/y==z still implies z**y==x), but for anything else divided by 0, no value makes sense (unless you have an infinite integer, and define infinity*0 == 0).
    – abarnert
    Apr 24, 2015 at 1:40
  • There is an error in your logic if you come across a situation where you are dividing by zero.
    – RufusVS
    Jul 28, 2021 at 1:42

4 Answers 4

90

Catch the error and handle it:

try:
    z = x / y
except ZeroDivisionError:
    z = 0

Or check before you do the division:

if y == 0:
    z = 0
else:
    z = x / y

The latter can be reduced to:

z = 0 if y == 0 else (x / y) 

Or if you're sure y is a number, which implies it`s truthy if nonzero:

z = (x / y) if y else 0
z = y and (x / y)   # alternate version
0
4

Returning zero instead of the division by zero error can be accomplished with a Boolean operation.

z = y and (x / y)

Boolean operations are evaluated left to right and return the operand, not True or False.

If y is 0, the value returned is y. If y is different from 0, the right side of the operation is executed and the value returned is x / y

1

ZeroDivisionError: division by zero

a = 10
b = 0
c = a/b

This would cause the type error because you are dividing by zero.


To solve this issue:

a = 10
b = 0
c = ( a / b ) if b != 0 else 0
print c
0
# we are dividing until correct data is given
executed = False
while not executed:
    try:
        a = float(input('first number --> '))
        b = float(input('second number --> '))
        z = a / b
        print(z)
        executed = True
    except ArithmeticError as arithmeticError:
        print(arithmeticError)
    except ValueError as valueError:
        print(valueError)
    except Exception as exception:
        print(exception)

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.