2016-01-29 41 views
0

我想反复询问用户输入(选择一个菜单选项),直到他们选择一个有效的选项。显示菜单,直到用户输入满足条件

我的主菜单是:

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 

我怎么会把它弄回来?

+0

我编辑了你的问题,特别是:代码块应该缩进4个空格以适当突出显示,并且内联代码应该在反引号之间。我还添加了一个问题陈述,并重新提出了问题标题。您可以进一步改进您的问题,只需添加程序中发生的情况,以及您期望发生的情况,或者明确指出您的方式。 –

+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