【问题标题】:Python: True if variable is integer or floatPython:如果变量是整数或浮点数,则为真
【发布时间】:2014-06-17 20:53:45
【问题描述】:

我正在尝试根据书籍作业编写一个小程序,但我无法检测用户的输入是int/float(总数的增量)还是stringreturn error)。我尝试在 add_to_total 变量上使用 .isdigit(),但是当我输入浮点数时,它会直接跳到 else 代码块。我尝试在互联网上搜索,但找不到明确的答案。这是我的代码:

total = 0
print("Welcome to the receipt program!")

while True:
    add_to_total = raw_input("Enter the value for the seat ['q' to quit]: ")
    if add_to_total == 'q':
        print("*****")
        print "Total: $%s" % total
        break
    if add_to_total.isdigit(): #Don't know how to detect if variable is int or float at the same time.
        add_to_total = float(add_to_total)
        total += add_to_total
    else:
        print "I'm sorry, but '%s' isn't valid. Please try again." % add_to_total

任何答案将不胜感激。

【问题讨论】:

    标签: python variables methods integer int


    【解决方案1】:

    使用异常来捕获无法汇总的用户输入。从测试任何用户输入切换到仅保护数学运算以总结收据。

    total = 0
    print("Welcome to the receipt program!")
    
    while True:
        add_to_total = raw_input("Enter the value for the seat ['q' to quit]: ")
        if add_to_total == 'q':
            break
        try:
            total += float(add_to_total)
        except ValueError:
            print "I'm sorry, but '%s' isn't valid. Please try again." % add_to_total
    print("*****")
    print "Total: $%s" % total
    

    【讨论】:

    • 谢谢,它成功了。我想我以前尝试过使用这种方法,但把它放在了错误的地方。接受的答案。
    【解决方案2】:

    您始终可以使用try... except 方法:

    try:
        add_to_total = float(add_to_total)
    except ValueError:
        print "I'm sorry, but '%s' isn't valid. Please try again." % add_to_total
    else:
        total += add_to_total
    

    记住:it's easier to ask forgiveness than permission

    【讨论】:

      【解决方案3】:

      非常接近旧条目:How can I check if my python object is a number?。答案是:

      isinstance(x, (int, long, float, complex))
      

      【讨论】:

      • OP 正在检查字符串是否可以转换为数字,而不是现有对象是否具有数字类型。
      猜你喜欢
      • 2019-01-23
      • 1970-01-01
      • 2010-11-24
      • 2016-02-09
      • 2011-01-30
      • 1970-01-01
      • 2022-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多