显示菜单,直到用户输入符合条件

时间:2016-01-29 20:05:46

标签: python

我想反复询问用户输入(选择菜单选项),直到他们选择有效选项。

我的主菜单是:

print ("Please choose whether you would like to encrypt a message, decrypt a message or exit the program.")
userSelection = input("Please type E for encrypt message\n D for decrypt message or\n X to exit the program.")

如果他们没有输入EDX,我希望此菜单再次显示,并重新启动该程序。

到目前为止,我有:

while True:
    userSelection != "E" or userSelection !=  "e" or userSelection != "D" or userSelection != "d" or userSelection != "X" or userSelection != "x"
    print ("Please choose an option from the menu.")
    break

如何让它返回?

1 个答案:

答案 0 :(得分:0)

使用while循环!

userSelectionOptions = ['e', 'd', 'x']
print ("Please choose an option from the menu.")
user_input = ''
user_input = input("Please type E for encrypt message\n D for decrypt message or\n X to exit the program: \n")
while user_input.lower() not in userSelectionOptions:
    print ("Please choose an option from the menu.")
    user_input = input("Please type E for encrypt message\n D for decrypt message or\n X to exit the program: \n")

# do stuff with the input

使用此代码,您首先要求用户输入,然后尝试验证它。如果验证失败,则用户进入while循环,直到他们给出的输入有效。

注意:已编辑以包含您的输入代码。请记住,如果您运行的是python2.7,则需要使用raw_input