TExcelTAD
Home › Basic Math & Pre-Algebra › Mini Project: Fraction Calculator and Unit Converter

Mini Project: Fraction Calculator and Unit Converter

In this project you will build two small tools that use exact arithmetic: a calculator that understands input like 3/4 + 1/6 or 2 1/3 * 3/8 and answers in lowest terms and as a mixed number, and a unit converter that handles length, mass, volume and temperature. At the end the two work together, so you can type 1 1/2 mi and get an exact answer in kilometres. The project uses most of the course: fractions and mixed numbers, GCF and LCM, decimals and rounding, ratios and units, and the floating-point lessons from Math in Computing.

What we are building: a few hundred lines of plain Python, built in six steps. Each step is a complete program you can run and change. Later steps repeat the functions they need from earlier ones, so every block runs on its own.

Step New concepts
1. Read a number parsing "3/4", "-5", "2 1/3" into numerator and denominator
2. Do the arithmetic by hand common denominators, GCF to simplify, checking against Fraction
3. Pretty output mixed numbers, signs, decimals
4. The calculator parsing a whole expression, error handling
5. The unit converter conversion factors through a base unit, temperature offsets
6. Putting it together exact unit conversion of fractional amounts

Note: The playground can't read keyboard input with input(), so each step runs its code on a list of sample inputs. To use the tools interactively on your own computer, wrap the last step in while True: line = input("> ").

Step 1: Read a number

A user can type a whole number (5), a fraction (3/4), a negative (-2/3) or a mixed number (2 1/3, meaning 2+132 + \frac{1}{3}). parse_number turns any of these into a pair (numerator, denominator). A mixed number w n/d becomes w⋅d+nd\frac{w \cdot d + n}{d}, the conversion from Mixed Numbers. For a negative mixed number such as -1 1/2, the minus applies to the whole value, giving −32-\frac{3}{2}.

python · try it yourself
def parse_number(text):
    text = text.strip()
    sign = -1 if text.startswith("-") else 1
    text = text.lstrip("-").strip()
    whole = 0
    if " " in text:                       # mixed number "w n/d"
        w, text = text.split(maxsplit=1)
        whole = int(w)
    if "/" in text:
        n, d = text.split("/")
        n, d = int(n), int(d)
    else:
        n, d = int(text), 1
    if d == 0:
        raise ZeroDivisionError("denominator is 0")
    return (sign * (whole * d + n), d)

for t in ["3/4", "5", "-2/3", "2 1/3", "-1 1/2", " 10/4 "]:
    print(f"{t!r:>10} -> {parse_number(t)}")
     '3/4' -> (3, 4)
       '5' -> (5, 1)
    '-2/3' -> (-2, 3)
   '2 1/3' -> (7, 3)
  '-1 1/2' -> (-3, 2)
  ' 10/4 ' -> (10, 4)

10/4 is not simplified yet. That is the job of the next step.

Step 2: Do the arithmetic by hand

Python's fractions.Fraction can do all of this for us, but writing it once by hand shows exactly what happens. Each operation produces an unsimplified result, and simplify divides top and bottom by their greatest common factor (GCF and LCM):

ab+cd=a⋅d+c⋅bb⋅dthen simplifyab−cd=a⋅d−c⋅bb⋅dab×cd=a⋅cb⋅dab÷cd=a⋅db⋅cmultiply by the reciprocal\begin{aligned} \frac{a}{b} + \frac{c}{d} &= \frac{a \cdot d + c \cdot b}{b \cdot d} && \text{then simplify} \\ \frac{a}{b} - \frac{c}{d} &= \frac{a \cdot d - c \cdot b}{b \cdot d} \\ \frac{a}{b} \times \frac{c}{d} &= \frac{a \cdot c}{b \cdot d} \\ \frac{a}{b} \div \frac{c}{d} &= \frac{a \cdot d}{b \cdot c} && \text{multiply by the reciprocal} \end{aligned}

Using the LCM of the denominators instead of b⋅db \cdot d gives smaller numbers along the way. Both give the same answer once simplified, and here we use the LCM for ++ and −-.

python · try it yourself
import math
from fractions import Fraction

def simplify(n, d):
    if d < 0:
        n, d = -n, -d
    g = math.gcd(n, d)
    return (n // g, d // g)

def calc(x, op, y):
    (a, b), (c, d) = x, y
    if op in "+-":
        m = math.lcm(b, d)
        a, c = a * (m // b), c * (m // d)
        raw = (a + c if op == "+" else a - c, m)
    elif op == "*":
        raw = (a * c, b * d)
    else:
        if c == 0:
            raise ZeroDivisionError("division by zero")
        raw = (a * d, b * c)
    return raw, simplify(*raw)

for x, op, y in [((3, 4), "+", (1, 6)), ((5, 6), "-", (3, 10)),
                 ((7, 3), "*", (3, 8)), ((2, 5), "/", (-4, 15))]:
    raw, result = calc(x, op, y)
    check = eval(f"Fraction(*{x}) {op} Fraction(*{y})")
    print(f"{x[0]}/{x[1]} {op} {y[0]}/{y[1]} = {raw[0]}/{raw[1]} = {result[0]}/{result[1]}   Fraction says {check}")
3/4 + 1/6 = 11/12 = 11/12   Fraction says 11/12
5/6 - 3/10 = 16/30 = 8/15   Fraction says 8/15
7/3 * 3/8 = 21/24 = 7/8   Fraction says 7/8
2/5 / -4/15 = 30/-20 = -3/2   Fraction says -3/2

With the LCM, 34+16\frac{3}{4} + \frac{1}{6} is 912+212=1112\frac{9}{12} + \frac{2}{12} = \frac{11}{12}, which is already in lowest terms. The division shows why simplify moves the sign: 30−20\frac{30}{-20} is the same number as −32-\frac{3}{2}, and by convention the denominator is kept positive.

Tip: The eval here only builds the check from our own test data. Never call eval on text a user typed. Step 4 parses the input properly instead.

Step 3: Pretty output

People like 1 5/12 better than 17/12. To turn an improper fraction into a mixed number, divide: the quotient is the whole part and the remainder is the new numerator. Work with the absolute value and put the sign back at the end. That avoids Python's floor division of negatives (-17 // 12 is −2, see Modular Arithmetic).

python · try it yourself
from fractions import Fraction

def mixed(fr):
    sign = "-" if fr < 0 else ""
    n, d = abs(fr.numerator), fr.denominator
    whole, rest = divmod(n, d)
    if rest == 0:
        return f"{sign}{whole}"
    if whole == 0:
        return f"{sign}{rest}/{d}"
    return f"{sign}{whole} {rest}/{d}"

def describe(fr):
    return f"{fr}  =  {mixed(fr)}  ≈  {float(fr):.4g}"

for fr in [Fraction(17, 12), Fraction(-17, 12), Fraction(8, 15), Fraction(24, 6), Fraction(-3, 2), Fraction(0)]:
    print(describe(fr))
17/12  =  1 5/12  ≈  1.417
-17/12  =  -1 5/12  ≈  -1.417
8/15  =  8/15  ≈  0.5333
4  =  4  ≈  4
-3/2  =  -1 1/2  ≈  -1.5
0  =  0  ≈  0

From here on we let Fraction do the arithmetic. It simplifies automatically and keeps the sign on the numerator, exactly like our Step 2 code.

Step 4: The calculator

Now the whole expression. A regular expression splits 2 1/3 * 3/8 into operand, operator and operand. An operand is a mixed number, a fraction or a whole number, each with an optional minus sign. The mixed-number form is tried first, so 2 1/3 isn't read as just 2. Bad input and division by zero become friendly messages instead of crashes.

python · try it yourself
import re
from fractions import Fraction

NUM = r"-?\d+\s+\d+/\d+|-?\d+/\d+|-?\d+"
EXPR = re.compile(rf"^\s*({NUM})\s*([-+*/×÷])\s*({NUM})\s*
quot;) def to_fraction(text): text = text.strip() neg = text.startswith("-") parts = text.lstrip("-").split() value = sum(Fraction(p) for p in parts) # "2 1/3" -> 2 + 1/3 return -value if neg else value def mixed(fr): sign = "-" if fr < 0 else "" whole, rest = divmod(abs(fr.numerator), fr.denominator) if rest == 0: return f"{sign}{whole}" return f"{sign}{whole} {rest}/{fr.denominator}" if whole else f"{sign}{rest}/{fr.denominator}" def calculate(line): m = EXPR.match(line) if not m: return "error: try something like 3/4 + 1/6" x, op, y = to_fraction(m[1]), m[2], to_fraction(m[3]) try: if op == "+": r = x + y elif op == "-": r = x - y elif op in "*×": r = x * y else: r = x / y except ZeroDivisionError: return "error: division by zero" return f"{r} ({mixed(r)})" for line in ["3/4 + 1/6", "2 1/3 * 3/8", "5 - 7/2", "-1 1/2 ÷ 3/4", "1/3 + 1/3 + 1/3", "4/5 / 0", "7/0 + 1"]: try: print(f"{line:<16} => {calculate(line)}") except ZeroDivisionError: print(f"{line:<16} => error: a denominator is 0")
3/4 + 1/6        => 11/12  (11/12)
2 1/3 * 3/8      => 7/8  (7/8)
5 - 7/2          => 3/2  (1 1/2)
-1 1/2 ÷ 3/4     => -2  (-2)
1/3 + 1/3 + 1/3  => error: try something like 3/4 + 1/6
4/5 / 0          => error: division by zero
7/0 + 1          => error: a denominator is 0

The calculator handles exactly one operation per line. Supporting longer expressions with the order of operations is a good extension, and the "Ideas" list at the end comes back to it.

Step 5: The unit converter

Every unit in a category is defined by how many base units it equals (see Units and Conversion). Base units are the metre, the kilogram and the litre. To convert, multiply up to the base unit and divide down to the target, so one table gives every pair of units. Temperature is different, because the scales also have different zero points. It needs a formula with an offset, not just a factor.

python · try it yourself
UNITS = {
    "length": {"mm": 0.001, "cm": 0.01, "m": 1, "km": 1000,
               "in": 0.0254, "ft": 0.3048, "yd": 0.9144, "mi": 1609.344},
    "mass":   {"g": 0.001, "kg": 1, "oz": 0.028349523125, "lb": 0.45359237},
    "volume": {"ml": 0.001, "l": 1, "tsp": 0.00492892159375, "cup": 0.2365882365,
               "gal": 3.785411784},
}

def find_category(unit):
    for cat, table in UNITS.items():
        if unit in table:
            return cat
    raise ValueError(f"unknown unit {unit!r}")

def convert(value, src, dst):
    if src in "CFK" and dst in "CFK":
        c = {"C": value, "F": (value - 32) * 5 / 9, "K": value - 273.15}[src]
        return {"C": c, "F": c * 9 / 5 + 32, "K": c + 273.15}[dst]
    cat = find_category(src)
    if find_category(dst) != cat:
        raise ValueError(f"cannot convert {src} to {dst}")
    return value * UNITS[cat][src] / UNITS[cat][dst]

for value, src, dst in [(5, "km", "mi"), (6, "ft", "m"), (12, "in", "cm"), (2.5, "lb", "kg"),
                        (500, "g", "oz"), (2, "cup", "ml"), (1, "gal", "l"),
                        (100, "C", "F"), (-40, "F", "C"), (300, "K", "C")]:
    print(f"{value:>6} {src:<3} = {convert(value, src, dst):>9.3f} {dst}")

try:
    convert(3, "kg", "m")
except ValueError as e:
    print("error:", e)
     5 km  =     3.107 mi
     6 ft  =     1.829 m
    12 in  =    30.480 cm
   2.5 lb  =     1.134 kg
   500 g   =    17.637 oz
     2 cup =   473.176 ml
     1 gal =     3.785 l
   100 C   =   212.000 F
   -40 F   =   -40.000 C
   300 K   =    26.850 C
error: cannot convert kg to m

All these factors are exact by definition: an inch is exactly 2.54 cm, and a pound is exactly 0.45359237 kg. The only errors come from storing them as binary floats, which is the subject of the last step.

Step 6: Putting it together

A recipe calls for 1 1/2 cup and a hiking map says 3/4 mi. Combining the two tools, each amount is parsed as a Fraction and so is each factor. Fraction("1609.344") is exactly 16093441000\frac{1609344}{1000}. The conversion therefore stays exact until we choose to round, and the result shows how small the float error from Step 5 really is.

python · try it yourself
from fractions import Fraction

FACTORS = {  # exact, as strings, in base units (m, kg, l)
    "length": {"cm": "0.01", "m": "1", "km": "1000", "in": "0.0254", "ft": "0.3048", "mi": "1609.344"},
    "mass": {"g": "0.001", "kg": "1", "oz": "0.028349523125", "lb": "0.45359237"},
    "volume": {"ml": "0.001", "l": "1", "tsp": "0.00492892159375", "cup": "0.2365882365"},
}
UNIT = {u: (cat, Fraction(f)) for cat, t in FACTORS.items() for u, f in t.items()}

def to_fraction(text):
    neg = text.strip().startswith("-")
    value = sum(Fraction(p) for p in text.strip().lstrip("-").split())
    return -value if neg else value

def convert_line(line):
    *amount, src, dst = line.split()               # "1 1/2 cup ml"
    amount = " ".join(amount)
    (c1, f1), (c2, f2) = UNIT[src], UNIT[dst]
    if c1 != c2:
        return f"cannot convert {src} to {dst}"
    exact = to_fraction(amount) * f1 / f2
    floaty = float(to_fraction(amount)) * float(f1) / float(f2)
    return f"{exact} {dst}  ≈ {float(exact):.6g}   float error {abs(float(exact) - floaty):.1e}"

for line in ["1 1/2 cup ml", "3/4 mi km", "2/3 ft in", "1/8 lb g", "3 tsp ml", "1 kg mi"]:
    print(f"{line:<14} -> {convert_line(line)}")
1 1/2 cup ml   -> 1419529419/4000000 ml  ≈ 354.882   float error 5.7e-14
3/4 mi km      -> 37719/31250 km  ≈ 1.20701   float error 0.0e+00
2/3 ft in      -> 8 in  ≈ 8   float error 0.0e+00
1/8 lb g       -> 45359237/800000 g  ≈ 56.699   float error 0.0e+00
3 tsp ml       -> 473176473/32000000 ml  ≈ 14.7868   float error 0.0e+00
1 kg mi        -> cannot convert kg to mi

Two thirds of a foot is exactly 8 inches: 23×12=8\frac{2}{3} \times 12 = 8. Fraction is guaranteed to give exactly 8, while the float version only lands on 8.0 here because its rounding errors happen to cancel. The float errors are zero or about 6×10−146 \times 10^{-14}, far smaller than anything a recipe or a map cares about. That is the practical lesson of Floating Point: floats are fine for measurements, but use Fraction or Decimal when you need exact answers, such as money or results to compare with ==.

Ideas to extend it

  • Allow longer expressions such as 1/2 + 1/3 × 3/4, with the order of operations. Hint: first split on + and −, then on × and ÷.
  • Accept a percent, so that 25% of 3/4 gives 3/16 (Percent of a Number).
  • Add an area category (m², ft², acre). Square factors convert squared units: 1 ft2=0.30482 m21\ \text{ft}^2 = 0.3048^2\ \text{m}^2.
  • Print a whole conversion table, for example cups ↔ millilitres for 14\frac{1}{4}, 13\frac{1}{3}, 12\frac{1}{2}, 23\frac{2}{3}, 34\frac{3}{4} and 1 cup.
  • Add pow: (2/3) ^ 3 and (4/9) ^ 1/2. When is the result still a fraction? (See nth Roots and Fractional Exponents.)

Test yourself

How does the project convert the mixed number 2132\frac{1}{3} to an improper fraction?

  1. 2+13=1\frac{2 + 1}{3} = 1
  2. 2⋅3+13=73\frac{2 \cdot 3 + 1}{3} = \frac{7}{3}
  3. 2⋅13=232 \cdot \frac{1}{3} = \frac{2}{3}
  4. 2⋅1+33=53\frac{2 \cdot 1 + 3}{3} = \frac{5}{3}

Why can't temperature use the same factor table as length and mass?

  1. Temperatures can be negative
  2. The scales have different zero points, so conversion needs an offset as well as a factor
  3. Kelvin is not a real unit
  4. Python floats can't store temperatures

What does simplify(30, -20) return in the Step 2 code?

  1. (3, -2)
  2. (-3, 2)
  3. (30, -20)
  4. (-30, 20)