🛠
Practice Projects · ★
Dictionaries · Functions · Input menus
Project 4 — Unit Converter
Convert between common units (length, weight, temperature) using a menu-driven CLI. Extend the conversion table with new units without changing the core logic.
dictfunctionmenuconversion
Duration
⏱ 1.5 hours
Level
📊 Basic Applied
Prerequisite
🎯 Basic Weeks 7, 9
OUTCOME
A data-driven unit converter that is easy to extend
What you'll learn
- 1Store conversion factors in a dict-of-dict structure
- 2Write a generic convert(value, from_unit, to_unit) function
- 3Present a clean numbered menu
- 4Handle temperature as a special case (formula-based)
Supported Units
| Category | Units |
|---|---|
| Length | mm, cm, m, km, in, ft, mi |
| Weight | mg, g, kg, lb, oz |
| Temperature | °C, °F, K |
Sample Session
text
Unit Converter
1) Length 2) Weight 3) Temperature 4) Quit
Choice: 1
From unit (mm/cm/m/km/in/ft/mi): km
To unit: mi
Value: 5
5 km = 3.1069 mi
Choice: 3
From unit (C/F/K): C
To unit: F
Value: 100
100°C = 212.0°F💻 Examples
Run these examples and check the output yourself.
solution.py— Data-driven unit converter
CODE
# All conversions to SI base unit (metre, gram, kelvin)
LENGTH = {"mm":1e-3,"cm":1e-2,"m":1,"km":1e3,"in":0.0254,"ft":0.3048,"mi":1609.344}
WEIGHT = {"mg":1e-3,"g":1,"kg":1e3,"lb":453.592,"oz":28.3495}
def convert_linear(value, from_u, to_u, table):
return value * table[from_u] / table[to_u]
def convert_temp(value, from_u, to_u):
# Convert to Kelvin first
if from_u == "C": k = value + 273.15
elif from_u == "F": k = (value - 32) * 5/9 + 273.15
else: k = value
if to_u == "C": return k - 273.15
if to_u == "F": return (k - 273.15) * 9/5 + 32
return k
while True:
print("\n1) Length 2) Weight 3) Temperature 4) Quit")
c = input("Choice: ").strip()
if c == "4": break
elif c == "1": tbl = LENGTH; cat = "Length"
elif c == "2": tbl = WEIGHT; cat = "Weight"
elif c == "3":
from_u = input(f"From (C/F/K): ").upper()
to_u = input(f"To (C/F/K): ").upper()
val = float(input("Value: "))
print(f"{val}°{from_u} = {convert_temp(val,from_u,to_u):.4f}°{to_u}")
continue
else: print("Invalid"); continue
units = list(tbl.keys())
from_u = input(f"From unit ({"/".join(units)}): ").lower()
to_u = input(f"To unit: ").lower()
val = float(input("Value: "))
result = convert_linear(val, from_u, to_u, tbl)
print(f"{val} {from_u} = {result:.6g} {to_u}")
📝 Exercises
Try them yourself first, then open the solution to compare.
Exercise 1
Build the unit converter
Goal: Implement the converter with length, weight, and temperature categories.
Requirements
- Data-driven design (dicts for length and weight)
- Temperature handled via formula
- Handles unknown units gracefully
- Loop until quit
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub ↗