Python math division operation returns 0 -


print "------------ epidemiology --------------\n"  def divide(a,b):     return a/b  print " [population] point prevalence rate: " = input("enter value people disease: " ) b = input("enter value total population: " )     prevalence = divide(a,b) print " population prevalence rate is: ",prevalence 

a , b user input , not know if integers or floats. answer 0 when run program. (i'm new in python). how fix or change in function avoid problem?

the input part of code works, math not.

you answer 0 because using python2 , performing integer division. fact population disease cannot higher total population reason 0 every reasonable input (except when both values same).

two fixes:

def divide(a,b):     if b == 0:         # decide should happen here     else:         return float(a)/b 

this make sure function performs floating point division, not matter numbers pass it. second fix should use raw_input in python2 , cast input number (float fine here).

a = float(raw_input("enter value people disease: ")) # add error checking needed b = float(raw_input("enter value total population: " )) # add error checking needed 

the problem input() is equivalent eval(raw_input()).


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -