Universal Temperature Converter Python Script

This script converts temperatures between Celsius, Fahrenheit, and Kelvin using a simple, menu-driven interface. It allows users to easily input a temperature value and select a conversion option to quickly view the result.

Click to view script…
#!/usr/bin/env python3

def celsius_to_fahrenheit(c):
    return (c * 9/5) + 32

def celsius_to_kelvin(c):
    return c + 273.15

def fahrenheit_to_celsius(f):
    return (f - 32) * 5/9

def fahrenheit_to_kelvin(f):
    return (f - 32) * 5/9 + 273.15

def kelvin_to_celsius(k):
    return k - 273.15

def kelvin_to_fahrenheit(k):
    return (k - 273.15) * 9/5 + 32

def main():
    print("Temperature Converter")
    print("---------------------")
    print("Converts temperatures between Celsius, Fahrenheit, and Kelvin.\n")
    
    while True:
        print("Conversion options:")
        print("1. Celsius to Fahrenheit")
        print("2. Celsius to Kelvin")
        print("3. Fahrenheit to Celsius")
        print("4. Fahrenheit to Kelvin")
        print("5. Kelvin to Celsius")
        print("6. Kelvin to Fahrenheit")
        choice = input("Enter your choice (1-6) or 'q' to quit: ")
        
        if choice.lower() == 'q':
            print("Goodbye!")
            break
        
        try:
            choice = int(choice)
        except ValueError:
            print("Invalid input. Please enter a number between 1 and 6, or 'q' to quit.\n")
            continue
        
        if choice < 1 or choice > 6:
            print("Invalid choice. Please choose a valid conversion option.\n")
            continue
        
        temp_input = input("Enter the temperature value: ")
        try:
            temp = float(temp_input)
        except ValueError:
            print("Invalid temperature value. Please enter a numeric value.\n")
            continue
        
        if choice == 1:
            result = celsius_to_fahrenheit(temp)
            print(f"{temp}°C is equal to {result:.2f}°F\n")
        elif choice == 2:
            result = celsius_to_kelvin(temp)
            print(f"{temp}°C is equal to {result:.2f} K\n")
        elif choice == 3:
            result = fahrenheit_to_celsius(temp)
            print(f"{temp}°F is equal to {result:.2f}°C\n")
        elif choice == 4:
            result = fahrenheit_to_kelvin(temp)
            print(f"{temp}°F is equal to {result:.2f} K\n")
        elif choice == 5:
            result = kelvin_to_celsius(temp)
            print(f"{temp} K is equal to {result:.2f}°C\n")
        elif choice == 6:
            result = kelvin_to_fahrenheit(temp)
            print(f"{temp} K is equal to {result:.2f}°F\n")
            
if __name__ == "__main__":
    main()