Beginner · Console Apps · Packages: standard library only
Project 9: Unit Converter
Create a command-line converter for length, weight, volume and temperature using lookup tables and clear error messages.
What you will learn
- Use dictionaries as lookup tables
- Convert through a base unit to avoid many formulas
- Raise and catch ValueError with helpful messages
- Parse a line of text with split()
- Format numbers with f-string format codes
Prerequisites
- Variables, numbers and f-strings
- Dictionaries
- Functions and return values
- while loops and break/continue
- Exceptions: try/except and raise
Packages and installation
Packages: standard library only.
Project structure
unit_converter/
main.pyStep-by-step build
- Choose base units. Every length is stored as a number of metres, every weight as grams and every volume as litres. To convert, multiply by the source factor and divide by the target factor.
- Build the FACTORS table. A dictionary of dictionaries groups units by category. Adding a new unit later is just one more line.
- Find the category. category_of() searches the table so we can refuse to convert, for example, kilometres to kilograms.
- Handle temperature separately. Temperature has offsets, not just factors, so convert_temp() goes through Celsius as a middle step.
- Write convert(). It looks up both categories, raises ValueError for unknown units or mismatched categories, and then does the maths.
- Write the input loop. Read a line like '5 km mi', split it into three parts, call convert, and print the answer with :.4g formatting.
- Test the edge cases. Try wrong units, text instead of a number, and a missing part. The program must show a message and keep running.
Complete source code
"""Unit Converter - length, weight, temperature and volume."""
# Each unit stores how many base units it equals (metre, gram, litre).
FACTORS = {
"length": {"m": 1, "km": 1000, "cm": 0.01, "mm": 0.001,
"mi": 1609.344, "ft": 0.3048, "in": 0.0254},
"weight": {"g": 1, "kg": 1000, "mg": 0.001, "lb": 453.59237, "oz": 28.349523},
"volume": {"l": 1, "ml": 0.001, "gal": 3.785412, "cup": 0.236588},
}
TEMPS = {"c", "f", "k"}
def category_of(unit):
"""Return the category name that contains the unit."""
if unit in TEMPS:
return "temperature"
for name, units in FACTORS.items():
if unit in units:
return name
return None
def convert_temp(value, src, dst):
"""Go through Celsius as the middle step."""
if src == "f":
celsius = (value - 32) * 5 / 9
elif src == "k":
celsius = value - 273.15
else:
celsius = value
if dst == "f":
return celsius * 9 / 5 + 32
if dst == "k":
return celsius + 273.15
return celsius
def convert(value, src, dst):
"""Convert value from src to dst, raising ValueError on bad input."""
a, b = category_of(src), category_of(dst)
if a is None:
raise ValueError(f"unknown unit '{src}'")
if b is None:
raise ValueError(f"unknown unit '{dst}'")
if a != b:
raise ValueError(f"cannot convert {a} to {b}")
if a == "temperature":
return convert_temp(value, src, dst)
table = FACTORS[a]
return value * table[src] / table[dst]
def help_text():
print("Type: <number> <from> <to> e.g. 5 km mi")
for name, units in FACTORS.items():
print(f" {name}: {' '.join(units)}")
print(" temperature: c f k")
print("Type 'quit' to stop.")
def main():
help_text()
while True:
try:
line = input("> ").strip().lower()
except EOFError:
break
if line in ("quit", "q"):
break
if line in ("help", "?"):
help_text()
continue
parts = line.split()
if len(parts) != 3:
print("Please enter: number from to")
continue
try:
value = float(parts[0])
result = convert(value, parts[1], parts[2])
except ValueError as err:
print("Error:", err)
continue
print(f"{value:g} {parts[1]} = {result:.4g} {parts[2]}")
print("Bye!")
if __name__ == "__main__":
main()
Code explanation
Conversion via a base unit
value * table[src] / table[dst] means: first change to the base unit, then to the target. With 7 length units you need 7 numbers, not 42 formulas.
Why temperature is special
Fahrenheit and Kelvin have different zero points, so multiplication alone is not enough. Going through Celsius keeps the code to 3 formulas.
Raising errors
convert() raises ValueError with a clear message. main() catches it and prints it, so the logic and the printing stay separate.
Number formatting
{value:g} removes useless zeros (5.0 becomes 5) and {result:.4g} keeps four significant digits, which suits both tiny and huge answers.
Input parsing
line.split() gives a list of words. float(parts[0]) raises ValueError for text such as 'abc', which the same except block handles.
Expected output
Type: <number> <from> <to> e.g. 5 km mi
length: m km cm mm mi ft in
weight: g kg mg lb oz
volume: l ml gal cup
temperature: c f k
Type 'quit' to stop.
> 5 km = 3.107 mi
> 100 c = 212 f
> 32 f = 0 c
> 2.5 kg = 5.512 lb
> 1 gal = 3785 ml
> Error: cannot convert length to weight
> Error: could not convert string to float: 'abc'
> Error: unknown unit 'xx'
> Please enter: number from to
> Please enter: number from to
> Type: <number> <from> <to> e.g. 5 km mi
length: m km cm mm mi ft in
weight: g kg mg lb oz
volume: l ml gal cup
temperature: c f k
Type 'quit' to stop.
> 0 k = -273.1 c
> Bye!
Common errors and solutions
Solution: The first word was not a number. The program catches this and prints an error; in your own code wrap float() in try/except.
Solution: Dictionary keys are case sensitive. Use .lower() on the input as the program does.
Solution: Do not multiply by a factor for temperatures. Use the formulas with the 32 and 273.15 offsets.
Solution: Use / (true division) not //, otherwise 5 m to km would give 0.
Ideas to improve the project
- Add more categories such as speed, area and time
- Load the unit tables from a JSON file
- Allow input like '5km to mi'
- Keep a history and show it with a 'history' command
- Add currency conversion with rates typed by the user
- Write unit tests for convert()