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
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
Complete source code
main.py
What each file does
- main.py
- The whole program: data classes, validation, the command loop and the report.
How to run it
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
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.txtand compare withtests/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
- 1Add a 'table' command that prints a conversion table for a range of values.
- 2Support plural and abbreviated forms automatically.
- 3Remember the last conversion so 'again 10' converts 10 with the same units.
Built and tested it yourself? Mark it to update your dashboard.