-3

I am trying to loop around a try and except for my menu options, part of the code is below, I am just wondering how I can infinitely loop this to avoid program crashing ... I tried a while true loop but I failed!

error here : https://i.stack.imgur.com/Euk1L.jpg

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

2 Answers2

3

Try something along

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 >
MariusSiuram
  • 3,380
  • 1
  • 21
  • 40
0

If you want this snippet to loop you need to introduce, well, a loop. E.g.:

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")
Falko
  • 17,076
  • 13
  • 60
  • 105
Mureinik
  • 297,002
  • 52
  • 306
  • 350