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
2The 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:
0Now 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
- 1
The program ends with the error
NameError: name 'average' is not defined. Write the function in place of the comment:averagehas a parameternumbersand 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 withsum(), andlen(numbers)tells you how many there are. The program then prints the average temperatures of two weeks,21.0and13.0. - 2
Below the function
average, write a functionwarm_dayswith two parameters,temperaturesandlimit. It returns a new list of the temperatures that are greater thanlimit. At the end of the program, printwarm_days(week1, 20). The program prints[21, 24, 23].