Founding Batch Offer · HLD · LLD · System Design at ₹799 until 30 Nov

Temperature Converter

Convert among Celsius, Fahrenheit, and Kelvin with branches. Students normalize the unit label, calculate via Celsius, and format all three output temperatures.

IntermediatePhase 6 - Category 5: Real-World Logic ProblemsExample 6 of 15
temperature-converter.py
1# Take input
2temp = float(input("Enter temperature: "))
3unit = input("Enter unit (C/F/K): ").upper()
4
5# Convert to all units
6if unit == 'C':
7 celsius = temp
8 fahrenheit = (celsius * 9/5) + 32
9 kelvin = celsius + 273.15
10elif unit == 'F':
11 fahrenheit = temp
12 celsius = (fahrenheit - 32) * 5/9
13 kelvin = celsius + 273.15
14elif unit == 'K':
15 kelvin = temp
16 celsius = kelvin - 273.15
17 fahrenheit = (celsius * 9/5) + 32
18else:
19 print("Invalid unit")
20 exit()
21
22print(f"Celsius: {celsius:.2f}°C")
23print(f"Fahrenheit: {fahrenheit:.2f}°F")
24print(f"Kelvin: {kelvin:.2f}K")

Output

Enter temperature: 25
Enter unit (C/F/K): C
Celsius: 25.00°C
Fahrenheit: 77.00°F
Kelvin: 298.15K

In this one

  • Normalize unit labels
  • Use offsets as well as scaling
  • Assign all output variables

How it works

  1. 1

    Uppercase the entered unit label.

  2. 2

    Use its branch to calculate all three temperature scales.

  3. 3

    Reject unsupported labels, otherwise print formatted results.

Edge cases

Does lowercase c work?

Does lowercase c work?

Yes. upper normalizes it.

Does the code reject negative Kelvin?

Does the code reject negative Kelvin?

No. Physical-range validation is not included.

What's going on

upper allows c or C to select the Celsius branch. Each valid branch assigns celsius, fahrenheit, and kelvin before the final display.

Fahrenheit conversion subtracts thirty-two before multiplying by five ninths. Kelvin differs from Celsius by 273.15. Invalid labels print a message and exit. The formulas are mathematical conversions; the code does not validate temperatures below absolute zero or strip surrounding label spaces.

Does lowercase c work? Yes. upper normalizes it.

Does the code reject negative Kelvin? No. Physical-range validation is not included.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why subtract 32 when converting Fahrenheit?

Pick an answer to check it.

Question 2

Does lowercase c work?

Pick an answer to check it.

Questions people ask

Does lowercase c work?

Yes. upper normalizes it.

Does the code reject negative Kelvin?

No. Physical-range validation is not included.

Why subtract 32 when converting Fahrenheit?

The Fahrenheit and Celsius zero points differ.