Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (18.4k points)

I am facing the error when I run the program using python:

The error is like this:

ZeroDivisionError: division by zero

The code 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

How can I avoid the error in python, my desired output is:

 z = 0

1 Answer

0 votes
by (36.8k points)
edited by

You need to catch the error and handle it:

try:

    z = x / y

except ZeroDivisionError:

    z = 0

Or you can check before doing the division:

if y != 0:

    z = x / y

else:

    z = 0

Later you can reduced to:

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

Want to gain end-to-end skills in Data Science with Python? Enroll today in this Data Science with Python Course and be a master in it 

Related questions

0 votes
1 answer
asked Mar 1, 2021 in Python by Rekha (2.2k points)
0 votes
1 answer
asked Sep 24, 2019 in Python by Sammy (47.6k points)

Browse Categories

...