Functions and Lists

An argument can be any value, a list too. A function that gets a list can go through it with a loop and return a result. This function counts how many numbers in a list are greater than a limit:

def count_over(numbers, limit):
    count = 0
    for number in numbers:
        if number > limit:
            count += 1
    return count

temperatures = [18, 25, 31, 22, 28]
print(count_over(temperatures, 24))
print(count_over([5, 10, 15], 7))

This prints:

3
2

The parameter numbers holds whatever list the call passes: first the list temperatures, then [5, 10, 15]. You know counting from the lesson on loops, but now it's inside a function, so you can count in any list with a single line. And because count is a local variable, every call starts from 0 again.

Notice where the return is: after the loop, when all the numbers have been checked. In Python, the indentation decides that: return count is indented as much as for, so it isn't part of the loop. A common mistake is to indent it one level more, into the loop:

def count_over(numbers, limit):
    count = 0
    for number in numbers:
        if number > limit:
            count += 1
        return count

temperatures = [18, 25, 31, 22, 28]
print(count_over(temperatures, 24))

This prints:

0

Now return is in the body of the loop. It ends the whole function, and the loop with it, already in the first iteration. The function only checked the first number, 18, so it returned 0.

A function can also return a list: create an empty list before the loop, add elements to it with .append() in the loop, and return it after the loop. And a function can use other functions, such as sum() and len().

Instructions

The program ends with the error NameError: name 'average' is not defined. Write the function in place of the comment: average has a parameter numbers and returns the average of the numbers in the list, that is, their sum divided by how many there are. You can add them up with a loop or with sum(), and len(numbers) tells you how many there are. The program then prints the average temperatures of two weeks, 21.0 and 13.0.

Below the function average, write a function warm_days with two parameters, temperatures and limit. It returns a new list of the temperatures that are greater than limit. At the end of the program, print warm_days(week1, 20). The program prints [21, 24, 23].

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

9/10