Celsius to Fahrenheit Program in Python
Problem statement
Convert a temperature between Celsius and Fahrenheit using F = C × 9/5 + 32, and back using C = (F − 32) × 5/9.Approach 1: simple loop
Apply the formula directly. The order matters exactly as written: multiply first, then add 32 — put brackets around anything you want done earlier.
c = 37 f = c * 9 / 5 + 32 print(f) # Output: 98.6
Check the anchors as you go: 0°C must give 32°F (freezing point) and 100°C must give 212°F (boiling point). If those two pass, the formula is right.
Approach 2: reusable function
Wrap both directions in functions so the conversion is reusable and testable — and each formula lives in exactly one place.
def to_fahrenheit(c):
return c * 9 / 5 + 32
def to_celsius(f):
return (f - 32) * 5 / 9
print(to_fahrenheit(37)) # 98.6
print(to_celsius(98.6)) # 37.0
print(to_fahrenheit(100)) # 212.0Notice the asymmetry in the brackets: the reverse formula needs (f - 32) grouped because subtraction happens before multiplication would not give the right order.
Approach 3: Pythonic alternative
Real programs convert ranges, not single values — and present them in a tidy table with f-string formatting.
def to_fahrenheit(c):
return c * 9 / 5 + 32
print(f"{'C':>5} {'F':>7}")
for c in range(-2, 3):
print(f"{c:>5} {to_fahrenheit(c):>7.1f}")
# Output:
# -2 28.4
# -1 30.2
# 0 32.0
# 1 33.8
# 2 35.6{c:>5} right-aligns in 5 characters and :.1f shows exactly one decimal — a two-character change that turns output into a report.
Dry run
Trace C = 37: 37 × 9 = 333. 333 / 5 = 66.6. 66.6 + 32 = 98.6 — human body temperature. Now the anchors: C = 0 → 0 + 32 = 32 (freezing ✓). C = 100 → 900/5 + 32 = 180 + 32 = 212 (boiling ✓). And the reverse on your own answer: (98.6 − 32) × 5/9 = 66.6 × 5/9 = 333/9 = 37 — you land back where you started, which is the strongest check a conversion has.
Common errors
- Using
9 // 5— integer division makes it 1, so every result comes out as C + 32. Use true division/. - Forgetting the
+ 32— the answer is off by exactly 32 degrees. - Multiplying by 5/9 in the forward direction — that is the reverse formula; F-to-C divides by 9/5 differently from C-to-F.
- Omitting brackets in the reverse formula —
f - 32 * 5 / 9computesf - (32*5/9), not(f-32)*5/9. - Reading
input()withoutfloat()— temperatures can be decimal, and string arithmetic raises TypeError.
Practice on PyDebug
Turn the idea into a debugging habit with these free browser exercises: