Python Unit Converter
This utility converts values between different units of measurement (like length and weight) using a dictionary of conversion factors. It demonstrates how to normalize data to a "base unit" to perform conversions between any two supported units.
Modules Used:
- argparse: To handle command-line arguments.
The Code
Save this as converter.py.
import argparse
# Conversion factors relative to a base unit
# Length base: meter (m)
# Weight base: kilogram (kg)
CONVERSIONS = {
'length': {
'm': 1.0,
'km': 1000.0,
'cm': 0.01,
'mm': 0.001,
'mi': 1609.344,
'yd': 0.9144,
'ft': 0.3048,
'in': 0.0254,
},
'weight': {
'kg': 1.0,
'g': 0.001,
'mg': 0.000001,
'lb': 0.45359237,
'oz': 0.02834952,
}
}
def convert_units(value, from_unit, to_unit):
# 1. Identify the category (length, weight, etc.)
category = None
for cat, units in CONVERSIONS.items():
if from_unit in units and to_unit in units:
category = cat
break
if category is None:
print(f"Error: Conversion from '{from_unit}' to '{to_unit}' is not supported.")
print("Supported units:")
for cat, units in CONVERSIONS.items():
print(f" {cat.capitalize()}: {', '.join(units.keys())}")
return
# 2. Perform conversion: Source -> Base -> Target
factors = CONVERSIONS[category]
# Convert input to base unit (e.g., km -> m)
base_value = value * factors[from_unit]
# Convert base unit to target unit (e.g., m -> ft)
final_value = base_value / factors[to_unit]
print(f"{value} {from_unit} = {final_value:.4f} {to_unit}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="CLI Unit Converter")
parser.add_argument("value", type=float, help="Numeric value to convert")
parser.add_argument("from_unit", help="Source unit (e.g., km, lb)")
parser.add_argument("to_unit", help="Target unit (e.g., mi, kg)")
args = parser.parse_args()
convert_units(args.value, args.from_unit.lower(), args.to_unit.lower())
Usage
# Convert 5 Kilometers to Miles
python converter.py 5 km mi
# Convert 150 Pounds to Kilograms
python converter.py 150 lb kg