我想这样做,如果你输入错误的文字它仍然有效吗?

时间:2015-02-05 11:57:36

标签: python python-2.7 variables if-statement input

question = input('Please choose one. add, times, divide, minus')

if (question=='add'):
if (question=='times'):
if (question=='divide'):
if (question=='minus'):

我想这样做,如果我输入别的东西,它会让我再次输入而不是错误

3 个答案:

答案 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
...

注意,要中断循环,答案必须是其中一种选择。