Python error: [ZeroDivisionError: division by zero]
I got an error when running my program using python: The error looks like this:
ZeroDivisionError: division by zero
The visualization of my program is similar to the following:
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
Here I want to ask how to avoid this error in python, my desired output is: z = 0
+3
markov zain
source
to share
2 answers
Catch the error and handle it:
try:
z = x / y
except ZeroDivisionError:
z = 0
Or check before dividing:
if y != 0:
z = x / y
else:
z = 0
The latter can be summarized as:
z = (x / y) if y != 0 else 0
+15
kindall
source
to share
You cannot divide by zero. 0 / 0
or n / 0
not defined. This causes Python to throw an error.
-1
Klaus D.
source
to share