【问题标题】:While loop not handling the exceptionWhile循环不处理异常
【发布时间】:2018-11-13 05:12:27
【问题描述】:

以下是所选城市的列表:

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

【问题讨论】:

  • input() 接受任何内容。我不认为它可以提高ValueError
  • 我意识到,当我发帖时,我在 except 中添加了一个 if 语句,让它知道是否有一个选项未被选中。仍然没有为我工作。
  • 更新您的问题以包含您实际使用的最新代码。
  • Try-except-structures 用于捕获让您的程序退出的错误,因为它无法再处理某事(div 0 或某事类似)。你试图捕捉的是一个语义错误,即关于 you 作为程序作者最初想要拥有的错误,但现在(例如由于用户输入)与它不同 应该在你的脑海里。为此,您需要 if ... elif ... else。

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


【解决方案1】:

不需要try/except。只需使用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.")

【讨论】:

  • 我想我在这里过于复杂了。感谢您的输入。我相信我的困惑源于我最近阅读的部分有异常处理。
猜你喜欢
  • 2014-11-11
  • 1970-01-01
  • 2013-09-21
  • 1970-01-01
  • 2016-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
相关资源
最近更新 更多