我已经编写了下面的Python代码(实际上,这是我在“24小时内自学Python”第80页的练习解决方案。)
这个想法是:桌子周围有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!"
答案 0 :(得分:2)
通常,当您不知道要运行循环的次数时,解决方案是while
循环。
for seat in range(1,5):
my_input = raw_input("Enter: ")
while not(my_input == 'q' or isnumeric(my_input)):
my_input = raw_imput("Please re-enter value")
if my_input == 'q':
break
else:
total += float(my_input)
答案 1 :(得分:0)
total = 0
for seat in range(1,5):
incorrectInput = True
while(incorrectInput):
print 'Note the amount for seat', seat, 'and'
myinput = raw_input("enter it here ['q' to quit]: ")
if myinput == 'q':
print 'Goodbye'
quit()
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
incorrectInput = False
else:
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput)
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
答案 2 :(得分:0)
正如Patrick Haugh和SilentLupin所说,while
循环可能是最好的方法。另一种方式是递归 - 即,一遍又一遍地调用相同的函数,直到获得有效的输入:
def is_numeric(value):
try:
input = float(value)
except ValueError:
return False
else:
return True
def is_q(value):
return value == 'q'
def is_valid(value, validators):
return any(validator(input) for validator in validators)
def get_valid_input(msg, validators):
value = raw_input(msg)
if not is_valid(value, validators):
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(value)
value = get_valid_input(msg, validators)
return value
total = 0
for seat in range(1,5):
print 'Note the amount for seat', seat, 'and'
myinput = get_valid_input("enter it here ['q' to quit]: ", [is_q, is_numeric])
if myinput == 'q':
break
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
if myinput == 'q':
print "Goodbye!"
else:
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
在上面的代码中,get_valid_input
一遍又一遍地调用自己,直到其中一个提供的validators
产生了一些真实的东西。