虽然在Python 3中尝试除外

时间:2018-01-25 09:53:25

标签: 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)

问题 - 输入一些不是熊的东西会导致"除了"永诀。我想要发生的事情应该是相当明显的 - 如果用户输入了不在bearNames中的内容,它应该触发except,打印错误并返回尝试。

2 个答案:

答案 0 :(得分:1)

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

写入的代码首先要求用户输入,然后开始。如果用户输入了'灰熊'。尝试成功,并将bearTruth设置为false,从而打破循环。 (也许一个休息陈述在这里有用,但我还没有达到休息陈述:))

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

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

答案 1 :(得分:1)

因为你要求做出一些更正或解释。

从您的代码中

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)

这样做,你知道 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)