以下是城市选择的清单:
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
答案 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.")