Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python math division operation returns 0

print "------------ EPIDEMIOLOGY --------------\n"

def divide(A,B):
    return A/B

print " [Population] point Prevalence rate: "
A = input("Enter value for people with disease: " )
B = input("Enter value for total population: " )    
prevalence = divide(A,B)
print " Population Prevalence rate is: ",prevalence

A and B are user input and do not know if they are integers or floats. My answer is always 0 when i run this program. (I'm new in Python). How do i fix this or change in my function to avoid this problem?

the input part of code works, the math does not.

like image 615
Zane Avatar asked Dec 25 '22 10:12

Zane


2 Answers

You get the answer 0 because you are using Python2 and performing integer division. The fact that the population with disease cannot be higher than the total population is the reason that you get zero for every reasonable input (except when both values are the same).

Two fixes:

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

This will make sure that your function performs floating point division, not matter what numbers you pass to it. The second fix is that you should use raw_input in Python2 and cast the input to a number (float would be fine here).

a = float(raw_input("Enter value for people with disease: ")) # add error checking as needed
b = float(raw_input("Enter value for total population: " )) # add error checking as needed

The problem with input() is that it is equivalent to eval(raw_input()).

like image 85
timgeb Avatar answered Jan 08 '23 13:01

timgeb


In python 2.x is performed integer division. If dividend is less than divisor, the operation returns zero.
So you have two options:

Make one of operands as float:

def divide(A,B):
    return float(A)/B

import feature from Python 3

from __future__ import division

print "------------ EPIDEMIOLOGY --------------\n"

def divide(A,B):
    return A/B
like image 36
felipsmartins Avatar answered Jan 08 '23 14:01

felipsmartins