Lesson 7
Objects and Dictionaries
Chapter 7: Exception handling
Exercise (list of fruits)
Let’s try practice handling errors.
Here is a short piece of code. I am expecting two potential exceptions to occur (can you spot them?) Running the program and being a ‘naughty user’ may give you an idea of what kind of exceptions you might expect to happen.
Try to apply what you have just learnt, and display some user-friendly error messages whenever the expected errors happen, rather than letting Python display some cryptic error messages!
fruits = ["apples", "oranges", "bananas", "pineapples", "mangoes"]
index = int(input("Enter an integer: "))
fruit = fruits[index]
print(f"You love {fruit}!")