Python Forum

Full Version: need small help for simple calculation
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Dear All,


how to calculate the below problem:

from __future__ import division

4/6

Out[3]: 0.6666666666666666


when I am trying for this - 

5/ 0= 

out: ZeroDivisionError: division by zero
how can solve it?

actually, i  don't known value of two variables 

e.g. [a] = ? ( may be 0, 1, 2, 3, 4,5)
       [ b]= ? (may be 0, 1, 2, 3,4,5)

want to calculate the division of a and b 

thanks in advance       Huh
You can't divide by 0 (this is a mathematical constraint, not specific to Python). So you have to test the value of the divisor and, if it is zero, issue some error message instead of doing the division.
You can do two two things.
Catch if the variable is zero

if var1 == 0 == var2:
    result = var1 / var2
Or catch the error

try:
    result = var1 / var2
except ZeroDivisionError:
    # do
The second way is faster but do not use it if not pass it in the class.
(Mar-09-2017, 09:01 AM)wavic Wrote: [ -> ]
if var1 == 0 == var2:
    result = var1 / var2

well var1 == 0 == var2 is True only when both var1 and var2 are 0 and that definitely does not solve the Division by zero error, but anyway that would be the least of the problems :-)

(Mar-09-2017, 09:01 AM)wavic Wrote: [ -> ]The second way is faster but do not use it if not pass it in the class.
Not sure what you mean by that...
Maybe Wavric ment: Use try/except clausule only if it was already explained in the class (assuming that this is a class homework)?
(Mar-09-2017, 12:32 PM)zivoni Wrote: [ -> ]Maybe Wavric ment: Use try/except clausule only if it was already explained in the class (assuming that this is a class homework)?

Aha, THAT class... Doh
Right! Anyway, I am not really sure if it is a faster method in all cases. For such a simple tasks like this. I can't test now.