Unit Converter

 def convert_temperature(value, from_unit, to_unit):

    if from_unit == "Celsius" and to_unit == "Fahrenheit":

        return (value * 9/5) + 32

    elif from_unit == "Fahrenheit" and to_unit == "Celsius":

        return (value - 32) * 5/9

    elif from_unit == "Celsius" and to_unit == "Kelvin":

        return value + 273.15

    elif from_unit == "Kelvin" and to_unit == "Celsius":

        return value - 273.15

    elif from_unit == "Fahrenheit" and to_unit == "Kelvin":

        return (value - 32) * 5/9 + 273.15

    elif from_unit == "Kelvin" and to_unit == "Fahrenheit":

        return (value - 273.15) * 9/5 + 32

    return value


def convert_length(value, from_unit, to_unit):

    conversion_factors = {

        "meters": 1,

        "kilometers": 0.001,

        "centimeters": 100,

        "millimeters": 1000,

        "inches": 39.3701,

        "feet": 3.28084,

        "miles": 0.000621371,

    }

    return value * conversion_factors[to_unit] / conversion_factors[from_unit]


def convert_weight(value, from_unit, to_unit):

    conversion_factors = {

        "kilograms": 1,

        "grams": 1000,

        "milligrams": 1_000_000,

        "pounds": 2.20462,

        "ounces": 35.274,

    }

    return value * conversion_factors[to_unit] / conversion_factors[from_unit]


def main():

    print("Unit Converter")

    print("1. Temperature")

    print("2. Length")

    print("3. Weight")

    choice = input("Choose a category (1/2/3): ")


    if choice == "1":

        print("\nTemperature Units: Celsius, Fahrenheit, Kelvin")

        value = float(input("Enter the value to convert: "))

        from_unit = input("Convert from: ").capitalize()

        to_unit = input("Convert to: ").capitalize()

        result = convert_temperature(value, from_unit, to_unit)

        print(f"{value} {from_unit} is equal to {result:.2f} {to_unit}")


    elif choice == "2":

        print("\nLength Units: meters, kilometers, centimeters, millimeters, inches, feet, miles")

        value = float(input("Enter the value to convert: "))

        from_unit = input("Convert from: ").lower()

        to_unit = input("Convert to: ").lower()

        result = convert_length(value, from_unit, to_unit)

        print(f"{value} {from_unit} is equal to {result:.2f} {to_unit}")


    elif choice == "3":

        print("\nWeight Units: kilograms, grams, milligrams, pounds, ounces")

        value = float(input("Enter the value to convert: "))

        from_unit = input("Convert from: ").lower()

        to_unit = input("Convert to: ").lower()

        result = convert_weight(value, from_unit, to_unit)

        print(f"{value} {from_unit} is equal to {result:.2f} {to_unit}")


    else:

        print("Invalid choice! Please select 1, 2, or 3.")


if __name__ == "__main__":

    main()


No comments: