Home / Python / Example programs / Basics

Python program: Convert Celsius to Fahrenheit

Convert temperatures from Celsius to Fahrenheit (F = C × 9/5 + 32) and back.

The code

def c_to_f(c):
    return c * 9 / 5 + 32

def f_to_c(f):
    return (f - 32) * 5 / 9

for c in [-10, 0, 21.5, 37, 100]:
    print(f"{c:>6} °C = {c_to_f(c):6.1f} °F")

print(f"98.6 °F = {f_to_c(98.6):.1f} °C")

Output

   -10 °C =   14.0 °F
     0 °C =   32.0 °F
  21.5 °C =   70.7 °F
    37 °C =   98.6 °F
   100 °C =  212.0 °F
98.6 °F = 37.0 °C

How it works

Each formula becomes a small function, then a loop prints a neat table. :>6 right-aligns in 6 characters; :6.1f uses 6 characters with 1 decimal.

Python features used

Learn the ideas behind it in the free lesson Functions.