This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 7: Exception handling

Exercise (list of fruits)

face Josiah Wang

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}!")