Skip to content
Advertisement

Error python : [ZeroDivisionError: division by zero]

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement