Case Study: Building a Unit Converter

The Scenario

You're studying abroad in Europe next semester. You're American and you think in Fahrenheit, miles, and pounds. Your European friends think in Celsius, kilometers, and kilograms. Rather than Googling conversions every five minutes, you decide to build a Python program that handles the most common conversions you'll need.

This case study walks through the design and implementation of a multi-unit converter using everything from Chapter 3: variables, types, expressions, type casting, and f-string formatting.

Planning the Converter

Before writing code, let's apply computational thinking (Chapter 1) and decompose the problem:

  1. Get user input — what kind of conversion, and what value?
  2. Convert the value — apply the right formula
  3. Display the result — formatted cleanly

For now (without conditionals from Chapter 4), we'll build separate converters for each unit type and combine them into one program later.

Version 1: Temperature Converter

The conversion formulas: - Fahrenheit to Celsius: C = (F - 32) * 5 / 9 - Celsius to Fahrenheit: F = C * 9 / 5 + 32

# temperature_converter.py
print("=" * 40)
print("  Temperature Converter")
print("=" * 40)

# Get input
fahrenheit_str = input("\nEnter temperature in °F: ")
fahrenheit = float(fahrenheit_str)

# Convert
celsius = (fahrenheit - 32) * 5 / 9

# Display result
print(f"\n{fahrenheit:.1f}°F = {celsius:.1f}°C")

# Provide context
print(f"\nFor reference:")
print(f"  Water freezes at 32.0°F / 0.0°C")
print(f"  Water boils at  212.0°F / 100.0°C")
print(f"  Body temp is    98.6°F / 37.0°C")

Sample run:

========================================
  Temperature Converter
========================================

Enter temperature in °F: 72

72.0°F = 22.2°C

For reference:
  Water freezes at 32.0°F / 0.0°C
  Water boils at  212.0°F / 100.0°C
  Body temp is    98.6°F / 37.0°C

Design Decisions

Notice several things about this code:

  1. We used float() for type casting, not int(). Temperatures can have decimals (98.6°F is body temperature).
  2. We stored the intermediate result in celsius rather than computing it inside the f-string. This is more readable and easier to debug.
  3. We added context — the reference temperatures help the user interpret the result. Is 22°C hot or cold? The reference table makes it clear.

Version 2: Distance Converter

# distance_converter.py
print("=" * 40)
print("  Distance Converter")
print("=" * 40)

# Conversion factors
MILES_TO_KM = 1.60934
FEET_TO_METERS = 0.3048
INCHES_TO_CM = 2.54

# Get input
miles_str = input("\nEnter distance in miles: ")
miles = float(miles_str)

# Convert
kilometers = miles * MILES_TO_KM
feet = miles * 5280
meters = feet * FEET_TO_METERS

# Display
print(f"\n{'Conversion Results':^40}")
print(f"{'─' * 40}")
print(f"  {'Miles:':<20}{miles:>12,.2f}")
print(f"  {'Kilometers:':<20}{kilometers:>12,.2f}")
print(f"  {'Feet:':<20}{feet:>12,.0f}")
print(f"  {'Meters:':<20}{meters:>12,.2f}")

Sample run:

========================================
  Distance Converter
========================================

Enter distance in miles: 26.2

          Conversion Results
────────────────────────────────────────
  Miles:                       26.20
  Kilometers:                  42.16
  Feet:                      138,336
  Meters:                  42,163.78

Design Decisions

  1. Constants are named in ALL_CAPSMILES_TO_KM, FEET_TO_METERS. This follows PEP 8 convention and makes it clear these values don't change.
  2. We used f-string alignment (:<20 for left-align, :>12 for right-align) to create a clean columnar layout.
  3. We used the thousands separator (:,) for large numbers like feet and meters.

Version 3: Weight Converter with Multiple Outputs

# weight_converter.py
print("=" * 40)
print("  Weight Converter")
print("=" * 40)

# Conversion factors
LBS_TO_KG = 0.453592
KG_TO_LBS = 2.20462
OZ_PER_LB = 16

# Get input
pounds_str = input("\nEnter weight in pounds: ")
pounds = float(pounds_str)

# Convert
kilograms = pounds * LBS_TO_KG
ounces = pounds * OZ_PER_LB
grams = kilograms * 1000

# Display
print(f"\n{'─' * 40}")
print(f"  {pounds:.1f} pounds is equivalent to:")
print(f"{'─' * 40}")
print(f"  {kilograms:>10.2f} kilograms")
print(f"  {grams:>10.1f} grams")
print(f"  {ounces:>10.1f} ounces")
print(f"{'─' * 40}")

# Practical comparison
print(f"\n📊 For context:")
print(f"  A liter of water weighs about 2.2 lbs / 1.0 kg")
print(f"  A US quarter weighs about 0.2 oz / 5.7 g")

