Python:如果变量是整数或 float 则为真

标签 python variables methods integer int

我正在尝试根据书本作业编写一个小程序,但我无法检测用户的输入是 int/float(对总数的增量)还是 string (返回错误)。我尝试在 add_to_total 变量上使用 .isdigit() 但是当我输入一个 float 时,它会直接跳到 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

如有任何答复,我们将不胜感激。

最佳答案

您始终可以使用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

关于Python:如果变量是整数或 float 则为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23406670/

相关文章:

python - 使用 PYMYSQL 更正 Python 中的 SQL 用法

java - 覆盖实例化 Java 对象中的方法

methods - AudioFileGetProperty - .mm 源文件中没有匹配的函数调用,但在 .m 中可以吗?

python - Tensorflow中如何使用image_summary查看不同批处理的图片?

python - 如何在 Python 3 的 dateutil 解析器中解析超过 24 小时的日期?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php - php可接受使用or命令分配变量时产生错误?

regex - 使用ansible从变量中解析子字符串

python - Python 解释器是否将实例绑定(bind)到方法或 self 参数?

python - 用 Python 求解幂律分布