~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:
- Asks the user to enter a temperature value (a number)
- Asks the user to enter the unit the value is in (
F,C, orK) - 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:
- Case-insensitive unit. A user who types
f(lowercase) should be treated the same asF. Use the string method.upper():unit = input('...').upper(). - 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.
- Trim whitespace. Users sometimes type
Fwith 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 Fis37.78 Cis310.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):
- User types
sevenfor the temperature.float('seven')raisesValueErrorand the program crashes with a traceback. Week 9 (pdbandtry/except) covers how to handle this gracefully; for now, the crash is acceptable. - User types
Centigradefor the unit. Yourif/elifchain falls through to theelsebranch and prints "Unknown unit". That is the right behavior. - Floating-point precision.
0.1 + 0.2 != 0.3in Python. Your conversions will sometimes show99.99999999...instead of100.00. The:.2fformat specifier rounds the display to 2 decimal places, hiding the issue. Try it: convert100 Fto C and back to F; you may not get exactly100.00back.
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 offloat().int('98.6')raisesValueError. Usefloat()for temperatures. - Comparing strings with
=.unit = 'F'is assignment (unitbecomes'F').unit == 'F'is comparison. The first is silent and wrong; the second is what you want. - Forgetting
.upper(). A user who typesftriggers theelsebranch unless you normalize case. The lab requires the normalization. - Wrong formula. Reading
C * 9 / 5 + 32asC * (9 / 5 + 32)is a precedence bug. Always parenthesize when in doubt:(C * 9 / 5) + 32.
Stretch (optional)
- Add a fourth unit: Rankine (
R = F + 459.67). - Support a one-shot CLI invocation:
python lab-1-temp.py 100 Fshould print the conversion without prompting. Hint: readsys.argv(week 6 introducesargparse; this is the pre-argparse version). - 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.