Chapter 2: Control Flow / Lesson 16

Temperature Conversion Program

🎯 Project: Temperature Converter

In this lesson, you'll build a temperature converter program that converts between Celsius and Fahrenheit. This project reinforces your understanding of conditional statements, mathematical operations, and formatting output.

You'll learn how to implement conversion formulas, handle different input formats, and display results clearly to users.

Conversion Formulas

Here are the mathematical formulas you'll need:

  • Celsius to Fahrenheit: F = (C × 9/5) + 32
  • Fahrenheit to Celsius: C = (F - 32) × 5/9

💡 Key Conversion Points

• Water freezes at 0°C = 32°F

• Water boils at 100°C = 212°F

• -40°C = -40°F (they meet at this point!)

Basic Temperature Converter

Here's a basic implementation that converts a temperature based on the unit:

converter.py
temp = 100 unit = "C" if unit == "C" or unit == "c": # Convert Celsius to Fahrenheit fahrenheit = (temp * 9 / 5) + 32 print(f"{temp}°C = {fahrenheit}°F") elif unit == "F" or unit == "f": # Convert Fahrenheit to Celsius celsius = (temp - 32) * 5 / 9 print(f"{temp}°F = {celsius}°C") else: print(f"Error: Unknown unit '{unit}'")

Enhanced Converter with Rounding

Temperature conversions often result in long decimal numbers. Use round() to format the output nicely:

rounded_converter.py
temp = 100 unit = "C" if unit.upper() == "C": fahrenheit = (temp * 9 / 5) + 32 print(f"{temp}°C = {round(fahrenheit, 2)}°F") elif unit.upper() == "F": celsius = (temp - 32) * 5 / 9 print(f"{temp}°F = {round(celsius, 2)}°C") else: print("Invalid unit. Use 'C' or 'F'")

Using Match Statement

For cleaner code (Python 3.10+), you can use a match statement:

match_converter.py
temp = 100 unit = "C" match unit.upper(): case "C" | "CELSIUS": fahrenheit = (temp * 9 / 5) + 32 print(f"{temp}°C = {round(fahrenheit, 1)}°F") case "F" | "FAHRENHEIT": celsius = (temp - 32) * 5 / 9 print(f"{temp}°F = {round(celsius, 1)}°C") case _: print("Invalid unit. Use 'C' or 'F'")

Adding Temperature Context

You can add helpful context about what the temperature means:

contextual_converter.py
temp = 100 unit = "C" if unit.upper() == "C": fahrenheit = (temp * 9 / 5) + 32 print(f"{temp}°C = {round(fahrenheit, 1)}°F") # Add context if temp <= 0: print("Freezing point!") elif temp >= 100: print("Boiling point!") elif unit.upper() == "F": celsius = (temp - 32) * 5 / 9 print(f"{temp}°F = {round(celsius, 1)}°C")

Tips for Better Conversion

💡 Handle Case Sensitivity

Use unit.upper() or unit.lower() to handle both uppercase and lowercase inputs gracefully.

💡 Round for Readability

Use round() to limit decimal places. Most temperatures don't need more than 1-2 decimal places.

💡 Validate Input

Always check if the unit is valid before performing calculations. This prevents errors and provides helpful feedback.

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...