Python中的简单单元转换器

2024-04-20 13:36:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程新手,我正在尝试用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

谢谢你的帮助。


Tags: andtowhichinputrawcm单位float
2条回答

可以使用带转换因子的字典,以及调用它们的函数。

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

你可以在这个例子中使用字典。

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)()

相关问题 更多 >