Skip to content

Instantly share code, notes, and snippets.

@avivajpeyi
Last active May 14, 2020 04:36
Show Gist options
  • Save avivajpeyi/9fc7b0c95d351fc55ec955efd62dbd34 to your computer and use it in GitHub Desktop.
Save avivajpeyi/9fc7b0c95d351fc55ec955efd62dbd34 to your computer and use it in GitHub Desktop.
"""
Match the error with the function
a. TypeError
b. AttributeError
c. IndexError
d. ValueError (error 1)
e. ZeroDivisionError
f. IndentationError
More error types:
https://www.tutorialsteacher.com/python/error-types-in-python
"""
def error_1():
"""
ERROR TYPE: Value Error
When the type expected is correct but the value of the variable is
inappropriate.
:return:
"""
return int('xyz')
def error_2():
"""
ERROR TYPE: Type Error
Occurs when the data provided is the wrong type for the function.
For example a function may want a string and instead an integer was provided.
:return:
"""
return '2' + 2
def error_3():
"""
ERROR TYPE: ZeroDivison
Happens when you divide by 0.
:return:
"""
return 42 / 0 # error!
def error_4():
"""
ERROR TYPE: Attribute Error
Occurs when an attribute isn’t present in a object, but is being used.
:return:
"""
class Tea:
def __init__(self):
self.water = 100 # ml
t = Tea()
print(t.water) # works
print(t.leaves) # error!
pass
def error_5():
"""
ERROR TYPE: indentation
When your indentation is inappropriate for the code you
are writing.
:return:
"""
eval("""
print(1)
print(2)
""")
def error_6():
"""
ERROR TYPE: Index
When you access a collection at an index that has yet to be initialised.
Commonly occurs when writing an indexed loop to access a list.
:return:
"""
my_list = [1, 2, 3]
return my_list[3]
def call_users_chosen_function(user_choice):
try:
if user_choice == 1:
error_1()
elif user_choice == 2:
error_2()
elif user_choice == 3:
error_3()
elif user_choice == 4:
error_4()
elif user_choice == 5:
error_5()
elif user_choice == 6:
error_6()
else:
raise ValueError(
f"Invalid user choice: {user_choice}. "
f"Expected value are 1,2,..6"
)
except Exception as exception:
statement = (
f"-----ERROR-----\n"
f"Exception: {type(exception).__name__}\n"
f"Exception message: {exception}\n"
f"---------------\n"
)
print(statement)
def main():
user_choice = 1
while user_choice != 0:
user_choice = int(input("Enter a num from 1...6 (0 to exit) = "))
call_users_chosen_function(user_choice)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment