Lesson 8
Making Objects the Main Star!
Chapter 10: Input validation
Exercise
Now, it’s your turn to try these two approaches to ensure the robustness of a piece code.
You are given the following piece of code. The function reads in a list
of numbers
and a query
(int
). The code will search for the first occurrence of query
in the list, and add up the value of query
with the number that comes after it in the list.
There are two places where things can potentially go wrong. Can you spot them? (Think about it first before continuing. My test cases should give you a hint!)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
The two issues are:
- What if a query does not occur in the list of numbers? What happens?
- What if a query occurs at the end of a list? What should you do?
Let’s say we deal with the first problem by printing out a warning message that says “The query n was not found in numbers. Returning 0.”, and return 0
.
For the second case, let’s say we decided that if the query is the last element in the list, we will just return the value of the query without adding it to any other number. For example, if numbers = [1, 2, 3, 4]
and query = 4
, the function should simply return 4
.
Now, your task is to modify the code to handle both these cases.
You will implement TWO versions of the code.
- The first version uses a LBYL approach (using
if
statements). - The second version should use an EAFP approach (using
try... except
blocks).
Compare the two approaches you implemented and observe how they are different!