I wrestled with this for several hours, the figured it out. Of course it seems painfully obvious to me now, but maybe one day someone else will get stuck in the same place, so I thought I'd ask-and-answer. Of course any corrections or interpretations are welcome.
Abridged code:
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)
Problem - entering something which isn't a bear loops the "except" part forever. What I want to happen should be fairly obvious - if the user enters something which isn't in bearNames, it should trigger the except, print the error and head back to try.
Since your were asking for some corrections or interpretations.
From your code
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)
You can be specific (and I would recommend it) with Exceptions to make sure you isolate the error that you may be expecting.
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)
Doing it that way, you know that the Bear wasn't actually one. And only if the Bear is a real one you go into the else
block to do something else.
If you have made a mistake in the last 4 lines, the exception raised will be different and will not be hidden by the generic
except:
block, which would also be hiding other errors, but you would believe it was wrong input from the user.
Because you are in a while
loop, you can alternatively do:
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)