虽然在 Python 3 中尝试除外

While Try Except in Python 3

我为此苦苦思索了几个小时,终于弄明白了。当然,现在对我来说这似乎很明显,但也许有一天其他人会被困在同一个地方,所以我想我会问和答。当然欢迎任何更正或解释。

缩略代码:

bearNames = {
    'grizzly' : 'GZ',
    'brown' : 'BR',
}

bearAttributes = {
    'GZ' : 'huge and light brown',
    'BR' : 'medium and dark brown',
}

print("Type the name of a bear:")
userBear = input("Bear: ")

beartruth = True
while beartruth == True:

    try:
        print("Abbreviation is ", bearNames[userBear])
        print("Attributes are ", bearAttributes[bearNames[userBear]])
        print("beartruth: ", beartruth)
        beartruth = False
        print("beartruth: ", beartruth)

    except:
        print("Something went wrong - did you not type a bear name?")
        print("beartruth: ", beartruth)

问题 - 输入不是熊的东西会永远循环 "except" 部分。我想要发生的事情应该很明显 - 如果用户输入的内容不在 bearNames 中,它应该触发 except,打印错误并返回尝试。

我最终想出的答案是将 input() 放在 while 中。解释...

编写的代码首先要求用户输入,然后开始。如果用户输入“grizzly”,则尝试成功,并且 bearTruth 设置为 false,从而打破循环。 (也许 break 语句在这里有用,但我还没有达到 break 语句的程度 :) )

如果用户输入的不是熊,则输入完成,然后开始尝试。它失败了,但我们已经在 while 内,并且用户输入已设置。所以再次尝试使用相同的 userBear 值,再次失败,并永远循环。

也许有一天像我这样愚蠢的人会遇到这个问题并找到这个解决方案。

由于您要求更正或解释。

来自您的代码

try:
    print("Abbreviation is ", bearNames[userBear])
    print("Attributes are ", bearAttributes[bearNames[userBear]])
    print("beartruth: ", beartruth)
    beartruth = False
    print("beartruth: ", beartruth)

except:
    print("Something went wrong - did you not type a bear name?")
    print("beartruth: ", beartruth)

您可以使用 Exceptions 来具体说明(我会推荐它),以确保隔离您可能预期的错误。

try:
    print("Abbreviation is ", bearNames[userBear])
except KeyError:
    print("Something went wrong - did you not type a bear name?")
    print("beartruth: ", beartruth)
else:
    print("Attributes are ", bearAttributes[bearNames[userBear]])
    print("beartruth: ", beartruth)
    beartruth = False
    print("beartruth: ", beartruth)

那样做,你就知道 Bear 实际上不是一只。只有当 Bear 是真实的时,您才能进入 else 块做其他事情。

如果你在最后4行有错误,抛出的异常会有所不同,不会被泛型隐藏

except:

块,这也会隐藏其他错误,但您会认为这是用户输入的错误。

因为你在一个 while 循环中,你也可以这样做:

try:
    print("Abbreviation is ", bearNames[userBear])
except KeyError:
    print("Something went wrong - did you not type a bear name?")
    print("beartruth: ", beartruth)
    continue  # go back to the beginning of the loop

# There was no error and continue wasn't hit, the Bear is a bear
print("Attributes are ", bearAttributes[bearNames[userBear]])
print("beartruth: ", beartruth)
beartruth = False
print("beartruth: ", beartruth)