Python Forum
need small help for simple calculation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
need small help for simple calculation
#1
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
Reply
#2
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.
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#3
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
(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...
Reply
#5
Maybe Wavric ment: Use try/except clausule only if it was already explained in the class (assuming that this is a class homework)?
Reply
#6
(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
Reply
#7
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020