简体   繁体   中英

Error in BMI calculator

I am trying to calculator using classes in python. I tried to solve in this way:

class Person(object):
  def __init__(self,name,age,weight,height):
      self.name = name
      self.age = age
      self.weight = float(weight)
      self.height = float(height)
  def get_bmi_result(self):
      bmi = (self.weight)/float((self.height*30.48)*(self.height*30.48))
      print bmi
      if bmi <= 18.5:
        return "underweight"
      elif bmi>18.5 and bmi<25:
           return "normal"
      elif bmi>30:
           return "obese"
  pass

when I call the constructor: p = Person("hari", "25", "6", "30") and p.get_bmi_result it was returning <bound method Person.get_bmi_result of <Person object at 0x00DAEED0>> . I entered weight in kilograms and height in foots and in the calculation I tried to convert foot to centimeters.

You simply forgot to call your method:

p.get_bmi_result()

Note those () parenthesis. You only dereferenced the bound method object.

With the call, your code runs just fine:

>>> class Person(object):
...   def __init__(self,name,age,weight,height):
...       self.name = name
...       self.age = age
...       self.weight = float(weight)
...       self.height = float(height)
...   def get_bmi_result(self):
...       bmi = (self.weight)/float((self.height*30.48)*(self.height*30.48))
...       print bmi
...       if bmi <= 18.5:
...         return "underweight"
...       elif bmi>18.5 and bmi<25:
...            return "normal"
...       elif bmi>30:
...            return "obese"
... 
>>> p = Person("hari", "25", "6", "30")
>>> p.get_bmi_result()
7.17594027781e-06
'underweight'

Clearly your formula needs adjusting still, a BMI of 0.000007 is radically underweight for someone weighing 6 stone, even if only 30 inches(?) small.

Depending on what your weight and height unit sizes are, you may need to consult the BMI formula and adjust your method a little.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM