我已经在下面编写了Python代码(实际上它是我在第24页的“在24小时内自学Python”练习的解决方案)。如何在循环内发出警告并要求输入raw_input
想法是:餐桌周围有4个座位,服务员知道每个座位的订购量,输入这4个数量并获得总数。
如果提供的raw_input不是一个数字(而是一个字符串),我的代码会将这个人踢出去。但是,目标是给出错误消息(“此条目无效”)并再次询问输入 - 直到它为数字。但是,我无法弄清楚如何再次询问用户的原始输入 - 因为我已经在循环中了。
非常感谢您的建议!
def is_numeric(value):
try:
input = float(value)
except ValueError:
return False
else:
return True
total = 0
for seat in range(1,5):
print 'Note the amount for seat', seat, 'and'
myinput = raw_input("enter it here ['q' to quit]: ")
if myinput == 'q':
break
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
else:
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput)
break
if myinput == 'q':
print "Goodbye!"
else:
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
非常感谢 - 这个解决方案非常棒! – user3245256