Python programs / Numbers / Temperature conversion

Python Program to Convert Celsius to Fahrenheit and Back

Beginner Numbers

Converts a temperature from Celsius to Fahrenheit and from Fahrenheit back to Celsius with the two standard formulas.

Celsius and Fahrenheit measure temperature from different starting points and in different sized steps. Water freezes at 0 °C, which is 32 °F, and boils at 100 °C, which is 212 °F. So 100 Celsius degrees cover the same range as 180 Fahrenheit ones: each Celsius degree is 9/5 (1.8) Fahrenheit degrees. To convert 37 °C: 37 × 9 / 5 = 66.6, and 66.6 + 32 = 98.6 °F.

Program

def celsius_to_fahrenheit(celsius):
    """The temperature in Fahrenheit for celsius degrees."""
    return celsius * 9 / 5 + 32


def fahrenheit_to_celsius(fahrenheit):
    """The temperature in Celsius for fahrenheit degrees."""
    return (fahrenheit - 32) * 5 / 9


print(f"37 C = {celsius_to_fahrenheit(37):.1f} F")
print(f"100 F = {fahrenheit_to_celsius(100):.1f} C")

Open in the editor Download temperature_conversion.py

Output

37 C = 98.6 F
100 F = 37.8 C

How it works

  1. Celsius to Fahrenheit: multiplying by 9/5 turns the Celsius degrees into Fahrenheit ones, and adding 32 moves the starting point, as water freezes at 32 °F, not 0.
  2. Fahrenheit to Celsius undoes those steps in reverse order: subtract 32 first, then multiply by 5/9. The brackets make the subtraction happen first. Without them, Python would work out 32 * 5 / 9 first, as multiplication and division come before subtraction.
  3. The program converts 37 °C, the normal body temperature, and 100 °F. :.1f in the f-string shows each result with one decimal place: 100 °F is 37.777… °C, which prints as 37.8.

Other ways to write it

One function for both directions

A second argument can say which scale to convert to, so one function does both:

def convert(degrees, to):
    if to == "F":
        return degrees * 9 / 5 + 32
    return (degrees - 32) * 5 / 9

print(convert(100, "F"), convert(212, "C"))

With 1.8 and round()

9 / 5 is 1.8, so many programs write the formula with 1.8. Here round(…, 1) rounds the result itself to one decimal place, instead of only how it's printed.

def celsius_to_fahrenheit(celsius):
    return round(celsius * 1.8 + 32, 1)

print(celsius_to_fahrenheit(37), celsius_to_fahrenheit(-40))

Try it yourself

  • Convert 0 °C and 100 °C, the freezing and boiling points of water: you should get 32 and 212.
  • Find the one temperature that's the same on both scales, -40: try celsius_to_fahrenheit(-40).
  • Print a conversion table from 0 °C to 100 °C in steps of 10 with a for loop and range(0, 101, 10).
  • Add a function that converts Celsius to Kelvin, which is Celsius plus 273.15.

More numbers programs

Share this program