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

Chapter 10: Input validation

Exercise

face Josiah Wang

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
def find_in_list(numbers, query):
    position = numbers.index(query)
    return numbers[position] + numbers[position+1]

def test_valid():
    numbers = [1, 2, 3, 4]
    result = find_in_list(numbers, 2)
    print(result)

def test_notinlist():
    numbers = [1, 2, 3, 4]
    result = find_in_list(numbers, 7)
    print(result)

def test_endoflist():
    numbers = [1, 2, 3, 4]
    result = find_in_list(numbers, 4)
    print(result)

if __name__ == "__main__":
    test_valid()
    test_notinlist()
    test_endoflist()

The two issues are:

  1. What if a query does not occur in the list of numbers? What happens?
  2. 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.

  1. The first version uses a LBYL approach (using if statements).
  2. The second version should use an EAFP approach (using try... except blocks).

Compare the two approaches you implemented and observe how they are different!