Python Tutorial
Python Project: Temperature Converter
Convert Celsius, Fahrenheit, and Kelvin with functions so each scale is a one-line formula.
What you are building
You write small functions that convert among Celsius, Fahrenheit, and Kelvin. Each formula lives in one place. A table of sample values proves the functions agree with the usual checkpoints: water freezes, room temperature, body temperature, and water boils.
Run everything at /try. That editor executes Python. It is not an HTML preview and not a C or C++ compile step. Values are listed in the script, so you never type into input().
Skills used
- One function per conversion
- Arithmetic with
floatvalues roundwhen you want a short printed figure- Calling one converter from another (Fahrenheit through Celsius into Kelvin)
- Formatted columns so the table is readable
Put each formula in a function
Celsius to Fahrenheit is multiply by 9 / 5, then add 32. The inverse subtracts 32, then multiplies by 5 / 9. Kelvin is Celsius plus 273.15. Name those steps. Do not copy the numbers into every print line.
Example
def c_to_f(c):
return c * 9 / 5 + 32
def f_to_c(f):
return (f - 32) * 5 / 9
def c_to_k(c):
return c + 273.15
print(c_to_f(0))
print(f_to_c(32))
print(c_to_k(0))Zero Celsius should print 32.0, 32 Fahrenheit should print 0.0, and zero Celsius should print 273.15 Kelvin. If any of those fail, fix the function before you build the table.
Reuse Celsius as the hub
You do not need six independent formulas. Convert Fahrenheit to Kelvin by going through Celsius. Convert Kelvin to Fahrenheit the same way. Then a bug in c_to_f is still only in one function.
Example
def c_to_f(c):
return c * 9 / 5 + 32
def f_to_c(f):
return (f - 32) * 5 / 9
def c_to_k(c):
return c + 273.15
def k_to_c(k):
return k - 273.15
def f_to_k(f):
return c_to_k(f_to_c(f))
def k_to_f(k):
return c_to_f(k_to_c(k))
print(round(f_to_k(32), 2))
print(round(k_to_f(273.15), 2))32 Fahrenheit is 273.15 Kelvin, the freezing point of water. If f_to_k(32) is not 273.15, one of the hub functions is wrong. Test the hub before you trust the table.
Complete program
Four Celsius samples fill a printed table of F and K. A second block converts a few Fahrenheit values back, so you see both directions. Copy the whole file into /try.
Example
def c_to_f(c):
return c * 9 / 5 + 32
def f_to_c(f):
return (f - 32) * 5 / 9
def c_to_k(c):
return c + 273.15
def k_to_c(k):
return k - 273.15
def f_to_k(f):
return c_to_k(f_to_c(f))
def k_to_f(k):
return c_to_f(k_to_c(k))
samples_c = [0, 21, 37, 100]
print("Temperature converter")
print()
print(f"{'C':>8} {'F':>8} {'K':>8}")
for c in samples_c:
print(f"{c:8.1f} {c_to_f(c):8.1f} {c_to_k(c):8.2f}")
print()
print("Checks from Fahrenheit")
for f in [32, 70, 212]:
c = f_to_c(f)
k = f_to_k(f)
print(f, "F ->", round(c, 2), "C,", round(k, 2), "K")| C | F | K | Note |
|---|---|---|---|
| 0 | 32.0 | 273.15 | Water freezes |
| 21 | 69.8 | 294.15 | Mild room |
| 37 | 98.6 | 310.15 | Body temperature |
| 100 | 212.0 | 373.15 | Water boils |
Common mistakes
- Writing
c * (9 / 5 + 32)folds 32 into the scale factor. Usec * 9 / 5 + 32. The inverse needs parentheses:(f - 32) * 5 / 9. - Using 273 instead of 273.15. The table will then miss every Kelvin value by 0.15.
- Integer division in another language. In Python 3,
9 / 5is 1.8. You do not need9.0, but you must not use//. - Rounding inside the function. Keep full precision in the return value. Round only when you print.
- Mixing scales in one variable name. Call the Celsius value
c, nottemp, once Fahrenheit is in the same file.
How to extend / Practice tasks
Keep the functions. Change the samples or the rounding.
- Add
-40tosamples_c. Celsius and Fahrenheit meet at -40. Print that row and confirm both columns show -40.0. - Write
format_row(c)that returns one formatted string, then print with a loop that only calls that helper. - Convert 0 Kelvin to Celsius and Fahrenheit and print a warning if Celsius is below -273.15, the absolute zero floor this project does not otherwise enforce.
📘 Real-World Deep Dive
A temperature converter looks trivial, but it's the cleanest place to learn a rule you'll use forever: put the conversion math in small pure functions, keep input/output at the edges, and the whole thing becomes testable and reusable.
What to build
Convert between Celsius, Fahrenheit, and Kelvin, rejecting physically impossible temperatures below absolute zero.
Real-Life Example
ABS_ZERO_C = -273.15
def c_to_f(c: float) -> float:
if c < ABS_ZERO_C:
raise ValueError("below absolute zero")
return c * 9 / 5 + 32
def c_to_k(c: float) -> float:
if c < ABS_ZERO_C:
raise ValueError("below absolute zero")
return c - ABS_ZERO_C
for c in [0, 37, 100, -300]:
try:
print(f"{c:>4}C = {c_to_f(c):.1f}F, {c_to_k(c):.2f}K")
except ValueError as e:
print(f"{c:>4}C = {e}")Validation lives inside the conversion, so no caller can produce a nonsense temperature.
Expected Output
0C = 32.0F, 273.15K
37C = 98.6F, 310.15K
100C = 212.0F, 373.15K
-300C = below absolute zeroCommon mistakes
- Integer division bites here: in Python 3
9 / 5is 1.8 (good), but porting to//silently truncates and every result is wrong. - Rounding for display (
:.1f) is fine, but round only at output — rounding mid-chain accumulates error. - Kelvin and the Fahrenheit floor differ; validate against absolute zero in the correct scale, not a hard-coded 0.
🚀 Performance & Best Practices
- Pure functions (no printing inside) mean you can test
c_to_f(100) == 212directly. - Build a tiny dispatch table
{("C","F"): c_to_f, ...}to avoid a maze of if/elif for every pair. - Use
math.isclosein tests — exact float equality on conversions is fragile.
🧪 Try It Yourself
- Add Kelvin→Celsius and Fahrenheit→Celsius so any pair converts to any other.
- Wrap it in a CLI:
python temp.py 100 C Fprints212.0. - Add a test that every round-trip (C→F→C) returns the original within
1e-9.