Temperature conversion is a common task in programming, especially when dealing with scientific data, weather information, or international units. In this article, we’ll learn how to convert temperatures between Celsius and Fahrenheit using Python with examples.
Table of contents
Understanding Celsius and Fahrenheit
Celsius and Fahrenheit are temperature scales used to measure how hot or cold something is.
- Celsius (°C)
- It is based on the freezing point of water at 0°C and the boiling point at 100°C.
- Example: A normal body temperature is around 37°C.
- Fahrenheit (°F)
- Water freezes at 32°F and boils at 212°F.
- Example: A normal body temperature is about 98.6°F.
Conversion Formulas
To convert between Celsius and Fahrenheit, we use these formulas:
- Celsius to Fahrenheit:
F = ( C × 9/5 ) + 32 - Fahrenheit to Celsius:
C = ( F - 32 ) × 5/9
How to Convert Celsius To Fahrenheit in Python
Steps to convert temperature from Celsius to Fahrenheit
- Take the Temperature in Celsius
Get or read the temperature in degrees Celsius that you want to convert.
For Example, the temperature = 25°C i.e.,c = 25 - Apply the Formula
Now put the Celsius value into the formula:
F = ( C × 9/5 ) + 32F = ( 25 * 9/5 ) + 32 = ( 225 / 5 ) + 32 = 45 + 32 = 77°F - Display the result in the proper format
Use
print()function and f-string (formatted string literal) in Python to display the result.
Code Example
Output:
Enter temperature in Celsius: 37
37.0°C is equal to 98.60°F
Enter temperature in Celsius: -37
-37.0°C is equal to -34.60°F
Explanation
- Step 1: Here, we are taking the user’s input for temperature in Celsius. As the input is in string format, we need to convert it into a float for calculation.
- input() takes input as a string.
float()converts it to a decimal number (float).- The value is stored in the variable
c.
- Step 2: Plugging the value of
cin formula:F = ( C × 9/5 ) + 32f = ( 37 * 9/5 ) + 32 = ( 333 / 5 ) + 32 = 66.6 + 32 = 98.6°F.- The result is stored in the variable
f.
- Step 3: We use an f-string (formatted string literal) to display the result in a readable format.
{c}shows the input Celsius value.{f:.2f}shows Fahrenheit value rounded to 2 decimal places.- Adds degree symbols and labels (
°C,°F) for clarity.
- Note: The Formula can be used for minus temperatures as well. For Example, if
c = -37°Cthenf = -34.60°F
How to Convert Fahrenheit To Celsius in Python
Like the above approach, we will use the following formula to convert temperature from Fahrenheit to Celsius.
C = ( F - 32 ) × 5/9
For Example, if f = 98.6
C = ( 98.6 - 32 ) * 5/9 = ( 66.6 * 5) / 9 = 333 / 9 = 37°c.
Code Example
Output:
Enter temperature in Fahrenheit: 98.6
98.6°F is equal to 37.00°C
Enter temperature in Fahrenheit: -34
-34.0°F is equal to -36.67°C

Leave a Reply