Unit Converter Using Python

Comprehensive Unit Converter for Multiple Categories

Project Overview

The Comprehensive Unit Converter for Multiple Categories is a Python program designed to perform various unit conversions across different categories, including temperature, distance, weight, time, area, volume, speed, energy, pressure, power, and storage. The program allows users to convert values between a wide range of units within these categories, helping to simplify day-to-day calculations and engineering tasks. This project not only demonstrates the use of functions and conditionals in Python but also integrates an interactive user interface to handle multiple conversion operations.

The key features of the program include a simple text-based menu system, which provides a clear and concise way to select the type of conversion, input values, and receive results. The program covers a broad spectrum of conversion types, ensuring versatility and utility for various fields, from science and engineering to general daily use.

Key Features

  • Multiple Conversion Categories: The program includes a wide range of categories such as temperature, distance, weight, time, area, volume, speed, energy, pressure, power, and storage.
  • Interactive Menu System: The user can select a category and specific conversion type, and then input the value to be converted.
  • Flexible Conversion Functions: Each conversion category has a dedicated function that performs the necessary unit conversion based on user input.
  • Error Handling: The program raises clear error messages for invalid conversions and unit mismatches, ensuring that the user is informed about the type of issue.
  • Unit Category Expansion: Easily extendable to accommodate more conversion categories in the future.
  • Real-Time Feedback: Displays the converted result immediately for user validation.

Flow of the Program

  • Start the Program: The program displays a main menu where the user selects the category for conversion (e.g., temperature, distance, etc.).
  • Select Conversion Type: After selecting a category, the user is prompted to choose a specific conversion type (e.g., Celsius to Fahrenheit for temperature conversion).
  • Input the Value: Once the conversion type is selected, the user enters the value they want to convert.
  • Display the Result: The program performs the conversion using the appropriate function and displays the result.
  • Repeat or Exit: After completing a conversion, the program asks the user if they wish to perform another conversion or exit.

Breaking Down the Code

1. Conversion Functions:

The core of the program revolves around a series of conversion functions, each tailored to handle conversions for different categories. Each function follows a similar structure: it takes a value, the from_unit, and the to_unit, then performs the conversion and returns the result.

For instance, the convert_temperature function handles the conversion between temperature units such as Celsius, Fahrenheit, and Kelvin. Here’s how it works:

  • Input: A temperature value, the unit it is in, and the unit to convert to.
  • Process: The function checks the combination of from_unit and to_unit, applies the appropriate mathematical formula for the conversion, and returns the result.

Each conversion function uses a series of if-elif statements to determine which conversion should take place based on the provided units. If no valid conversion is found, a ValueError is raised.

Example:

  def convert_temperature(value, from_unit, to_unit):
    if from_unit == "Celsius":
        if to_unit == "Fahrenheit":
            return value * 9/5 + 32
        elif to_unit == "Kelvin":
            return value + 273.15
    # More conversion logic...
  

2. User Interaction Functions:

The display_options function prints the available conversion options for each category. This allows the user to select the conversion they are interested in.

  def display_options(category):
    print(f"\nSelect a conversion for {category}:")
    if category == "temperature":
        print("1. Celsius to Fahrenheit\n2. Fahrenheit to Celsius\n3. Celsius to Kelvin\n4. Kelvin to Celsius\n5. Fahrenheit to Kelvin\n6. Kelvin to Fahrenheit")
    # More categories...
  

3. Input and Conversion Loop:

The main function is the entry point of the program, which controls the overall flow. The program runs in an infinite loop, continuously offering the user the chance to perform conversions or exit. The user can select a category, choose a conversion, input the value to convert, and see the result. If the user chooses to exit, the loop terminates.

  def main():
    while True:
        print("\nUnit Converter")
        print("1. Temperature\n2. Distance\n3. Weight\n4. Time\n5. Area\n6. Volume\n7. Speed\n8. Energy\n9. Pressure\n10. Power\n11. Storage\n12. Exit")
        choice = int(input("Select a category (1-12): "))
        if choice == 1:
            display_options("temperature")
            value, option = get_input_for_conversion()
            # Conversion logic...
        elif choice == 12:
            break
  

4. Conversion Execution:

Each selected option corresponds to a specific conversion. For example, selecting the temperature conversion from Celsius to Fahrenheit calls the convert_temperature function with the corresponding arguments.

Final Code

Here is the complete code for the Unit Converter 

  # Conversion functions for new categories

