DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Day 32: Python Temperature Converter, Switch Between Fahrenheit and Celsius with Inputs

Welcome to Day 32 of the #80DaysOfChallenges journey! This beginner task involves creating a temperature converter that handles Fahrenheit to Celsius and vice versa, based on user choice and value, using math ops and conditionals for the logic. It's a practical intro to interactive scripts, blending inputs, calculations, and error checks, ideal for everyday utils or learning flow control. If you're practicing user-driven code or arithmetic in conditions, this "Python temperature converter" example shows a function that's reusable and pairs nicely with a simple prompt loop for conversions.


💡 Key Takeaways from Day 32: Temperature Convert Function

This challenge defines a function for the core conversion, wrapped in an interactive block for user input and output. It's a neat setup for conditional math: pick scale, apply formula, format result. We'll outline the basics: function with scale check and formulas, input handling for interactivity, and formatted print with units.

1. Function Design: Conditional Formulas

The convert_temperature function takes a value and scale, applies the right math, or raises an error. Its signature includes types:

def convert_temperature(value: float, to_scale: str) -> float:
    """
    Convert temperature between Fahrenheit and Celsius.
    to_scale must be either 'C' or 'F'.
    """
Enter fullscreen mode Exit fullscreen mode

The logic:

if to_scale.upper() == 'C':
    # Convert Fahrenheit to Celsius
    return (value - 32) * 5 / 9
elif to_scale.upper() == 'F':
    # Convert Celsius to Fahrenheit
    return (value * 9 / 5) + 32
else:
    raise ValueError("Scale must be 'C' or 'F'.")
Enter fullscreen mode Exit fullscreen mode

.upper() makes it case-insensitive. This keeps the function focused, easy to test independently, and ready for expansion like adding Kelvin or more scales.

2. Input Normalization: User-Friendly Prompts

In the example, gather inputs:

scale = input("Convert to (C/F): ").strip().upper()
temp = float(input("Enter temperature value: "))
Enter fullscreen mode Exit fullscreen mode

strip().upper() cleans the scale, and float ensures numeric temp. This handles real-user input gracefully, preventing common errors. The conditional in the function ties back here, making the script robust without extra checks outside.

3. Output Formatting: Result with Units

Compute and show:

result = convert_temperature(temp, scale)
unit = "°C" if scale == "C" else "°F"
print(f"Converted temperature: {result:.2f}{unit}")
Enter fullscreen mode Exit fullscreen mode

The f-string rounds to two decimals and adds the unit. For inputs like to C, 32: outputs 0.00°C. It's a polished touch, and the print block could loop for multiple conversions if extended.


🎯 Summary and Reflections

This temperature converter combines inputs and math into a handy tool, emphasizing conditional paths for different cases. It reminded me:

  • Formula simplicity: Basic ops handle real-world calcs effectively.
  • Input robustness: Upper and strip make it forgiving.
  • Output clarity: Formatting turns numbers into readable info.

What emerged was its utility, like in weather apps. For more, add validation for non-numeric temps or round options.

Advanced Alternatives: Use a dict for formulas, or enums for scales. How do you handle units in code? Share below!


🚀 Next Steps and Resources

Day 32 mixed interactivity with math, prepping for calc-based challenges. In #80DaysOfChallenges? Added Kelvin? Post your tweak!

Top comments (0)