Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error python : [ZeroDivisionError: division by zero]

Tags:

python

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

like image 433
markov zain Avatar asked Apr 24 '15 01:04

markov zain


People also ask

How do I fix ZeroDivisionError division by zero in Python?

The Python "ZeroDivisionError: float division by zero" occurs when we try to divide a floating-point number by 0 . To solve the error, use an if statement to check if the number you are dividing by is not zero, or handle the error in a try/except block.

What happens when you divide by zero in Python?

00:11 In mathematics, division by zero is undefined and it will cause a Python program to crash if you attempt it.

What kind of error is dividing by zero in Python?

In mathematics, division by 0 is undefined. Because of this, Python will issue the above error when your code tries to accomplish this undefined expression.

Which error will occur when dividing a number with zero?

Any number divided by zero gives the answer “equal to infinity.” Unfortunately, no data structure in the world of programming can store an infinite amount of data. Hence, if any number is divided by zero, we get the arithmetic exception .


2 Answers

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 
like image 114
kindall Avatar answered Oct 18 '22 19:10

kindall


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

like image 24
J. Antunes Avatar answered Oct 18 '22 21:10

J. Antunes