Unit Converter (Code) in Python

← Back to Projects

About the project:This project will allow you to convert between various units of measurement, such as length, weight, and temperature.

This Python script provides functions to convert between common units of length, weight, and temperature.

It prompts the user for the type of conversion, the value, and the units to convert from and to.

Allows the user to choose units and value to be coverted to other.

How to use this Unit Converter:

  • Run the Python script.
  • It will ask you to choose a conversion type (Length, Weight, or Temperature).
  • Then, you will enter the value you want to convert, followed by the original unit and the target unit.
  • The script will display the converted value.
  • You can continue making conversions until you type q to quit.

Project Level: Beginner

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: choose any code snippet and follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# unit_converter.py

def convert_length(value, from_unit, to_unit):
    """Converts a length value from one unit to another."""
    # Base unit: meters
    conversions = {
        "meters": 1.0,
        "kilometers": 1000.0,
        "centimeters": 0.01,
        "millimeters": 0.001,
        "miles": 1609.34,
        "yards": 0.9144,
        "feet": 0.3048,
        "inches": 0.0254
    }

    if from_unit not in conversions or to_unit not in conversions:
        return None, "Invalid length unit(s)."

    # Convert to meters first
    value_in_meters = value * conversions[from_unit]
    # Convert from meters to the target unit
    converted_value = value_in_meters / conversions[to_unit]
    return converted_value, None

def convert_weight(value, from_unit, to_unit):
    """Converts a weight value from one unit to another."""
    # Base unit: kilograms
    conversions = {
        "kilograms": 1.0,
        "grams": 0.001,
        "milligrams": 0.000001,
        "pounds": 0.453592,
        "ounces": 0.0283495
    }

    if from_unit not in conversions or to_unit not in conversions:
        return None, "Invalid weight unit(s)."

    # Convert to kilograms first
    value_in_kilograms = value * conversions[from_unit]
    # Convert from kilograms to the target unit
    converted_value = value_in_kilograms / conversions[to_unit]
    return converted_value, None

def convert_temperature(value, from_unit, to_unit):
    """Converts a temperature value from one unit to another."""
    from_unit = from_unit.lower()
    to_unit = to_unit.lower()

    if from_unit == to_unit:
        return value, None

    if from_unit == "celsius":
        if to_unit == "fahrenheit":
            return (value * 9/5) + 32, None
        elif to_unit == "kelvin":
            return value + 273.15, None
    elif from_unit == "fahrenheit":
        if to_unit == "celsius":
            return (value - 32) * 5/9, None
        elif to_unit == "kelvin":
            return ((value - 32) * 5/9) + 273.15, None
    elif from_unit == "kelvin":
        if to_unit == "celsius":
            return value - 273.15, None
        elif to_unit == "fahrenheit":
            return ((value - 273.15) * 9/5) + 32, None
    
    return None, "Invalid temperature unit(s)."

def main():
    """Main function to run the Unit Converter."""
    print("--- Python Unit Converter ---")
    print("Available conversion types: Length, Weight, Temperature")

    while True:
        conversion_type = input("\nEnter conversion type (Length, Weight, Temperature, or 'q' to quit): ").strip().lower()

        if conversion_type == 'q':
            print("Exiting Unit Converter. Goodbye!")
            break
        elif conversion_type not in ["length", "weight", "temperature"]:
            print("Invalid conversion type. Please choose from Length, Weight, or Temperature.")
            continue

        try:
            value = float(input(f"Enter the value to convert: ").strip())
        except ValueError:
            print("Invalid value. Please enter a number.")
            continue

        from_unit = input(f"Enter the unit to convert FROM (e.g., meters, pounds, celsius): ").strip().lower()
        to_unit = input(f"Enter the unit to convert TO (e.g., kilometers, grams, fahrenheit): ").strip().lower()

        converted_value = None
        error_message = None

        if conversion_type == "length":
            converted_value, error_message = convert_length(value, from_unit, to_unit)
        elif conversion_type == "weight":
            converted_value, error_message = convert_weight(value, from_unit, to_unit)
        elif conversion_type == "temperature":
            converted_value, error_message = convert_temperature(value, from_unit, to_unit)

        if error_message:
            print(f"Error: {error_message}")
        elif converted_value is not None:
            print(f"\n{value} {from_unit} is equal to {converted_value:.4f} {to_unit}.")
        else:
            print("An unexpected error occurred during conversion.")

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()