Python Forum
need small help for simple calculation - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: need small help for simple calculation (/thread-2353.html)



need small help for simple calculation - desul - Mar-09-2017

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


RE: need small help for simple calculation - Ofnuts - Mar-09-2017

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.


RE: need small help for simple calculation - wavic - Mar-09-2017

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.


RE: need small help for simple calculation - buran - Mar-09-2017

(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...


RE: need small help for simple calculation - zivoni - Mar-09-2017

Maybe Wavric ment: Use try/except clausule only if it was already explained in the class (assuming that this is a class homework)?


RE: need small help for simple calculation - buran - Mar-09-2017

(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


RE: need small help for simple calculation - wavic - Mar-09-2017

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.