Sample run:

========================================
  Weight Converter
========================================

Enter weight in pounds: 155

────────────────────────────────────────
  155.0 pounds is equivalent to:
────────────────────────────────────────
       70.31 kilograms
    70306.8 grams
     2480.0 ounces
────────────────────────────────────────

📊 For context:
  A liter of water weighs about 2.2 lbs / 1.0 kg
  A US quarter weighs about 0.2 oz / 5.7 g

Version 4: The Full Converter

Let's combine everything into one program. Without conditionals (coming in Chapter 4), we'll run all conversions sequentially:

# full_converter.py — Unit Converter v1.0
print("=" * 50)
print(f"{'UNIVERSAL UNIT CONVERTER':^50}")
print("=" * 50)

# --- Temperature ---
print(f"\n{'[ Temperature ]':^50}")
temp_f = float(input("  Temperature in °F: "))
temp_c = (temp_f - 32) * 5 / 9
print(f"  Result: {temp_f:.1f}°F = {temp_c:.1f}°C")

# --- Distance ---
print(f"\n{'[ Distance ]':^50}")
dist_mi = float(input("  Distance in miles: "))
dist_km = dist_mi * 1.60934
print(f"  Result: {dist_mi:.2f} mi = {dist_km:.2f} km")

# --- Weight ---
print(f"\n{'[ Weight ]':^50}")
weight_lbs = float(input("  Weight in pounds: "))
weight_kg = weight_lbs * 0.453592
print(f"  Result: {weight_lbs:.1f} lbs = {weight_kg:.2f} kg")

# Summary
print(f"\n{'=' * 50}")
print(f"{'CONVERSION SUMMARY':^50}")
print(f"{'=' * 50}")
print(f"  {'Temperature:':<20}{temp_f:>8.1f}°F  →  {temp_c:>8.1f}°C")
print(f"  {'Distance:':<20}{dist_mi:>8.2f} mi  →  {dist_km:>8.2f} km")
print(f"  {'Weight:':<20}{weight_lbs:>8.1f} lbs →  {weight_kg:>8.2f} kg")
print(f"{'=' * 50}")

Sample run:

==================================================
            UNIVERSAL UNIT CONVERTER
==================================================

                  [ Temperature ]
  Temperature in °F: 72
  Result: 72.0°F = 22.2°C

                    [ Distance ]
  Distance in miles: 5
  Result: 5.00 mi = 8.05 km

                     [ Weight ]
  Weight in pounds: 150
  Result: 150.0 lbs = 68.04 kg

==================================================
              CONVERSION SUMMARY
==================================================
  Temperature:           72.0°F  →      22.2°C
  Distance:              5.00 mi  →      8.05 km
  Weight:              150.0 lbs →     68.04 kg
==================================================

What We Used from Chapter 3

Concept How It Was Applied
Variables Storing input values and conversion results
Types (float, str) Converting user input from string to float
Arithmetic expressions Conversion formulas (multiplication, division, subtraction)
Type casting float(input(...)) to convert string input to numbers
f-strings Formatting output with alignment, decimal places, centering
Constants (ALL_CAPS) Conversion factors like MILES_TO_KM
String repetition "=" * 50 for visual borders

What We Can't Do Yet

This converter has limitations that future chapters will address:

  • No menu or choices — the user can't pick which conversion to run. (Chapter 4: conditionals)
  • No looping — the program runs once and exits. (Chapter 5: loops)
  • No error handling — entering "abc" instead of a number crashes the program. (Chapter 11: error handling)
  • No reverse conversions — we hardcoded the direction. (Chapter 4 or Chapter 6: functions)

Discussion Questions

  1. Why did we use float() instead of int() for type casting in this program? What would go wrong if we used int()?

  2. The conversion factors (MILES_TO_KM = 1.60934) are written as constants. What would happen if you accidentally wrote MILES_TO_KM = miles * 1.60934 instead? Why does naming conventions help prevent this kind of mistake?

  3. Look at the f-string formatting in the summary table. What would the output look like without alignment specifiers? Try removing the :<20, :>8.1f, etc., and compare.

  4. The temperature formula (fahrenheit - 32) * 5 / 9 uses parentheses. What would happen if you wrote fahrenheit - 32 * 5 / 9 instead? What result would you get for 72°F?

Try It Yourself

  1. Add a currency conversion section (USD to EUR, GBP, JPY). Research current exchange rates.
  2. Add a speed converter (mph to km/h). The formula is the same as miles to km.
  3. Modify the temperature section to also show the Kelvin equivalent (K = C + 273.15).
  4. Create a "cooking converter" that converts between cups, tablespoons, teaspoons, and milliliters.