0

i was just writing this very simple script to calculate bmi in kg and cm. But it always prints 0. Any ideas why?

code:

weight = int(raw_input("Weight in kg: "))
length = int(raw_input("Length in cm: "))

def bmi():
    bmi = (weight) / (length * length)
    return bmi

print bmi()
Lagastic
  • 137
  • 1
  • 1
  • 9
  • Due to integer division in Python 2.x, `a / b == 0` for all `a < b` if both `a` and `b` are integers. – jonrsharpe Jan 09 '15 at 16:20
  • Um, you're using Py 2.7 and performing int division, so you'll always get an int. If you divide, say, 60 by 175*175, that's going to be less than 1, so it ends up zero. – Roberto Jan 09 '15 at 16:21
  • add this at the start: `from __future__ import division` – Roberto Jan 09 '15 at 16:21

1 Answers1

1

Type cast it to float. / will do integer division always.

That is

bmi = float(weight) / float(length * length)

It will print

Weight in kg: 10
Length in cm: 20
0.025

Or do

from __future__ import division
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • 1
    To improve on this, as floats are often imperfect ways to represent calculations such as BMI, consider using the `Decimal` module. – NDevox Jan 09 '15 at 16:29