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

Unit Converter

Convert between units of length, weight, and more — organised with a clean lookup table. Learn data-driven design.

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

1 The Problem

We want a flexible unit converter: convert metres to feet, kilograms to pounds, and so on. Rather than a tangle of if-statements, we store the conversion factors in a table and look them up. It teaches data-driven design — using data to drive behaviour instead of hard-coded logic.

Where this shows up: any converter, pricing tables, tax brackets, configuration-driven features, lookup tables. Driving behaviour from data (not endless if-statements) is what makes software easy to extend.

2 How to Think About It

Think about how to avoid a mess of if-statements, before any code:

The plan — in plain English
1. Store the conversion factors in a table (a dictionary): “metres to feet” → 3.281, etc. → 2. Ask what to convert from, to, and the amount. → 3. Look up the right factor and multiply. → 4. Show the result. Adding a new conversion later means adding one line to the table — no new code.

Conversion table

Ask from, to, amount

Look up the factor

Multiply amount by factor

Show result

3 The Build — explained part by part

Here is the complete converter. Each part is explained below.

Pythonconvert.py
# A data-driven unit converter.

# Each conversion and its multiply-by factor.
factors = {
    ("m", "ft"): 3.281,
    ("ft", "m"): 0.3048,
    ("kg", "lb"): 2.205,
    ("lb", "kg"): 0.4536,
    ("km", "mi"): 0.6214,
    ("mi", "km"): 1.609,
}

print("Units: m, ft, kg, lb, km, mi")
from_unit = input("From: ")
to_unit = input("To: ")
amount = float(input("Amount: "))

key = (from_unit, to_unit)
if key in factors:
    result = amount * factors[key]
    print(f"{amount} {from_unit} = {result:.3f} {to_unit}")
else:
    print("Sorry, that conversion is not available.")
What each part does — in plain words
factors = { ("m", "ft"): 3.281, ... } — the heart of the design. The keys are pairs (from, to) and the values are what to multiply by. All the “knowledge” lives in this table, not in code.

key = (from_unit, to_unit) — build the lookup key from the user’s choices.

if key in factors: — check the conversion exists before trying it, so an unknown pair gives a friendly message instead of a crash.

result = amount * factors[key] — the entire conversion: look up the factor and multiply. One line handles every conversion in the table.

{result:.3f} — show three decimal places for precision.
Common mistakes — and how to avoid them
✗ Writing a separate if-branch for every conversion — unmaintainable as units grow.
✓ Store factors in a table and use one lookup for all of them.
✗ Not checking the key exists — an unknown pair crashes with KeyError.
✓ Guard with if key in factors first.
✗ Mixing up the direction — using the m→ft factor for ft→m.
✓ Store both directions as separate entries, or invert the factor.

4 Test & Prove Each Part

We test that conversions use the right factors and that unknown ones are handled safely.

Metres to feet uses the correct factor
A round-trip conversion returns close to the original
An unknown conversion is reported, not crashed
Pythontest_convert.py
FACTORS = {
    ("m", "ft"): 3.281,
    ("ft", "m"): 0.3048,
    ("kg", "lb"): 2.205,
}


def convert(amount, from_unit, to_unit):
    key = (from_unit, to_unit)
    if key in FACTORS:
        return amount * FACTORS[key]
    return None


def test_metres_to_feet():
    """1 metre is about 3.281 feet."""
    assert round(convert(1, "m", "ft"), 3) == 3.281


def test_round_trip():
    """Converting there and back is close to the start."""
    feet = convert(10, "m", "ft")
    back = convert(feet, "ft", "m")
    assert round(back) == 10


def test_unknown_conversion():
    """An unknown conversion returns None, not a crash."""
    assert convert(5, "m", "kg") is None

Run with pytest -v. The convert function is tiny because the table does the work. Adding a conversion needs only a new table entry — and the tests still pass.

5 The Interface

INPUTfrom, to, amounttwo units and a number
What it expects
From: m
To: ft
Amount: 10
OUTPUTconverted amountresult in target unit
What it returns
10.0 m = 32.810 ft

6 Run It & Automate It

Run it locally
python3 convert.py
Enter the units and amount to convert.

Jenkins runs the tests automatically — each line explained below.

What you should see when it works
Terminala real run
Units: m, ft, kg, lb, km, mi
From: m
To: ft
Amount: 10
10.0 m = 32.810 ft
If it breaks — how to fix it
🚨 KeyError on conversion.
That pair is not in the table. Add it, or check the key-exists guard is in place.
🚨 Results are inverted (too big/small).
You used the wrong-direction factor. Check the (from, to) order.
GroovyJenkinsfile
// Jenkinsfile — automated tests on every change.
pipeline {
    agent any
    stages {
        stage('Get the code') { steps { checkout scm } }       // download the code
        stage('Install') { steps { sh 'python3 -m venv venv && . venv/bin/activate && pip install pytest' } }  // test tool
        stage('Test') { steps { sh '. venv/bin/activate && pytest -v' } }   // run every test
    }
    post {
        success { echo 'All tests passed.' }
        failure { echo 'A test failed — look above.' }
    }
}
🎯 Try this next — make it yours
  1. Temperature. Add C↔F (needs a formula, not just a factor). (Teaches: when a table is not enough.)
  2. Auto-reverse. Generate the reverse factor automatically. (Teaches: building data from data.)
  3. List options. Show all available conversions. (Teaches: reading dictionary keys.)
What you learned
You learned data-driven design: storing knowledge in a lookup table (a dictionary keyed by pairs) so behaviour is driven by data, not endless if-statements. Adding features becomes adding data. Related: Variables & Types, Variables & Types.