question = input('Please choose one. add, times, divide, minus')
if (question=='add'):
if (question=='times'):
if (question=='divide'):
if (question=='minus'):
我想这样做,如果我输入别的东西,它会让我再次输入而不是错误
答案 0 :(得分:1)
使用elif
将您的条件联系在一起;然后只会选择一个匹配条件:
if (question=='add'):
elif (question=='times'):
elif (question=='divide'):
elif (question=='minus'):
额外的好处是你现在可以使用else
块来捕捉用户选择以上的情况:
if (question=='add'):
elif (question=='times'):
elif (question=='divide'):
elif (question=='minus'):
else:
您可以在无限循环中提出问题,并使用break
逐步退出该循环,并使用continue
从顶部重新启动循环:
while True:
question = input('Please choose one. add, times, divide, minus')
if (question=='add'):
#
elif (question=='times'):
#
elif (question=='divide'):
#
elif (question=='minus'):
#
else:
print('Please enter a valid option!')
continue
# we got here, so we must've had a proper input
break
另请参阅Stack Overflow上的规范Asking the user for input until they give a valid response问题。
答案 1 :(得分:0)
除非他/她输入正确的输入,否则它将持续ping用户
while True:
question = input('Please choose one. add, times, divide, minus')
if (question=='add'):
#Do processing
break
elif (question=='times'):
#Do processing
break
elif (question=='divide'):
#Do processing
break
elif (question=='minus'):
#Do processing
break
else:
print "Please enter a valid input !"
答案 2 :(得分:0)
继续问:
question = ''
while question not in ('add', 'times', 'divide', 'minus'):
question = input('Please choose one. add, times, divide, minus')
if question == 'add':
# do something
elif question == 'times':
# do something
...
注意,要中断循环,答案必须是其中一种选择。