我是编程新手,我正在尝试在python中创建一个简单的单位转换器。我想将公制系统中的单位和公制转换为英制,反之亦然。我已经开始使用这段代码了,我发现这种方法速度慢且效率低,如何更有效地编码?
import math
import time
"""Unit Converter"""
#Welcome and variable setting
print ("Welcome to Sam's Unit Converter")
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
感谢您的帮助。
答案 0 :(得分:4)
您可以使用包含转换因子的字典以及调用它们的函数。
def convert_SI(val, unit_in, unit_out):
SI = {'mm':0.001, 'cm':0.01, 'm':1.0, 'km':1000.}
return val*SI[unit_in]/SI[unit_out]
示例:强>
In [18]: convert_SI(1, 'm', 'km')
Out[18]: 0.001
In [19]: convert_SI(1, 'km', 'm')
Out[19]: 1000.0
In [20]: convert_SI(1, 'cm', 'm')
Out[20]: 0.01
答案 1 :(得分:0)
您可以在此示例中使用字典。
def handle_one():
print 'one'
def handle_two():
print 'two'
def handle_three():
print 'three'
print 'Enter 1 for handle_one'
print 'Enter 2 for handle_two'
print 'Enter 3 for handle_three'
choice=raw_input()
{
'1': handle_one,
'2': handle_two,
'3': handle_three,
}.get(choice)()