Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple unit converter in Python

I am new to programming and I am trying to make a simple unit converter in python. I want to convert units within the metric system and metric to imperial and vice-versa. I have started with this code and I found this method is slow and in-efficient, How can I code this more efficiently?

import math
import time
"""Unit Converter"""
#variable setting
cat = raw_input ("Which category would you like to convert? we support length(l) and Weight(w):  ")
if cat == ("l"):
unit1 = raw_input ("Which unit would you like to convert from: ")
unit2 = raw_input ("Which unit would you like to convert to: ")
num1 = raw_input ("Enter your value: " )
    
    ##Calculations  
    
if unit1 == "cm" and unit2 == "m":
    ans = float(num1)/100       
elif unit1 == "mm" and unit2 == "cm":
    ans = float(num1)/10
elif unit1 == "m" and unit2 == "cm":
    ans = float(num1)*100
elif unit1 == "cm" and unit2 == "mm":
    ans = float(num1)*10
elif unit1 == "mm" and unit2 == "m":
    ans = float(num1)/1000
elif unit1 == "m" and unit2 == "mm":
    ans = float(num1)*1000  
elif unit1 == "km" and unit2 == "m":
    ans = float(num1)*1000
elif unit1 == "m" and unit2 == "km":
    ans = float(num1)/1000
elif unit1 == "mm" and unit2 == "km":
    ans = float(num1)/1000000

Thanks for your help.

like image 460
SalamalCamel Avatar asked Sep 01 '26 04:09

SalamalCamel


1 Answers

You could use a dictionary with conversion factors, and a function that calls them.

def convert_si(val: float, unit_in: str, unit_out: str) -> float:
    SI = {'mm': 0.001, 'cm': 0.01, 'm': 1.0, 'km': 1000.0}
    return val * SI[unit_in] / SI[unit_out]

Example:

>>> convert_si(1, 'm', 'km')
0.001
>>> convert_si(1, 'km', 'm')
1000.0
>>> convert_si(1, 'cm', 'm')
0.01
like image 189
ryanjdillon Avatar answered Sep 03 '26 17:09

ryanjdillon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!