我正在尝试从图书作业中编写一个小程序,但我无法检测用户的输入是int/float
(增加到总数)还是string
(return error
)。我尝试在 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
任何答案都将不胜感激。
答案 0 :(得分:5)
使用例外来捕获无法概括的用户输入。从测试任何用户输入切换到仅保护数学运算来总结收据。
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
答案 1 :(得分:5)
您始终可以使用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
答案 2 :(得分:4)
非常接近旧条目:How can I check if my python object is a number?。答案是:
isinstance(x, (int, long, float, complex))