BMI Calculator Python Code: How to Write It
The calculator for this page is switched off while it is checked. The formula is below, and the worked example in the article shows how to use it by hand.
This article shows you exactly how to write a BMI calculator in Python, including the formula, a complete code example, and how to handle common edge cases. You’ll get a working script that takes weight and height inputs, calculates Body Mass Index, and prints the corresponding weight category. The code uses the standard metric formula BMI = weight (kg) / height (m)², with clear steps for converting imperial units if needed.
Formula
The BMI formula is weight in kilograms divided by height in meters squared:
BMI = weight (kg) / [height (m)]²
If you measure height in centimeters, convert to meters first by dividing by 100. For imperial units, use BMI = 703 × weight (lb) / [height (in)]². The result is a number in kg/m², typically rounded to one decimal place.
Worked Example
Using the default values from the calculator above (weight = 70 kg, height = 170 cm):
- Convert height: 170 cm ÷ 100 = 1.70 m
- Square the height: 1.70² = 2.89 m²
- Divide weight by height squared: 70 ÷ 2.89 = 24.22
- Round to one decimal: BMI = 24.2 kg/m²
The category for 24.2 is “Normal weight� (18.5–24.9).
Basic Python Code
Here’s a simple script that asks the user for weight and height, then prints the BMI and category:
weight = float(input("Enter weight in kg: "))
height_cm = float(input("Enter height in cm: "))
height_m = height_cm / 100
bmi = weight / (height_m ** 2)
print(f"BMI: {bmi:.1f}")
This covers the core logic. The next sections show how to expand it into a more robust program.
Adding Categories
The World Health Organization (WHO) defines these adult BMI categories:
- Underweight: BMI < 18.5
- Normal weight: 18.5 – 24.9
- Overweight: 25 – 29.9
- Obesity class I: 30 – 34.9
- Obesity class II: 35 – 39.9
- Obesity class III: ≥ 40
In Python, use if/elif/else statements to check the BMI value and print the category. For example:
if bmi < 18.5:
category = "Underweight"
print(category)
Make sure to test the boundaries (18.5, 25, 30) to ensure your conditions use < and ≤ correctly.
Handling Imperial Units
If your user enters pounds and inches, convert to metric first or use the imperial formula. A common approach:
weight_lb = float(input("Weight in lb: "))
height_in = float(input("Height in in: "))
weight_kg = weight_lb * 0.453592
height_m = height_in * 0.0254
bmi = weight_kg / (height_m ** 2)
Alternatively, use the direct imperial formula: bmi = 703 * weight_lb / (height_in ** 2). Both give the same result if you use the correct conversion factors.
Input Validation and Error Handling
A robust BMI calculator should handle invalid inputs gracefully. Use try/except blocks to catch non-numeric entries, and check that weight and height are positive:
try:
weight = float(input("Weight (kg): "))
height = float(input("Height (cm): "))
if weight <= 0 or height <= 0:
print("Weight and height must be positive.")
else:
# calculate
pass
except ValueError:
print("Please enter a number.")
This prevents crashes and gives the user a clear message. For a GUI or web app, you’d also validate on the front end, but the principle is the same.
Common Mistakes
- Forgetting to convert cm to m: Using height in cm directly gives a wildly wrong BMI (10,000 times too large).
- Using pounds in the metric formula: Mixing units is the most frequent error. Always convert to kg and meters first.
- Rounding too early: Round only the final BMI, not intermediate values, to avoid small errors.
- Misplacing category boundaries: Ensure 18.5 is “Normal� not “Underweight�, and 25 is “Overweight� not “Normal�.
Test your code with known values: 70 kg and 170 cm should give 24.2. A person 1.75 m tall and 80 kg has BMI 26.1 (Overweight).
Limitations of BMI
BMI is a screening tool, not a diagnostic measure. It does not distinguish muscle from fat, so a muscular athlete may have a high BMI without excess fat. It also doesn’t account for age, sex, bone density, or fat distribution. For children and teens, BMI is interpreted using age- and sex-specific percentiles. For most adults, however, BMI correlates reasonably with body fat percentage and health risks, which is why it remains widely used in public health.
Frequently Asked Questions
How do I write a BMI calculator in Python?
Get weight in kg and height in cm as floats, convert height to meters, compute weight / (height_m ** 2), and print the result. Add if/elif statements for categories. That’s the entire core.
What is the correct BMI formula?
Metric: BMI = weight (kg) / height (m)². Imperial: BMI = 703 × weight (lb) / height (in)². Use the same units throughout – never mix.
How do I handle height in feet and inches in Python?
Convert feet and inches to total inches: total_in = feet * 12 + inches. Then use the imperial formula or convert to meters (1 in = 0.0254 m). For example, 5’9� = 69 in, then height_m = 69 * 0.0254.
What is a good BMI for an adult?
For most adults, a BMI between 18.5 and 24.9 is considered normal. Below 18.5 is underweight, 25–29.9 is overweight, and 30+ is obese. However, BMI is not a perfect health measure – consult a healthcare professional for a full assessment.
Can I use this code for a web app?
Yes, the logic is the same. You can write a Python function that takes weight and height as arguments and returns BMI, then call it from a Flask or Django view. For a static site, you could also translate the formula to JavaScript.
Why does my BMI calculator give a different result than online calculators?
Check your units. Most online calculators ask for weight in kg and height in cm, but some use feet/inches and pounds. Also verify you’re not rounding intermediate steps. If you’re using the correct formula, results should match to one decimal place.
Related
Formula used
in weight | Weight | kg | 70 | 0 in height | Height | cm | 170 | 0 out bmi | BMI | kg/m² | weight / (height/100)^2 | 1 out category | Category | - | (bmi < 18.5 ? "Underweight" : bmi < 25 ? "Normal" : bmi < 30 ? "Overweight" : "Obese") | 0
Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.