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