Skip to content
Python project #03Beginner

Unit Converter

Convert length, mass, volume and temperature with natural commands like '5 km to mi', with aliases and helpful error messages.

Estimated time
~2 hours to build
Files
4 files · 265 lines
Technologies
Python 3, Dictionaries, f-strings

Introduction

Unit conversion is a perfect example of data-driven code: instead of writing a function per pair of units, every unit is stored as a factor relative to a base unit, so any conversion within a category is one multiplication and one division.

Problem statement

Accept commands of the form '<value> <unit> to <unit>'. Support length (mm to mi), mass (mg to t, oz, lb), volume (ml, l, cup, gal) and temperature (c, f, k), plus common word aliases. Reject unknown units, conversions between categories, non-numbers, negative lengths or masses and temperatures below absolute zero. A 'units' command lists everything; 'quit' ends the session with a count of conversions.

Objectives

  • Use dictionaries as conversion tables
  • Separate parsing, conversion and formatting into functions
  • Raise and handle ValueError with clear messages
  • Handle temperature as a special case

Features

  • Four categories and over 20 units
  • Word aliases such as 'miles' and 'celsius'
  • Thousands separators in input and output
  • Validation of units, categories and physical limits
  • Conversion counter on exit

Concepts demonstrated

  • Data-driven design
  • Exceptions for validation
  • String formatting
  • Command parsing

System architecture

FACTORS maps each category to units and their factor relative to a base unit (metre, kilogram, litre). convert checks that both units are in the same category and divides one factor by the other; temperatures go through Celsius in convert_temperature. handle parses one command and returns the message to print, so main only reads lines and prints results.

Folder structure

TextProject tree
unit-converter/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

111 lines
Pythonmain.py
"""Unit Converter: converts length, mass, volume and temperature from typed commands.
Commands:
<value> <unit> to <unit> e.g. 12.5 km to mi
units list the supported units
quit
"""
import sys
# Every unit is stored as a factor relative to the category's base unit.
FACTORS = {
"length": {"mm": 0.001, "cm": 0.01, "m": 1.0, "km": 1000.0, "in": 0.0254, "ft": 0.3048, "yd": 0.9144, "mi": 1609.344},
"mass": {"mg": 0.000001, "g": 0.001, "kg": 1.0, "t": 1000.0, "oz": 0.028349523125, "lb": 0.45359237},
"volume": {"ml": 0.001, "l": 1.0, "cup": 0.24, "gal": 3.785411784},
}
TEMPERATURE = {"c", "f", "k"}
ALIASES = {"metre": "m", "meter": "m", "kilometre": "km", "mile": "mi", "miles": "mi", "inch": "in", "foot": "ft",
"feet": "ft", "kilogram": "kg", "kilograms": "kg", "gram": "g", "grams": "g", "pound": "lb", "pounds": "lb",
"litre": "l", "liter": "l", "litres": "l", "celsius": "c", "fahrenheit": "f", "kelvin": "k"}
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip()
def normalise(unit: str) -> str:
unit = unit.lower()
return ALIASES.get(unit, unit)
def category_of(unit: str) -> str:
if unit in TEMPERATURE:
return "temperature"
for name, units in FACTORS.items():
if unit in units:
return name
raise ValueError(f"unknown unit '{unit}' (type 'units' to see the list)")
def convert_temperature(value: float, src: str, dst: str) -> float:
celsius = {"c": value, "f": (value - 32) * 5 / 9, "k": value - 273.15}[src]
if celsius < -273.15:
raise ValueError("that temperature is below absolute zero")
return {"c": celsius, "f": celsius * 9 / 5 + 32, "k": celsius + 273.15}[dst]
def convert(value: float, src: str, dst: str) -> float:
src_cat, dst_cat = category_of(src), category_of(dst)
if src_cat != dst_cat:
raise ValueError(f"can't convert {src_cat} ({src}) to {dst_cat} ({dst})")
if src_cat == "temperature":
return convert_temperature(value, src, dst)
if value < 0:
raise ValueError(f"{src_cat} can't be negative")
units = FACTORS[src_cat]
return value * units[src] / units[dst]
def tidy(number: float) -> str:
"""Up to four decimals, without trailing zeros, with thousands separators."""
text = f"{number:,.4f}".rstrip("0").rstrip(".")
return "0" if text in ("-0", "") else text
def handle(line: str) -> str:
parts = line.split()
if len(parts) != 4 or parts[2].lower() != "to":
return "Format: <value> <unit> to <unit>, e.g. 5 km to mi"
try:
value = float(parts[0].replace(",", ""))
except ValueError:
return f"'{parts[0]}' is not a number"
src, dst = normalise(parts[1]), normalise(parts[3])
try:
result = convert(value, src, dst)
except ValueError as error:
return f"Error: {error}"
return f"{tidy(value)} {src} = {tidy(result)} {dst}"
def main() -> None:
print("Unit Converter - type 'units' for the list, 'quit' to exit.")
count = 0
while True:
line = ask("> ")
if line is None or line.lower() in ("quit", "exit"):
break
if not line:
continue
if line.lower() == "units":
for name, units in FACTORS.items():
print(f" {name:<12}{', '.join(units)}")
print(f" {'temperature':<12}c, f, k")
continue
answer = handle(line)
if not answer.startswith(("Error", "Format", "'")):
count += 1
print(answer)
print(f"Goodbye! {count} conversion{'s' if count != 1 else ''} done.")
if __name__ == "__main__":
main()

What each file does

main.py
The whole program: data classes, validation, the command loop and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Unit Converter - type 'units' for the list, 'quit' to exit.
> units
length mm, cm, m, km, in, ft, yd, mi
mass mg, g, kg, t, oz, lb
volume ml, l, cup, gal
temperature c, f, k
> 5 km to mi
5 km = 3.1069 mi
> 12 in to cm
12 in = 30.48 cm
> 72.5 kg to lb
72.5 kg = 159.8351 lb
> 100 c to f
100 c = 212 f
> -40 f to c
-40 f = -40 c
> 0 k to c
0 k = -273.15 c
> 2 gal to l
2 gal = 7.5708 l
> 10 m to kg
Error: can't convert length (m) to mass (kg)
> five km to m
'five' is not a number
> 3 parsecs to km
Error: unknown unit 'parsecs' (type 'units' to see the list)
> -500 c to k
Error: that temperature is below absolute zero
> 1,250 m to km
1,250 m = 1.25 km
> to km
Format: <value> <unit> to <unit>, e.g. 5 km to mi
> quit
Goodbye! 8 conversions done.
Input
units
5 km to mi
12 in to cm
72.5 kg to lb
100 c to f
-40 f to c
0 k to c
2 gal to l
10 m to kg
five km to m
3 parsecs to km
-500 c to k
1,250 m to km
to km
quit

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • 5 km is 3.1069 mi, 100 c is 212 f and -40 f is -40 c.
  • Converting metres to kilograms, an unknown unit and a temperature below absolute zero all produce errors.
  • The session ends with '8 conversions done', counting only successful conversions.

Common errors

Results like 3.1068559611866697

Format with a fixed number of decimals and strip trailing zeros, as tidy() does.

KeyError for an unknown unit

Look the unit up in each category first and raise a ValueError with a helpful message.

Possible improvements

  • Add time, speed and data-size units
  • Accept compound input such as '5 ft 11 in'
  • Fetch live currency rates from an API

Additional challenges

  1. 1Add a 'table' command that prints a conversion table for a range of values.
  2. 2Support plural and abbreviated forms automatically.
  3. 3Remember the last conversion so 'again 10' converts 10 with the same units.

Built and tested it yourself? Mark it to update your dashboard.