1

Here is the list from the selection of cities:

city_choice = ["chicago","new york city","washington"]

Within the while loop below I am trying to have the user input a city from the list with an exception handler to let user know that isn't a choice and to select from the list. Why is the while loop not processing that?

while True:
try:
    city = input("Please enter city: ")
except ValueError:
    if city != [0,2]:
        print("Sorry, that isn\'t a choice.")
        #try again
        continue
    else:
        #city was successfully selected
        #Exit the loop.
        break
  • `input()` accepts anything. I don't think it can ever raise `ValueError`. – John Gordon Jun 03 '18 at 20:58
  • I realized that when I posted, I added an if statement within the except to let it know if one the choices were not selected. Still didn't work for me. – Walter Solares Jun 03 '18 at 20:59
  • Update your question to contain the latest code you're actually using. – John Gordon Jun 03 '18 at 20:59
  • Try-except-structures are for catching errors which let your program exit because it cannot handle sth anymore (div 0 or sth similar). What you are trying to catch is a semantic error, ie an error with respect what _you_ as the author of the program initially wanted to have, but now (eg because of user input) came different than it _should in your mind_. For this, you need if ... elif ... else. – SpghttCd Jun 03 '18 at 21:06

1 Answers1

1

No need for try/except. Just use the in operator:

city_choice = ["chicago","new york city","washington"]

while True:
    city = input("Please enter city: ")
    if city in city_choice:
        break
    print("Sorry, that isn\'t a choice.")
John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • I think I was over complicating here. Thanks for the input. I believe my confusion stems from the fact that the section I was reading recently had exception handling. – Walter Solares Jun 03 '18 at 21:05