Python Project Temperature Converter - Solutions and Explanations
Temperature converter:
Create a program that converts temperatures between Fahrenheit and Celsius.
Input values:
User provides a temperature and selects the conversion type (Fahrenheit to Celsius or vice versa).
Output value:
Converted the temperature.
Example:
Input values: Enter temperature: 32 Select a conversion type (1 for Fahrenheit to Celsius, 2 for Celsius to Fahrenheit): 1 Output value: Converted temperature: 0.0°C
Here are two different solutions for a temperature converter in Python. The program will allow the user to input a temperature and select the conversion type (Fahrenheit to Celsius or Celsius to Fahrenheit), then output the converted temperature.
Solution 1: Basic Approach Using Conditional Statements
Code:
Output:
Enter temperature: 100 Select a conversion type (1 for Fahrenheit to Celsius, 2 for Celsius to Fahrenheit): 1 Converted temperature: 37.8°C
Enter temperature: 37.8 Select a conversion type (1 for Fahrenheit to Celsius, 2 for Celsius to Fahrenheit): 2 Converted temperature: 100.0°F
Explanation:
- Uses two functions, 'fahrenheit_to_celsius()' and 'celsius_to_fahrenheit()', to handle the conversion logic.
- Takes user input for temperature and conversion type, then uses conditional statements ('if-elif-else') to determine which conversion function to call.
- Outputs the converted temperature to the user.
- This solution is simple and straightforward, separating the conversion logic into two functions.
Solution 2: Using a Class to Encapsulate the Conversion Logic
Code:
Output:
Enter temperature: 110 Select a conversion type (1 for Fahrenheit to Celsius, 2 for Celsius to Fahrenheit): 2 Converted temperature: 230.0°F
Enter temperature: 230 Select a conversion type (1 for Fahrenheit to Celsius, 2 for Celsius to Fahrenheit): 1 Converted temperature: 110.0°C
Explanation:
- Defines a 'TemperatureConverter' class that encapsulates all conversion-related functionality.
- Uses static methods 'fahrenheit_to_celsius()' and 'celsius_to_fahrenheit()' for the conversion logic, making them callable without needing an instance of the class.
- The 'convert_temperature()' method handles user input and directs the conversion process based on the selected type.
- This approach makes the code more modular and organized, utilizing Object-Oriented Programming (OOP) principles for better maintainability and extensibility.
Note:
Both solutions provide a way to convert temperatures between Fahrenheit and Celsius, with Solution 1 being a basic approach and Solution 2 offering a more structured, OOP-based design.