thecodex.expert · The Codex Family of Knowledge
Tier 1 · Beginner · Python Project

BMI Calculator

Calculate Body Mass Index from height and weight, and interpret the result. Learn formulas plus categorising a number.

🧠 Teaches how to think spoonfed, every age Last verified:

1 The Problem

We want a BMI calculator: take a person’s height and weight, compute their BMI, and tell them which category it falls into (underweight, normal, overweight). It teaches applying a formula and then categorising the result with ranges — a very common two-step pattern.

Where this shows up: health apps, any tool that turns a measurement into a category (credit scores into ratings, temperatures into warnings, marks into grades). Compute-then-classify is everywhere.

2 How to Think About It

Think about the two steps, before any code:

The plan — in plain English
1. Ask for height (in metres) and weight (in kg). → 2. Calculate BMI = weight ÷ (height × height). → 3. Categorise: under 18.5 is underweight, 18.5–25 is normal, over 25 is overweight. → 4. Show the number and the category.

under 18.5

18.5 to 25

over 25

Ask height and weight

BMI = weight / height squared

Which range?

Underweight

Normal

Overweight

3 The Build — explained part by part

Here is the complete BMI calculator. Each line is explained below.

Pythonbmi.py
# Calculate BMI and interpret it.

height = float(input("Height in metres (e.g. 1.75): "))
weight = float(input("Weight in kilograms: "))

# BMI formula: weight divided by height squared.
bmi = weight / (height * height)

# Categorise the result using ranges.
if bmi < 18.5:
    category = &quot;underweight&quot;
elif bmi < 25:
    category = &quot;normal weight&quot;
else:
    category = &quot;overweight&quot;

print(f&quot;Your BMI is {bmi:.1f} ({category}).&quot;)
What each part does — in plain words
height = float(...) and weight = float(...) — read both as decimals; height like 1.75 and weight like 68.5 both need decimals.

bmi = weight / (height * height) — the formula. The brackets ensure we square the height first, then divide. height * height is height squared.

if bmi < 18.5: ... elif bmi < 25: ... else: — categorise by range. The order matters: we check the lowest range first, so by the time we reach elif bmi < 25 we already know it is at least 18.5.

{bmi:.1f} — show the BMI to one decimal place, so 22.857 reads as a tidy 22.9.
Common mistakes — and how to avoid them
✗ Writing weight / height * height without brackets — that divides then multiplies, giving the wrong answer.
✓ Bracket the squared height: weight / (height * height).
✗ Checking ranges in the wrong order — checking < 25 before < 18.5 mislabels everyone.
✓ Check from lowest range upward so each elif can assume the earlier checks failed.
✗ Entering height in centimetres — 175 instead of 1.75 gives a tiny BMI.
✓ Use metres, or divide cm by 100.

4 Test & Prove Each Part

We test both the formula and the categorising against values we can verify by hand.

A known height and weight gives the right BMI
A low BMI is categorised as underweight
A mid-range BMI is categorised as normal
Pythontest_bmi.py
def calculate_bmi(weight, height):
    return weight / (height * height)


def categorise(bmi):
    if bmi < 18.5:
        return &quot;underweight&quot;
    if bmi < 25:
        return &quot;normal weight&quot;
    return &quot;overweight&quot;


def test_bmi_value():
    &quot;&quot;&quot;68 kg at 1.75 m is about 22.2.&quot;&quot;&quot;
    assert round(calculate_bmi(68, 1.75), 1) == 22.2


def test_underweight():
    &quot;&quot;&quot;A BMI of 17 is underweight.&quot;&quot;&quot;
    assert categorise(17) == &quot;underweight&quot;


def test_normal():
    &quot;&quot;&quot;A BMI of 22 is normal.&quot;&quot;&quot;
    assert categorise(22) == &quot;normal weight&quot;

Run with pytest -v. Splitting into calculate_bmi and categorise lets us test the maths and the classification separately — cleaner and clearer.

5 The Interface

INPUTheight + weighttwo decimals
What it expects
Height in metres: 1.75
Weight in kilograms: 68
OUTPUTBMI + categorynumber and interpretation
What it returns
Your BMI is 22.2 (normal weight).

6 Run It & Automate It

Run it locally
python3 bmi.py
Enter height and weight to see your BMI and category.

Jenkins runs the tests automatically — each line explained below.

What you should see when it works
Terminala real run
Height in metres (e.g. 1.75): 1.75
Weight in kilograms: 68
Your BMI is 22.2 (normal weight).
If it breaks — how to fix it
🚨 BMI is absurdly small or large.
Check your units — height in metres (1.75), weight in kg.
🚨 Everyone shows as the same category.
Your range checks are in the wrong order. Check the lowest threshold first.
GroovyJenkinsfile
// Jenkinsfile — automated tests on every change.
pipeline {
    agent any
    stages {
        stage(&#x27;Get the code&#x27;) { steps { checkout scm } }       // download the code
        stage(&#x27;Install&#x27;) { steps { sh &#x27;python3 -m venv venv && . venv/bin/activate && pip install pytest&#x27; } }  // test tool
        stage(&#x27;Test&#x27;) { steps { sh &#x27;. venv/bin/activate && pytest -v&#x27; } }   // run every test
    }
    post {
        success { echo &#x27;All tests passed.&#x27; }
        failure { echo &#x27;A test failed — look above.&#x27; }
    }
}
🎯 Try this next — make it yours
  1. Imperial units. Accept pounds and feet/inches too. (Teaches: unit conversion.)
  2. Finer categories. Split overweight into more bands. (Teaches: more ranges.)
  3. Healthy weight range. Tell them the weight range for a normal BMI at their height. (Teaches: rearranging a formula.)
What you learned
You learned the compute-then-classify pattern: apply a formula, then sort the result into categories with ordered range checks. This two-step shape appears in countless real tools. Related: Control Flow, Variables & Types.