我正在尝试从书籍作业中编写一个小程序,但是我在检测用户输入是否为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
任何答案将不胜感激.
使用异常来捕获无法汇总的用户输入.从测试任何用户输入切换到仅保护数学运算以总结收据.
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
您始终可以使用该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
请记住:请求宽恕比获得更容易