In one of my CS courses, we had to code our own interpreter for a given language specification. After the lectures on BNF, lexers, and parsers, I decided to get some practice with a personal project.

I decided to write a simple, proof-of-concept unit converter in Python, which would be able to convert between different metric units, and even U.S. customary units. The unit converter also performs basic arithmetic operations on numbers, converting any units as necessary.

How It Works

The unit converter works by expressing each measurement by a value and a list of the seven base SI units: kg, m, s, K, A, mol, and cd.

For example, numbers would be represented by something like:

12 N

83 cm/s

The tables used to convert between units look like this:

Metric units (click to enlarge)

Customary units (click to enlarge)

Notice how the customary system has a lot of units for each base SI unit, and none of the scales are at all nice to work with (all the scales are used to convert to metric equivalent bases). This table is what allows us to convert between systems and units, and perform basic arithmetic operations on them. By storing everything in base SI units, it becomes easier to add, multiply, convert, etc. between different units and systems.

Installing as a Python Module

To install the module for importing into other scripts, you can put the files in a directory called unitconvert in one of these paths: