PHP

a simple Python program for unit conversion

Here’s how to create a simple Python program for unit conversion.

This unit converter will allow conversions between several units, such as miles to kilometers, kilometers to miles, pounds to kilograms, and kilograms to pounds.

We’ll use a dictionary to map conversion functions, and the program will prompt the user for input and perform the desired conversion.

Code

def miles_to_kilometers(miles):
    return miles * 1.60934

def kilometers_to_miles(kilometers):
    return kilometers * 0.621371

def pounds_to_kilograms(pounds):
    return pounds * 0.453592

def kilograms_to_pounds(kilograms):
    return kilograms * 2.20462

# Dictionary to map choices to functions
conversion_functions = {
    '1': ('Miles to Kilometers', miles_to_kilometers),
    '2': ('Kilometers to Miles', kilometers_to_miles),
    '3': ('Pounds to Kilograms', pounds_to_kilograms),
    '4': ('Kilograms to Pounds', kilograms_to_pounds),
}

# Display conversion options
def display_menu():
    print("Choose a conversion type:")
    for key, (name, _) in conversion_functions.items():
        print(f"{key}. {name}")

# Perform the conversion
def convert_units():
    while True:
        display_menu()
        
        choice = input("Enter the conversion type (or 'q' to quit): ")
        if choice.lower() == 'q':
            print("Exiting the Unit Converter.")
            break

        if choice in conversion_functions:
            unit_name, conversion_function = conversion_functions[choice]
            try:
                value = float(input(f"Enter the value to convert for {unit_name}: "))
                result = conversion_function(value)
                print(f"Converted value: {result}\n")
            except ValueError:
                print("Please enter a valid number.\n")
        else:
            print("Invalid choice. Please select a valid option.\n")

# Start the unit converter
convert_units()

Explanation

  1. Define Conversion Functions:
    • miles_to_kilometers(miles): Converts miles to kilometers by multiplying miles by 1.60934.
    • kilometers_to_miles(kilometers): Converts kilometers to miles by multiplying kilometers by 0.621371.
    • pounds_to_kilograms(pounds): Converts pounds to kilograms by multiplying pounds by 0.453592.
    • kilograms_to_pounds(kilograms): Converts kilograms to pounds by multiplying kilograms by 2.20462.
  2. Dictionary for Conversion Options:
    • conversion_functions: This dictionary maps each option (e.g., ‘1’ for miles to kilometers) to a tuple containing the conversion name and corresponding function.
    • This approach makes it easy to add more conversions later.
  3. Display Menu (display_menu function):
    • This function displays the available conversion options.
    • It iterates through the conversion_functions dictionary and displays each option’s key and name.
  4. Conversion Logic (convert_units function):
    • This function is the main loop of the program, handling user input and performing conversions.
    • User Choice:
      • Displays the menu by calling display_menu().
      • Prompts the user to select a conversion type or enter ‘q’ to quit.
    • Conversion Execution:
      • Checks if the user’s choice is in conversion_functions.
      • If valid, it:
        • Retrieves the unit_name and conversion_function from the dictionary.
        • Prompts the user to input a value to convert.
        • Calls the appropriate conversion function.
        • Displays the result.
    • Error Handling:
      • If the user enters a non-numeric value, it catches the ValueError and displays an error message.
    • Invalid Choice Handling:
      • If the choice is not in conversion_functions, it displays an invalid choice message.
  5. Run the Converter:
    • convert_units() starts the program, displaying the menu and prompting for conversions.

Sample Output

>>> %Run convertunits.py
Choose a conversion type:
1. Miles to Kilometers
2. Kilometers to Miles
3. Pounds to Kilograms
4. Kilograms to Pounds
Enter the conversion type (or 'q' to quit): 1
Enter the value to convert for Miles to Kilometers: 12
Converted value: 19.31208

Choose a conversion type:
1. Miles to Kilometers
2. Kilometers to Miles
3. Pounds to Kilograms
4. Kilograms to Pounds
Enter the conversion type (or 'q' to quit): 3
Enter the value to convert for Pounds to Kilograms: 50
Converted value: 22.6796

Choose a conversion type:
1. Miles to Kilometers
2. Kilometers to Miles
3. Pounds to Kilograms
4. Kilograms to Pounds
Enter the conversion type (or 'q' to quit):

Important Notes

  • Modularity: Each conversion is a separate function, making the code modular and easy to extend with additional conversions.
  • Error Handling: The code checks for invalid input, helping avoid program crashes due to incorrect data types.
  • Extensibility: Adding new conversions is straightforward: simply define a new conversion function and add an entry to conversion_functions.

Summary

This Python program provides a basic, text-based unit converter that performs conversions between miles and kilometers, as well as pounds and kilograms.

The convert_units() function handles user input and calls the relevant conversion function based on the selected option, making it easy to expand and modify for additional units.