2016-01-29 120 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