Classroom Glossary Public page

Lab 1: Temperature Converter

762 words

~90 minutes. Build a CLI tool that converts between Fahrenheit, Celsius, and Kelvin. Use only week 1 syntax: variables, types, input, print, and arithmetic.


Goal: ship a working Python CLI tool that asks the user for a temperature and a unit, then prints the same temperature in the other two units.

Estimated time: 90 minutes

Prerequisites: Python 3.11+ installed; a code editor; week 1 lecture (variables, types, f-strings, input()).


Setup

mkdir -p ~/fnd-102/lab-1
cd ~/fnd-102/lab-1

Open a new file: lab-1-temp.py.


The conversion formulas

You will use three formulas. Write them out by hand once before coding so you understand what the program is doing:

  • Fahrenheit to Celsius: C = (F - 32) * 5 / 9
  • Celsius to Fahrenheit: F = C * 9 / 5 + 32
  • Celsius to Kelvin: K = C + 273.15
  • Kelvin to Celsius: C = K - 273.15

You can chain them: F to K is "F to C to K." K to F is "K to C to F." Implement two direct conversions and use them in pairs; you do not need six separate formulas.


Part A: First-pass version (30 min)

Write a version of lab-1-temp.py that does the following:

  1. Asks the user to enter a temperature value (a number)
  2. Asks the user to enter the unit the value is in (F, C, or K)
  3. Prints the same temperature in the other two units, formatted to 2 decimal places

Sample session:

$ python3 lab-1-temp.py
Enter a temperature: 100
Enter the unit (F, C, K): F
100.00 F = 37.78 C = 310.93 K

A minimal version uses input() twice, an if chain (you have not formally learned if yet; the lecture covered the basics implicitly), and f-strings for the output.

Hint: convert the input string to a number with float(), not int(). Temperatures have decimals.


Part B: Handle the three input units (20 min)

Modify the program to handle all three input units (F, C, K) correctly. If the user enters F, convert to C and K. If C, convert to F and K. If K, convert to C and F.

You will write something like:

value = float(input('Enter a temperature: '))
unit = input('Enter the unit (F, C, K): ')

if unit == 'F':
    celsius = (value - 32) * 5 / 9
    kelvin = celsius + 273.15
    print(f'{value:.2f} F = {celsius:.2f} C = {kelvin:.2f} K')
elif unit == 'C':
    # ... your code ...
elif unit == 'K':
    # ... your code ...
else:
    print(f'Unknown unit: {unit}')

You may not have formally learned elif yet; the lecture mentioned if in passing. elif is short for "else if" and lets you chain conditions. The full coverage of control flow is week 2; here you use just enough to make the lab work.


Part C: User experience polish (20 min)

The program in Part B works, but the UX is rough. Improve three things:

  1. Case-insensitive unit. A user who types f (lowercase) should be treated the same as F. Use the string method .upper(): unit = input('...').upper().
  2. Reject obviously-wrong input. If the user enters a temperature below absolute zero in their unit (-273.15 C, -459.67 F, 0 K is the minimum), print a warning. Do NOT crash; just print "Warning: that's below absolute zero" and proceed with the conversion anyway.
  3. Trim whitespace. Users sometimes type F with spaces. The string method .strip() removes leading and trailing whitespace: unit = input('...').strip().upper().

Part D: Commit your work (10 min)

cd ~/fnd-102/lab-1
git add lab-1-temp.py
git commit -m "lab-1: temperature converter (F, C, K) with input validation"

If this is your first commit in ~/fnd-102/:

cd ~/fnd-102
git init
git add lab-1/lab-1-temp.py
git commit -m "lab-1: temperature converter"

Expected output / artifact

Your lab-1-temp.py should:

  • Run without error on the three sample inputs: 100 F, 0 C, 273.15 K
  • Produce the correct conversions (verify with a known reference: 100 F is 37.78 C is 310.93 K)
  • Handle lowercase units (f, c, k)
  • Warn on sub-absolute-zero input but not crash
  • Be committed to your Git repo at ~/fnd-102/lab-1/lab-1-temp.py

A worked solution lives in the instructor's reference repository (do not look until you have shipped your version).


What's the failure mode?

This tool's likely failure modes (good practitioner habit: ask before you ship):

  1. User types seven for the temperature. float('seven') raises ValueError and the program crashes with a traceback. Week 9 (pdb and try / except) covers how to handle this gracefully; for now, the crash is acceptable.
  2. User types Centigrade for the unit. Your if/elif chain falls through to the else branch and prints "Unknown unit". That is the right behavior.
  3. Floating-point precision. 0.1 + 0.2 != 0.3 in Python. Your conversions will sometimes show 99.99999999... instead of 100.00. The :.2f format specifier rounds the display to 2 decimal places, hiding the issue. Try it: convert 100 F to C and back to F; you may not get exactly 100.00 back.

If you have time, try each failure mode and observe what your program does. That is half of debugging: knowing what error to expect.


Common pitfalls

  • Using int() instead of float(). int('98.6') raises ValueError. Use float() for temperatures.
  • Comparing strings with =. unit = 'F' is assignment (unit becomes 'F'). unit == 'F' is comparison. The first is silent and wrong; the second is what you want.
  • Forgetting .upper(). A user who types f triggers the else branch unless you normalize case. The lab requires the normalization.
  • Wrong formula. Reading C * 9 / 5 + 32 as C * (9 / 5 + 32) is a precedence bug. Always parenthesize when in doubt: (C * 9 / 5) + 32.

Stretch (optional)

  1. Add a fourth unit: Rankine (R = F + 459.67).
  2. Support a one-shot CLI invocation: python lab-1-temp.py 100 F should print the conversion without prompting. Hint: read sys.argv (week 6 introduces argparse; this is the pre-argparse version).
  3. Print a small table of common reference temperatures: water freezing (0 C), water boiling (100 C), human body (37 C), absolute zero (-273.15 C). Show the value in all three units.

Lab 1 v0.1.