虽然循环不处理异常



以下是选择城市的列表:

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

不需要尝试/例外。 只需使用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.")

相关内容

  • 没有找到相关文章

最新更新