Body Mass Index can be calculated using a simple formula kg/m2, where the weight is represented in kilograms (kg) and the height is represented in metres (m). The article discusses the various ways to calculate BMI using python programming language.
Environment
The code is executed in the following environment,
- Operating System - Windows 10
- Python version - 3.10
- Editor - Visual Studio Code
The simplest of the programs is to directly input the required fields in the respective units, calculate and display the result. The code below does the same,
weight = float(input("Enter weight (kg): ")) height = float(input("Enter height (cm): ")) / 100 bmi = (weight / (height * height)) print(f"BMI is {bmi:.1f}") Output: ------- $ python.exe bmi.py Enter weight (kg): 74 Enter height (cm): 173 BMI is 24.7
However, the program can also do the conversion from one unit to another to ease the life of the user. The core calculation remains the same, so it can be moved to a method (or function). The modified version of the above program with a separate method for the calculation,
def calculateBMI(weightInKg, heightInMetre): return weightInKg / (heightInMetre ** 2) weight = float(input("Enter weight (kg): ")) height = float(input("Enter height (cm): ")) / 100 bmi = calculateBMI(weight, height) print(f"BMI is {bmi:.1f}") Output: ------- $ python.exe bmi.py Enter weight (kg): 75 Enter height (cm): 178 BMI is 23.7
Rather asking for input in specified units, the program can be little flexible and allow the user to input the height and weight values in a range of units. In such cases the conversion needs to happen within the program. The code accepts the following units of the format "<value> <unit>", space is required between value and unit.
- Kilograms (kg)
- Pounds (lbs)
- Centimetre (cm)
- Metre (m)
- Feet (ft)
- Inches (in)
The inputs entred by the user are validated using the following conditions,
- Format - 10 kg, 5 ft 10 in, 4 ft etc
- Numeric Value - entered input for values must be a number
- Units - entered units can be in the list of units supported
- Bounds - lower and upper bounds (can be tuned further based on requirements)
def calculateBMI(weightInKg, heightInMetre): return weightInKg / (heightInMetre ** 2) def lbsToKg(lbs): return lbs / 2.2046 def ftInchesToMetre(ft, inches): return ft * 0.3048 + inches * 0.0254 def cmToMetre(cm): return cm / 100 def exitWithMsg(msg): print(msg) exit(1) def getWeightInKg(weight): wArgs = weight.strip().split() # weight should be of format <weight> <unit> if len(wArgs) != 2: exitWithMsg(f"Invalid input - {weight}") # numerical value required for weight try: fWeight = float(wArgs[0]) except: exitWithMsg(f"Invalid value for weight - {weight}") # weight can be either in kg or lbs if wArgs[1].lower() not in ['kg', 'lbs']: exitWithMsg(f"Invald unit for weight - {wArgs[1]}") # conversion to desired unit if wArgs[1].lower() == 'lbs': fWeight = lbsToKg(fWeight) # lower and upper bounds if fWeight <= 0 or fWeight > 1000: exitWithMsg(f"Abnormal weight {weight} entered") return fWeight def getHeightInMetre(height): hArgs = height.strip().split() # height should be of format 160 cm/m or 5 ft 8 in count = len(hArgs) if count != 2 and count != 4: exitWithMsg(f"Invalid input - {height}") fHeight2 = 0 # numerical value required for height try: fHeight1 = float(hArgs[0]) if count == 4: fHeight2 = float(hArgs[2]) except: exitWithMsg(f"Invalid value for height {height}") # primary height unit can be in cm, m or ft hUnit = hArgs[1].lower() if hUnit not in ['m', 'cm', 'ft']: exitWithMsg(f"Invalid unit for height {hArgs[0]}") # secondary height unit can only be 'in' if count == 4 and hUnit != 'ft' and hArgs[3].lower() != 'in': exitWithMsg(f"Invalid units for height {hUnit} {hArgs[3]}") # conversion of units if hUnit == 'cm': fHeight1 = cmToMetre(fHeight1) elif hUnit == 'ft': fHeight1 = ftInchesToMetre(fHeight1, fHeight2) # lower and upper bounds if fHeight1 <= 0 or fHeight1 >= 3: exitWithMsg(f"Abnormal height {height} entered") return fHeight1 if __name__ == "__main__": print("Enter values with units like 60 kg/160 cm/5 ft 6 in") weight = input("Enter weight: ") weightInKg = getWeightInKg(weight) height = input("Enter height: ") heightInMetre = getHeightInMetre(height) bmi = calculateBMI(weightInKg, heightInMetre) print(f"BMI is {bmi:.1f}") Output: ------- $> python.exe bmi.py Enter values with units like 60 kg/160 cm/5 ft 6 in Enter weight: 10 kg Enter height: 0 cm Abnormal height 0 cm entered $> python.exe bmi.py Enter values with units like 60 kg/160 cm/5 ft 6 in Enter weight: 74 kg Enter height: 5 ft 8.11 in BMI is 24.7 $> python.exe bmi.py Enter values with units like 60 kg/160 cm/5 ft 6 in Enter weight: 60 kg Enter height: 5ft Invalid input - 5ft $> python.exe bmi.py Enter values with units like 60 kg/160 cm/5 ft 6 in Enter weight: 50 kg Enter height: 5 ft BMI is 21.5
Thanks for reading. Please leave suggestions/comments if any.
Comments
Post a Comment