Skip to content

Question 20

What does the following function return?

1
2
3
4
5
6
7
def foo(tup, val):
    count = 0
    for e in tup:
        if e >= val:
            continue
        count += 1
    return count
Hint

Notice that function foo() returns the value of local variable count. This function seems to take in an iterable (possibly a tuple based on the name tup), and some primitive value for val - e.g., int, float, bool, str. What does count mean?

Solution

The function foo() contains a for loop which manipulates the value of count through iterating through each element in tup. For clarity, you may consider putting in test values for tup and val.

Suppose tup = (5, 10, 15, 20) and val = 12.

e (in tup) e >= val? count += 1
5 5 >= 12 (False) 0 + 1 = 1
10 10 >= 12 (False) 1 + 1 = 2
15 15 >= 12 (True) 2 (executed continue from if statement)
20 20 >= 12 (True) 2 (executed continue from if statement)

Notice that here, count does not increment as soon as we find that an element in tup that is bigger than val. We can very well infer from here that count represents the number of elements that are smaller than val.

Answer

The number of elements in tup that are smaller than val