so I’m currently using the python 3 fundamentals course on Pluralsight to begin learning python. This is the program that is being used to explain try/except block and finally:
acronyms = {'LOL': 'laugh out loud',
'IDK': "I don't know",
'TBH': 'to be honest'}
try:
def = acronyms["BTW"]
print('Definition of ', acronym, ' is ', def)
except:
print('The key ', acronym, ' does not exist')
finally:
print('The acronyms we have defined are:')
for acronym in acronyms:
print(acronym)
print('The program keeps going...')
After being ran, it should produce:
The key BTW does not exist
The acronyms defined are: LOL IDK TBH
The program keeps going…
However, it’s frustrating as "def" can’t be used in this way as it is a keyword and "acronym" isn’t been defined until the loop at the end so won’t in produce the print statement. Is there any way to correct this to get it to work the way they claim it should?
Thanks for any help offered.
>Solution :
Changes in comments below. The biggest thing is saving the acronym to check into a variable name, instead of hard-coding it into a string for one time usage.
If that program above is what was provided as a learning program, I would highly consider finding a different course. The only thing harder than learning a language is re-learning the language after you’ve been taught poor practices.
acronyms = {'LOL': 'laugh out loud',
'IDK': "I don't know",
'TBH': 'to be honest'}
try:
#Save acronym to check into a variable so it can be referenced again
acronym_to_check = "BTW"
#Change variable name to something other than def
result = acronyms[acronym_to_check]
#Use an f-string to format output
print(f'Definition of {acronym_to_check} is {result}')
#Catch a specific error, instead of catching every error that could happen
except KeyError:
print(f'The key {acronym_to_check} does not exist')
finally:
print('The acronyms we have defined are:')
for acronym in acronyms:
print(acronym)
print('The program keeps going...')