【问题标题】:Python: Users choosing either an int or a floatPython:用户选择 int 或 float
【发布时间】:2016-02-18 05:53:16
【问题描述】:

这可能是一个非常基本的问题,但我对 Python 有点陌生。我正在构建一个简单的距离转换工具,我希望用户可以选择输入浮点数或整数,具体取决于他们的测量值。除了十亿个 if 语句(每个测量单位一个,例如英寸到厘米或英尺到米)之外,还有没有合适的方法来做到这一点?

编辑:这是我的代码的 sn-p

#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 语句(仅距离的六次转换)。我宁愿不为每一个在浮点情况下分支的语句添加一个 if 语句。

【问题讨论】:

  • 您是否总是希望它从英制转换为公制?
  • 用户输入一个字符串。您可以根据需要将其转换为 int 或 float。而且 - int 与 float 到底与单位选择有什么关系?小数值可以在任何系统中使用。
  • 请发布您的代码的 sn-p 或给出您想要实现的目标的清晰示例。 stackoverflow.com/help/how-to-ask
  • 为什么要区分float和int?把所有东西都当作浮动。
  • @JohnColeman 它与单位本身无关,但它与让用户可以选择输入整数或小数值的测量值有关。我只是想让您了解我的工作内容。而且我不想在不需要时处理使用浮点数的不准确性。如果用户最初输入它,我想使用 int,但不想将它们限制为它。

标签: python python-2.7 floating-point int user-input


【解决方案1】:

在没有一堆 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)

我不知道这是否是解决它的好方法,但这是我的想法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多