def convert_temperature(value, from_unit, to_unit):
    if from_unit == "Celsius":
        if to_unit == "Fahrenheit":
            return value * 9/5 + 32
        elif to_unit == "Kelvin":
            return value + 273.15
    elif from_unit == "Fahrenheit":
        if to_unit == "Celsius":
            return (value - 32) * 5/9
        elif to_unit == "Kelvin":
            return (value - 32) * 5/9 + 273.15
    elif from_unit == "Kelvin":
        if to_unit == "Celsius":
            return value - 273.15
        elif to_unit == "Fahrenheit":
            return (value - 273.15) * 9/5 + 32
    raise ValueError("Invalid temperature conversion")

def convert_distance(value, from_unit, to_unit):
    if from_unit == "Kilometers":
        if to_unit == "Miles":
            return value * 0.621371
        elif to_unit == "Meters":
            return value * 1000
    elif from_unit == "Miles":
        if to_unit == "Kilometers":
            return value / 0.621371
        elif to_unit == "Meters":
            return value * 1609.34
    elif from_unit == "Meters":
        if to_unit == "Kilometers":
            return value / 1000
        elif to_unit == "Miles":
            return value / 1609.34
    raise ValueError("Invalid distance conversion")

def convert_weight(value, from_unit, to_unit):
    if from_unit == "Kilograms":
        if to_unit == "Pounds":
            return value * 2.20462
        elif to_unit == "Grams":
            return value * 1000
    elif from_unit == "Pounds":
        if to_unit == "Kilograms":
            return value / 2.20462
        elif to_unit == "Grams":
            return value * 453.592
    elif from_unit == "Grams":
        if to_unit == "Kilograms":
            return value / 1000
        elif to_unit == "Pounds":
            return value / 453.592
    raise ValueError("Invalid weight conversion")

def convert_time(value, from_unit, to_unit):
    if from_unit == "Seconds":
        if to_unit == "Minutes":
            return value / 60
        elif to_unit == "Hours":
            return value / 3600
    elif from_unit == "Minutes":
        if to_unit == "Seconds":
            return value * 60
        elif to_unit == "Hours":
            return value / 60
    elif from_unit == "Hours":
        if to_unit == "Seconds":
            return value * 3600
        elif to_unit == "Minutes":
            return value * 60
    raise ValueError("Invalid time conversion")

def convert_area(value, from_unit, to_unit):
    if from_unit == "SquareMeters":
        if to_unit == "SquareKilometers":
            return value / 1e6
        elif to_unit == "Acres":
            return value * 0.000247105
    elif from_unit == "SquareKilometers":
        if to_unit == "SquareMeters":
            return value * 1e6
        elif to_unit == "Acres":
            return value * 247.105
    elif from_unit == "Acres":
        if to_unit == "SquareMeters":
            return value / 0.000247105
        elif to_unit == "SquareKilometers":
            return value / 247.105
    raise ValueError("Invalid area conversion")

def convert_volume(value, from_unit, to_unit):
    if from_unit == "Liters":
        if to_unit == "CubicMeters":
            return value / 1000
        elif to_unit == "Gallons":
            return value * 0.264172
    elif from_unit == "CubicMeters":
        if to_unit == "Liters":
            return value * 1000
        elif to_unit == "Gallons":
            return value * 264.172
    elif from_unit == "Gallons":
        if to_unit == "Liters":
            return value / 0.264172
        elif to_unit == "CubicMeters":
            return value / 264.172
    raise ValueError("Invalid volume conversion")

def convert_speed(value, from_unit, to_unit):
    if from_unit == "MetersPerSecond":
        if to_unit == "KilometersPerHour":
            return value * 3.6
    elif from_unit == "KilometersPerHour":
        if to_unit == "MetersPerSecond":
            return value / 3.6
    raise ValueError("Invalid speed conversion")

def convert_energy(value, from_unit, to_unit):
    if from_unit == "Joules":
        if to_unit == "Kilojoules":
            return value / 1000
        elif to_unit == "Calories":
            return value * 0.239006
    elif from_unit == "Kilojoules":
        if to_unit == "Joules":
            return value * 1000
        elif to_unit == "Calories":
            return value * 239.006
    elif from_unit == "Calories":
        if to_unit == "Joules":
            return value / 0.239006
        elif to_unit == "Kilojoules":
            return value / 239.006
    raise ValueError("Invalid energy conversion")

def convert_pressure(value, from_unit, to_unit):
    if from_unit == "Pascal":
        if to_unit == "Bar":
            return value / 100000
        elif to_unit == "PSI":
            return value * 0.000145038
    elif from_unit == "Bar":
        if to_unit == "Pascal":
            return value * 100000
        elif to_unit == "PSI":
            return value * 14.5038
    elif from_unit == "PSI":
        if to_unit == "Pascal":
            return value / 0.000145038
        elif to_unit == "Bar":
            return value / 14.5038
    raise ValueError("Invalid pressure conversion")

def convert_power(value, from_unit, to_unit):
    if from_unit == "Watts":
        if to_unit == "Kilowatts":
            return value / 1000
        elif to_unit == "Horsepower":
            return value / 745.7
    elif from_unit == "Kilowatts":
        if to_unit == "Watts":
            return value * 1000
        elif to_unit == "Horsepower":
            return value / 0.7457
    elif from_unit == "Horsepower":
        if to_unit == "Watts":
            return value * 745.7
        elif to_unit == "Kilowatts":
            return value * 0.7457
    raise ValueError("Invalid power conversion")

def convert_storage(value, from_unit, to_unit):
    units = ["Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes", "Petabytes"]
    conversion_factors = {
        "Bytes": 1,
        "Kilobytes": 1024,
        "Megabytes": 1024**2,
        "Gigabytes": 1024**3,
        "Terabytes": 1024**4,
        "Petabytes": 1024**5
    }
    
    if from_unit not in units or to_unit not in units:
        raise ValueError("Invalid storage unit conversion")
    
    value_in_bytes = value * conversion_factors[from_unit]
    return value_in_bytes / conversion_factors[to_unit]

# Display options for different categories
def display_options(category):
    print(f"\nSelect a conversion for {category}:")
    if category == "temperature":
        print("1. Celsius to Fahrenheit\n2. Fahrenheit to Celsius\n3. Celsius to Kelvin\n4. Kelvin to Celsius\n5. Fahrenheit to Kelvin\n6. Kelvin to Fahrenheit")
    elif category == "distance":
        print("1. Kilometers to Miles\n2. Miles to Kilometers\n3. Kilometers to Meters\n4. Meters to Kilometers\n5. Miles to Meters\n6. Meters to Miles")
    elif category == "weight":
        print("1. Kilograms to Pounds\n2. Pounds to Kilograms\n3. Kilograms to Grams\n4. Grams to Kilograms\n5. Pounds to Grams\n6. Grams to Pounds")
    elif category == "time":
        print("1. Seconds to Minutes\n2. Minutes to Seconds\n3. Hours to Minutes\n4. Minutes to Hours\n5. Seconds to Hours\n6. Hours to Seconds")
    elif category == "area":
        print("1. SquareMeters to SquareKilometers\n2. SquareKilometers to SquareMeters\n3. SquareMeters to Acres\n4. Acres to SquareMeters")
    elif category == "volume":
        print("1. Liters to CubicMeters\n2. CubicMeters to Liters\n3. Gallons to Liters\n4. Liters to Gallons")
    elif category == "speed":
        print("1. MetersPerSecond to KilometersPerHour\n2. KilometersPerHour to MetersPerSecond")
    elif category == "energy":
        print("1. Joules to Kilojoules\n2. Kilojoules to Joules\n3. Joules to Calories\n4. Calories to Joules\n5. Kilojoules to Calories\n6. Calories to Kilojoules")
    elif category == "pressure":
        print("1. Pascal to Bar\n2. Bar to Pascal\n3. Pascal to PSI\n4. PSI to Pascal\n5. Bar to PSI\n6. PSI to Bar")
    elif category == "power":
        print("1. Watts to Kilowatts\n2. Kilowatts to Watts\n3. Watts to Horsepower\n4. Horsepower to Watts\n5. Kilowatts to Horsepower\n6. Horsepower to Kilowatts")
    elif category == "storage":
        print("1. Bytes to Kilobytes\n2. Kilobytes to Bytes\n3. Kilobytes to Megabytes\n4. Megabytes to Kilobytes\n5. Megabytes to Gigabytes\n6. Gigabytes to Megabytes\n7. Gigabytes to Terabytes\n8. Terabytes to Gigabytes")

# Get input from user for value and option
def get_input_for_conversion():
    value = float(input("Enter the value to convert: "))
    option = int(input("Enter your conversion choice: "))
    return value, option

