Created
September 19, 2019 21:32
-
-
Save raheemazeezabiodun/9d7b17a2dc390b8a0751bbcefc7a9e22 to your computer and use it in GitHub Desktop.
An example of how to use try except else in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
The try block tries to execute an expression | |
If an error occurs, it calls the except block alone | |
If no error occur, it calls the else block | |
The idea behind this is, if the school exists, print it out | |
""" | |
schools = { | |
'MIT': lambda: print("The school name is MIT"), | |
'HARVARD': lambda: print("The school name is HARVARD"), | |
'STANDFORD': lambda: print("The school name is STANDFORD") | |
} | |
try: | |
school_name = schools['MIT'] | |
except KeyError: | |
raise Exception("Key error") | |
else: | |
school_name() # The school name is MIT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment