I faced an error when I run my program using python: The error is like this:
JavaScript
x
2
1
ZeroDivisionError: division by zero
2
My program is similar to this:
JavaScript
1
14
14
1
In [55]:
2
3
x = 0
4
y = 0
5
z = x/y
6
---------------------------------------------------------------------------
7
ZeroDivisionError Traceback (most recent call last)
8
<ipython-input-55-30b5d8268cca> in <module>()
9
1 x = 0
10
2 y = 0
11
----> 3 z = x/y
12
13
ZeroDivisionError: division by zero
14
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:
JavaScript
1
5
1
try:
2
z = x / y
3
except ZeroDivisionError:
4
z = 0
5
Or check before you do the division:
JavaScript
1
5
1
if y == 0:
2
z = 0
3
else:
4
z = x / y
5
The latter can be reduced to:
JavaScript
1
2
1
z = 0 if y == 0 else (x / y)
2
Or if you’re sure y
is a number, which implies it`s truthy if nonzero:
JavaScript
1
3
1
z = (x / y) if y else 0
2
z = y and (x / y) # alternate version
3