# Main program loop
def main():
    while True:
        print("\nUnit Converter")
        print("1. Temperature\n2. Distance\n3. Weight\n4. Time\n5. Area\n6. Volume\n7. Speed\n8. Energy\n9. Pressure\n10. Power\n11. Storage\n12. Exit")
        
        try:
            choice = int(input("Select a category (1-12): "))
            if choice == 1:
                display_options("temperature")
                value, option = get_input_for_conversion()
                conversions = {
                    1: ('Celsius', 'Fahrenheit'),
                    2: ('Fahrenheit', 'Celsius'),
                    3: ('Celsius', 'Kelvin'),
                    4: ('Kelvin', 'Celsius'),
                    5: ('Fahrenheit', 'Kelvin'),
                    6: ('Kelvin', 'Fahrenheit')
                }
                try:
                    result = convert_temperature(value, conversions[option][0], conversions[option][1])
                    print(f"{value} {conversions[option][0]} = {result} {conversions[option][1]}")
                except ValueError as e:
                    print(e)
            elif choice == 2:
                display_options("distance")
                value, option = get_input_for_conversion()
                conversions = {
                    1: ('Kilometers', 'Miles'),
                    2: ('Miles', 'Kilometers'),
                    3: ('Kilometers', 'Meters'),
                    4: ('Meters', 'Kilometers'),
                    5: ('Miles', 'Meters'),
                    6: ('Meters', 'Miles')
                }
                try:
                    result = convert_distance(value, conversions[option][0], conversions[option][1])
                    print(f"{value} {conversions[option][0]} = {result} {conversions[option][1]}")
                except ValueError as e:
                    print(e)
            elif choice == 3:
                display_options("weight")
                value, option = get_input_for_conversion()
                conversions = {
                    1: ('Kilograms', 'Pounds'),
                    2: ('Pounds', 'Kilograms'),
                    3: ('Kilograms', 'Grams'),
                    4: ('Grams', 'Kilograms'),
                    5: ('Pounds', 'Grams'),
                    6: ('Grams', 'Pounds')
                }
                try:
                    result = convert_weight(value, conversions[option][0], conversions[option][1])
                    print(f"{value} {conversions[option][0]} = {result} {conversions[option][1]}")
                except ValueError as e:
                    print(e)
            elif choice == 4:
                display_options("time")
                value, option = get_input_for_conversion()
                conversions = {
                    1: ('Seconds', 'Minutes'),
                    2: ('Minutes', 'Seconds'),
                    3: ('Hours', 'Minutes'),
                    4: ('Minutes', 'Hours'),
                    5: ('Seconds', 'Hours'),
                    6: ('Hours', 'Seconds')
                }
                try:
                    result = convert_time(value, conversions[option][0], conversions[option][1])
                    print(f"{value} {conversions[option][0]} = {result} {conversions[option][1]}")
                except ValueError as e:
                    print(e)
            elif choice == 5:
                display_options("area")
                value, option = get_input_for_conversion()
                conversions = {
                    1: ('SquareMeters', 'SquareKilometers'),
                    2: ('SquareKilometers', 'SquareMeters'),
                    3: ('SquareMeters', 'Acres'),
                    4: ('Acres', 'SquareMeters')
                }
                try:
                    result = convert_area(value, conversions[option][0], conversions[option][1])
                    print(f"{value} {conversions[option][0]} = {result} {conversions[option][1]}")
                except ValueError as e:
                    print(e)
            elif choice == 6:
                display_options("volume")
                value, option = get_input_for_conversion()
                conversions = {
                    1: ('Liters', 'CubicMeters'),
                    2: ('CubicMeters', 'Liters'),
                    3: ('Gallons', 'Liters'),
                    4: ('Liters', 'Gallons')
                }
                try:
                    result = convert_volume(value, conversions[option][0], conversions[option][1])
                    print(f"{value} {conversions[option][0]} = {result} {conversions[option][1]}")
                except ValueError as e:
                    print(e)
            elif choice == 7:
                display_options("speed")
                value, option = get_input_for_conversion()
                conversions = {
                    1: ('MetersPerSecond', 'KilometersPerHour'),
                    2: ('KilometersPerHour', 'MetersPerSecond')
                }
                try:
                    result = convert_speed(value, conversions[option][0], conversions[option][1])
                    print(f"{value} {conversions[option][0]} = {result} {conversions[option][1]}")
                except ValueError as e:
                    print(e)
            elif choice == 8:
                display_options("energy")
                value, option = get_input_for_conversion()
                conversions = {
                    1: ('Joules', 'Kilojoules'),
                    2: ('Kilojoules', 'Joules'),
                    3: ('Joules', 'Calories'),
                    4: ('Calories', 'Joules'),
                    5: ('Kilojoules', 'Calories'),
                    6: ('Calories', 'Kilojoules')
                }
                try:
                    result = convert_energy(value, conversions[option][0], conversions[option][1])
                    print(f"{value} {conversions[option][0]} = {result} {conversions[option][1]}")
                except ValueError as e:
                    print(e)
            elif choice == 9:
                display_options("pressure")
                value, option = get_input_for_conversion()
                conversions = {
                    1: ('Pascal', 'Bar'),
                    2: ('Bar', 'Pascal'),
                    3: ('Pascal', 'PSI'),
                    4: ('PSI', 'Pascal'),
                    5: ('Bar', 'PSI'),
                    6: ('PSI', 'Bar')
                }
                try:
                    result = convert_pressure(value, conversions[option][0], conversions[option][1])
                    print(f"{value} {conversions[option][0]} = {result} {conversions[option][1]}")
                except ValueError as e:
                    print(e)
            elif choice == 10:
                display_options("power")
                value, option = get_input_for_conversion()
                conversions = {
                    1: ('Watts', 'Kilowatts'),
                    2: ('Kilowatts', 'Watts'),
                    3: ('Watts', 'Horsepower'),
                    4: ('Horsepower', 'Watts'),
                    5: ('Kilowatts', 'Horsepower'),
                    6: ('Horsepower', 'Kilowatts')
                }
                try:
                    result = convert_power(value, conversions[option][0], conversions[option][1])
                    print(f"{value} {conversions[option][0]} = {result} {conversions[option][1]}")
                except ValueError as e:
                    print(e)
            elif choice == 11:
                display_options("storage")
                value, option = get_input_for_conversion()
                conversions = {
                    1: ('Bytes', 'Kilobytes'),
                    2: ('Kilobytes', 'Bytes'),
                    3: ('Kilobytes', 'Megabytes'),
                    4: ('Megabytes', 'Kilobytes'),
                    5: ('Megabytes', 'Gigabytes'),
                    6: ('Gigabytes', 'Megabytes'),
                    7: ('Gigabytes', 'Terabytes'),
                    8: ('Terabytes', 'Gigabytes')
                }
                try:
                    result = convert_storage(value, conversions[option][0], conversions[option][1])
                    print(f"{value} {conversions[option][0]} = {result} {conversions[option][1]}")
                except ValueError as e:
                    print(e)
            elif choice == 12:
                print("Exiting the program.")
                break
            else:
                print("Invalid choice. Please choose a number between 1 and 12.")
        except ValueError:
            print("Invalid input. Please enter a number.")
            
