LearnPython has the Biggest Discount Ever! ------ Get $349 $129 Lifetime Access to all 13 Python Courses
How to Convert Fahrenheit to Celsius in Python
To convert a temperature from Fahrenheit to Celsius in Python, you can use the following formula:
celsius = (fahrenheit - 32) * 5/9
Example
Here’s a Python function that takes a temperature in Fahrenheit as input and returns the equivalent temperature in Celsius:
def fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
return celsius
You can call this function with a Fahrenheit temperature as an argument, and it will return the corresponding Celsius temperature.
Here’s an example usage:
# Example usage
fahrenheit = 75
celsius = fahrenheit_to_celsius(fahrenheit)
print(f"{fahrenheit}°F is equal to {celsius:.2f}°C")
Output:
75°F is equal to 23.89°C
In this example, we define the fahrenheit_to_celsius()
function that takes a fahrenheit
temperature as input. Inside the function, we apply the conversion formula to calculate the celsius
temperature. Finally, we return the celsius
value.
In the example usage, we set the fahrenheit
variable to 75. We then call the fahrenheit_to_celsius()
function with fahrenheit
as an argument and store the result in the celsius
variable. Finally, we print a formatted string that displays the Fahrenheit temperature and its equivalent Celsius temperature rounded to two decimal places using the :.2f
format specifier.
You can modify the fahrenheit
value to convert different Fahrenheit temperatures to Celsius.
Prompting the User Enter Celsius Temperature
To prompt the user to enter a temperature in Fahrenheit and then convert it to Celsius, you can use the input()
function to get user input.
# Prompt the user to enter temperature in Fahrenheit
fahrenheit = float(input("Enter the temperature in Fahrenheit: "))
# Convert Fahrenheit to Celsius
celsius = fahrenheit_to_celsius(fahrenheit)
# Print the result
print(f"{fahrenheit}°F is equal to {celsius:.2f}°C")
Since we expect the user to enter a numeric value, we use the float()
function to convert the user’s input from a string to a floating-point number. This allows us to perform the necessary arithmetic operations.
We call the fahrenheit_to_celsius()
function with the user-entered fahrenheit
value and store the result in the celsius
variable.
Finally, we print the result using an f-string, displaying the original Fahrenheit temperature and the converted Celsius temperature rounded to two decimal places.
Enter the temperature in Fahrenheit: 75
75.0°F is equal to 23.89°C
Also Check: