2016-02-05 144 views
-3

我想循環嘗試,除了我的菜單選項,部分代碼如下,我只是想知道如何無限循環,以避免程序崩潰...我嘗試了一段時間的真正循環,但我失敗了嘗試和除了沒有循環 - Python

錯誤的位置:http://imgur.com/o3F5phb

while True: 
    try: 
     choice = int(input("What would you like to do?\n1)Code a word\n2)Decode a word\n3)Print the coded words list\n4)Quit the program\n5)Clear Coded Words List\n>>>"))#Asking for choice from user 
    except ValueError: 
     print("Invalid entry! Try again") 
     choice =int(input("What would you like to do?\n1)Code a word\n2)Decode a word\n3)Print the coded words list\n4)Quit the program\n5)Clear Coded Words List\n>>>"))#Asking for choice from user 
     continue 
    else: 
     break 

回答

3

沿

valid_entry = False 
while not valid_entry: 
    try: 
     choice = (...) 
    except ValueError: 
     print("Invalid entry! Try again") 
    else: 
     valid_entry = True 
< here you have a valid choice variable and valid_entry is True > 
0

試試如果你想這個片段循環您需要引入,很好,一環。例如:

input_valid = False 
while not input_valid: 
    try: 
     choice=int(input("What would you like to do?\n1)Code a word\n2)Decode a word\n3)Print the coded words list\n4)Quit the program\n5)Clear Coded Words List\n>>>"))#Asking for choice from user 
     input_valid = True 
    except ValueError: 
     print("Invalid Entry!\nPlease Try Again\n") 
+0

基於反饋我改變了我的代碼,仍然得到了錯誤 –