2016-02-05 97 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

基于反馈我改变了我的代码,仍然得到了错误 –