Home / Python / Example programs / Basics

Python program: BMI calculator

Calculate body mass index (weight ÷ height²) and its category.

The code

def bmi(weight_kg, height_m):
    return weight_kg / height_m ** 2

def category(value):
    if value < 18.5:
        return "underweight"
    elif value < 25:
        return "healthy weight"
    elif value < 30:
        return "overweight"
    return "obese"

for w, h in [(52, 1.70), (70, 1.75), (88, 1.72)]:
    b = bmi(w, h)
    print(f"{w} kg, {h} m -> BMI {b:.1f} ({category(b)})")

Output

52 kg, 1.7 m -> BMI 18.0 (underweight)
70 kg, 1.75 m -> BMI 22.9 (healthy weight)
88 kg, 1.72 m -> BMI 29.7 (overweight)

How it works

One function calculates, another classifies with if/elif. Because each return ends the function, the last line only runs when no earlier test matched.

Python features used

Learn the ideas behind it in the free lesson Making Decisions.