我正在尝试根据书本作业编写一个小程序,但我无法检测用户的输入是 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
关于Python:如果变量是整数或 float 则为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23406670/