我想反复询问用户输入(选择菜单选项),直到他们选择有效选项。
我的主菜单是:
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.")
如果他们没有输入E
,D
或X
,我希望此菜单再次显示,并重新启动该程序。
到目前为止,我有:
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 :(得分: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
。