How to Convert Celsius to Fahrenheit in Python

To convert Celsius to Fahrenheit in Python, you can use the following formula:

fahrenheit = (celsius * 9/5) + 32

This formula takes the Celsius temperature, multiplies it by 9/5, and then adds 32 to get the equivalent temperature in Fahrenheit.

Example

Here’s a Python function that takes a Celsius temperature as input and returns the equivalent Fahrenheit temperature:

def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit

You can use this function by calling it with a Celsius temperature as an argument. For example:

# Convert 0 degrees Celsius to Fahrenheit
result = celsius_to_fahrenheit(0)
print(result) # Output: 32.0

# Convert 100 degrees Celsius to Fahrenheit
result = celsius_to_fahrenheit(100)
print(result) # Output: 212.0

In the above examples, the celsius_to_fahrenheit() function is called with different Celsius temperatures, and the corresponding Fahrenheit temperatures are printed.

Prompting the User Enter Celsius Temperature

You can also prompt the user to enter a Celsius temperature and then convert it to Fahrenheit:

celsius = float(input("Enter the temperature in Celsius: "))
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius}°C is equal to {fahrenheit}°F")

In this case, the user is prompted to enter the temperature in Celsius using the input() function. The input is then converted to a float using float() and passed to the celsius_to_fahrenheit() function. Finally, the result is printed using an f-string, which allows for easy formatting of the output.

Rounding the result:

Depending on your requirements, you may want to round the resulting Fahrenheit temperature to a certain number of decimal places.

You can use the round() function in Python to achieve this. For example, round(fahrenheit, 2) will round the Fahrenheit temperature to two decimal places.

Handling negative temperatures:

The Celsius to Fahrenheit conversion formula works for both positive and negative temperatures.

However, if you are displaying the result, you may want to include the negative sign for negative temperatures.

Unit labeling:

When presenting the result, it’s a good practice to include the unit label (°F) to clearly indicate that the temperature is in Fahrenheit.

This helps avoid confusion and makes the output more readable.

Also Check:

How to Convert Fahrenheit to Celsius in Python

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 125

Leave a Reply

Your email address will not be published. Required fields are marked *