while循环不处理异常

时间:2018-06-03 20:54:56

标签: python python-3.x while-loop exception-handling user-input

以下是城市选择的清单:

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

在下面的while循环中,我试图让用户从列表中输入一个带有异常处理程序的城市,让用户知道这不是一个选择并从列表中选择。为什么while循环没有处理呢?

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

1 个答案:

答案 0 :(得分:1)

无需尝试/除外。只需使用in运算符:

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.")
相关问题