Python Program to Convert Celsius to Fahrenheit
You can convert Celsius to Fahrenheit in Python using the formula
fahrenheit = (celsius * 9/5) + 32. For example, fahrenheit = (celsius * 9/5) + 32 converts Celsius temperature to Fahrenheit.Examples
Input0
Output32.0
Input25
Output77.0
Input-40
Output-40.0
How to Think About It
To convert Celsius to Fahrenheit, multiply the Celsius temperature by 9, then divide by 5, and finally add 32. This formula adjusts the scale and offset between the two temperature units.
Algorithm
1
Get the temperature value in Celsius from the user or input.2
Multiply the Celsius value by 9.3
Divide the result by 5.4
Add 32 to the result to get Fahrenheit.5
Return or print the Fahrenheit temperature.Code
python
celsius = float(input('Enter temperature in Celsius: ')) fahrenheit = (celsius * 9 / 5) + 32 print(f'{celsius}°C is {fahrenheit}°F')
Output
Enter temperature in Celsius: 25
25.0°C is 77.0°F
Dry Run
Let's trace converting 25°C to Fahrenheit through the code
1
Input Celsius
User inputs 25, so celsius = 25.0
2
Multiply by 9
25.0 * 9 = 225.0
3
Divide by 5
225.0 / 5 = 45.0
4
Add 32
45.0 + 32 = 77.0
5
Print result
Output: '25.0°C is 77.0°F'
| Step | Operation | Value |
|---|---|---|
| 1 | Input Celsius | 25.0 |
| 2 | Multiply by 9 | 225.0 |
| 3 | Divide by 5 | 45.0 |
| 4 | Add 32 | 77.0 |
| 5 | Print result | 25.0°C is 77.0°F |
Why This Works
Step 1: Multiply Celsius by 9
Multiplying by 9 scales the Celsius temperature to the Fahrenheit scale proportionally.
Step 2: Divide by 5
Dividing by 5 adjusts the ratio between Celsius and Fahrenheit degrees.
Step 3: Add 32
Adding 32 shifts the zero point from Celsius to Fahrenheit, aligning freezing points.
Alternative Approaches
Using a function
python
def celsius_to_fahrenheit(celsius): return (celsius * 9 / 5) + 32 print(celsius_to_fahrenheit(25))
This approach makes the conversion reusable and cleaner for multiple values.
Using lambda expression
python
c_to_f = lambda c: (c * 9 / 5) + 32 print(c_to_f(25))
A concise way to define the conversion in one line, useful for quick calculations.
Complexity: O(1) time, O(1) space
Time Complexity
The calculation uses a fixed number of arithmetic operations, so it runs in constant time.
Space Complexity
Only a few variables are used, so the space needed is constant.
Which Approach is Fastest?
All approaches run in constant time; using a function or lambda improves code reuse but does not affect speed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct calculation | O(1) | O(1) | Simple one-time conversion |
| Function | O(1) | O(1) | Reusable conversions |
| Lambda expression | O(1) | O(1) | Concise inline use |
Always convert input to float to handle decimal temperatures correctly.
Forgetting to add 32 after scaling causes incorrect Fahrenheit values.