python - 在 Python 3 中尝试除外

标签 python python-3.x while-loop try-except

我为此苦苦思索了几个小时,终于弄清楚了。当然,现在对我来说这似乎是显而易见的痛苦,但也许有一天其他人也会陷入同样的​​境地,所以我想我应该问并回答。当然,欢迎任何更正或解释。

精简代码:

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)

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

最佳答案

因为您要求一些更正或解释。

来自您的代码

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)

您可以具体说明(我建议这样做)异常,以确保隔离您可能期望的错误。

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)

这样做,你就知道实际上不是一只。仅当是真实的熊时,您才可以进入else block 执行其他操作。

如果您在最后 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)

关于python - 在 Python 3 中尝试除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48439995/

相关文章:

python-3.x - Tensorflow 和 Keras 中的相同(?)神经网络架构在相同数据上产生不同的准确性

c - 嵌套在循环中的公式将无法正确执行

python - 重复 RSA 加密/解密有时会失败,并出现明文太大错误

Python 使用字符串作为字典键

python - 为什么这个简单的 Spark 程序没有使用多核?

python - pip3 因导入错误而崩溃

python - 打印字符串中几个特定字符后的所有内容

mysql - Wordpress MySQL 结果资源无效

c - C 中的 while 循环验证输入是数字?

python - 高效插入数字 - NumPy/Python