Home » Learn Python » Getting Started » Example: Fahrenheit to Celsius in Python

Example: Fahrenheit to Celsius in Python

Now we can look at a useful complete simple program in Python. This program asks the user to enter a temperature in Fahrenheit and converts it to a temperature in Celsius.

If you’re new to programming, it’s well worth typing it out, getting it working, and then trying to write your own similar program, for example to convert miles to kilometres or vice-versa.

# Get the user to enter a temperature
temperature_f = input("Enter a temperature in Fahrenheit: ")

# temperature_f refers to a string. We must convert it 
# to a float so we can do calculations with it.
temperature_f = float(temperature_f)

# Convert to Celsius. 
temperature_c = (temperature_f - 32) / 1.8

# Tell the user the result.
print(f"{temperature_f:.1f} F is {temperature_c:.1f} C.")
Enter a temperature in Fahrenheit: 97
97.0 F is 36.1 C.

Leave a Reply

Blog at WordPress.com.

%d