Convert Celsius to Fahrenheit and Fahrenheit to Celsius using Python

In this article, I'm going to share a single Python script to convert Celsius to Fahrenheit and Fahrenheit to Celsius.

Convert Celsius to Fahrenheit and Fahrenheit to Celsius using Python
Photo by Daniela Paola Alchapar / Unsplash

In this article, I'm going to share a single Python script that will allow an end user to convert Celsius to Fahrenheit and Fahrenheit to Celsius.

def celsius_to_fahrenheit(celsius):
    """
    Convert temperature in Celsius to Fahrenheit
    """
    fahrenheit = round((celsius * 9/5) + 32, 1)
    return fahrenheit


def fahrenheit_to_celsius(fahrenheit):
    """
    Convert temperature in Fahrenheit to Celsius
    """
    celsius = round((fahrenheit - 32) * 5/9, 1)
    return celsius


while True:
    print("Enter '1' to convert Celsius to Fahrenheit")
    print("Enter '2' to convert Fahrenheit to Celsius")
    print("Enter '0' to exit")
    choice = int(input("Enter your choice: "))

    if choice == 1:
        celsius = float(input("Enter temperature in Celsius: "))
        fahrenheit = celsius_to_fahrenheit(celsius)
        print("Temperature in Fahrenheit: {:.1f}°F".format(fahrenheit))
    elif choice == 2:
        fahrenheit = float(input("Enter temperature in Fahrenheit: "))
        celsius = fahrenheit_to_celsius(fahrenheit)
        print("Temperature in Celsius: {:.1f}°C".format(celsius))
    elif choice == 0:
        print("Exiting the program...")
        break
    else:
        print("Invalid choice. Try again.")