【发布时间】:2015-11-12 11:51:45
【问题描述】:
我是编程新手,我正在尝试用 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
感谢您的帮助。
【问题讨论】:
-
这个问题是关于改进工作代码的。更适合Code Review。
-
@FrédéricHamidi 谢谢,我会在那里发帖,我什至不知道它存在。
-
你的意思是写的很慢?
-
@PeterWood 是的,一旦我完成了所有组合,这将需要很长时间。我还希望增加重量、速度、能量和数据存储。
-
为了将来的通知,如果您想将您的问题转移到另一个 SE 站点,您可以将其标记为审核并请求将其移动到所需的新站点。
标签: python converter units-of-measurement