![](/img/trans.png)
[英]simplest way to convert either a float or an int to the nearest integer in Python
[英]Python: Users choosing either an int or a float
这可能是一个非常基本的问题,但是我是Python的新手。 我正在构建一个简单的距离转换工具,我希望用户可以根据其测量值来选择输入浮点数或整数。 除了十亿个if语句(每个度量单位一个,例如英寸到厘米或英尺到米),还有没有做到这一点的合适方法?
编辑:这是我的代码的片段
#if imperial, offer choices of inch, foot, or mile
if disType == "i":
print """
What unit of measurement do you want to convert?
inches to centimeters: i
feet to meters: f
miles to kilometers: m
"""
unitType = raw_input(prompt)
#if unit is inches, prompt user for number of
#inches and convert to centimeters
if unitType == "i":
print "Please input distance in inches"
inches = int(raw_input(prompt))
centimeters = inches * 2.54
print "That is %i centimeters" % centimeters
如果用户输入一个小数,我希望能够解决这个问题。 但是对于每次转换,我都有其中一种if语句(仅距离转换为6次转换)。 我宁愿不为浮点数分支的每个分支添加if语句。
您似乎在没有一堆if语句的情况下如何实现单位转换时遇到麻烦,对吗?
如果我是你,我会这样做:
conv_func = {
'inch': func_for_inch_conv,
'cm': func_for_cm_conv,
...
}
data = raw_input() # prompt the user to enter data in the form '1 inch'
mag, unit = data.split(' ')
result = conv_func[unit](mag)
我不知道这是否是解决问题的好方法,但这就是我的想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.