w3resource

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:

# Solution 1: Basic Approach Using Conditional Statements

# Function to convert Fahrenheit to Celsius
def fahrenheit_to_celsius(fahrenheit):
    # Apply the conversion formula: (F - 32) * 5/9
    celsius = (fahrenheit - 32) * 5 / 9
    return celsius

# Function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
    # Apply the conversion formula: (C * 9/5) + 32
    fahrenheit = (celsius * 9 / 5) + 32
    return fahrenheit

# Get the temperature from the user
temperature = float(input("Enter temperature: "))

# Ask the user for the conversion type
conversion_type = input("Select a conversion type (1 for Fahrenheit to Celsius, 2 for Celsius to Fahrenheit): ")

# Perform the conversion based on user selection
if conversion_type == '1':
    # Convert Fahrenheit to Celsius
    converted_temperature = fahrenheit_to_celsius(temperature)
    print(f"Converted temperature: {converted_temperature:.1f}°C")
elif conversion_type == '2':
    # Convert Celsius to Fahrenheit
    converted_temperature = celsius_to_fahrenheit(temperature)
    print(f"Converted temperature: {converted_temperature:.1f}°F")
else:
    # Handle invalid conversion type selection
    print("Invalid selection. Please choose 1 or 2.")

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:

# Solution 2: Using a Class to Encapsulate the Conversion Logic

class TemperatureConverter:
    """Class to handle temperature conversions between Fahrenheit and Celsius."""

    @staticmethod
    def fahrenheit_to_celsius(fahrenheit):
        """Convert Fahrenheit to Celsius."""
        # Apply the conversion formula: (F - 32) * 5/9
        return (fahrenheit - 32) * 5 / 9

    @staticmethod
    def celsius_to_fahrenheit(celsius):
        """Convert Celsius to Fahrenheit."""
        # Apply the conversion formula: (C * 9/5) + 32
        return (celsius * 9 / 5) + 32

    def convert_temperature(self):
        """Prompt the user for input and perform the desired conversion."""
        # Get the temperature from the user
        temperature = float(input("Enter temperature: "))

        # Ask the user for the conversion type
        conversion_type = input("Select a conversion type (1 for Fahrenheit to Celsius, 2 for Celsius to Fahrenheit): ")

        # Perform the conversion based on user selection
        if conversion_type == '1':
            # Convert Fahrenheit to Celsius
            converted_temperature = self.fahrenheit_to_celsius(temperature)
            print(f"Converted temperature: {converted_temperature:.1f}°C")
        elif conversion_type == '2':
            # Convert Celsius to Fahrenheit
            converted_temperature = self.celsius_to_fahrenheit(temperature)
            print(f"Converted temperature: {converted_temperature:.1f}°F")
        else:
            # Handle invalid conversion type selection
            print("Invalid selection. Please choose 1 or 2.")

# Create an instance of the TemperatureConverter class
converter = TemperatureConverter()

# Call the method to perform temperature conversion
converter.convert_temperature()

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.



Follow us on Facebook and Twitter for latest update.