# Run the program
if __name__ == "__main__":
    main()
  

sample output

Unit Converter Using Python 01
Unit Converter Using Python 02
Unit Converter Using Python 03

Scenario: Calculating the Temperature category to convert 100 degrees Celsius to Fahrenheit. Step 1:Start of Program: The program starts by displaying the main menu with a list of categories. The user selects category 1 for Temperature: Select a category (1-12): 1. Temperature 2. Distance 3. Weight 4. Time 5. Area 6. Volume 7. Speed 8. Energy 9. Pressure 10. Power 11. Storage 12. Exit The user enters 1 for Temperature. Step 2: The program displays the available temperature conversions: Select a conversion for temperature: 1. Celsius to Fahrenheit 2. Fahrenheit to Celsius 3. Celsius to Kelvin 4. Kelvin to Celsius 5. Fahrenheit to Kelvin 6. Kelvin to Fahrenheit Step 3: The program asks for the input value (100 degrees Celsius): Enter the value to convert: 100 Step 4: The user selects option 1 (Celsius to Fahrenheit). Step 5: The program performs the conversion: Using the formula Fahrenheit = (Celsius * 9/5) + 32, it calculates: Fahrenheit = (100 * 9/5) + 32 = 212 Step 6: The result is displayed: 100 Celsius = 212 Fahrenheit

Conclusion

The Comprehensive Unit Converter project demonstrates the flexibility and power of Python in creating utility programs. It covers various unit conversion types and is structured in a way that allows for easy expansion and customization. The program uses basic Python concepts such as functions, conditionals, and loops to create a user-friendly and interactive tool for anyone needing to convert between different units of measurement. By following a clear flow of operations and providing informative error handling, the program ensures that users can perform conversions confidently and without confusion.

End of Post