Learn
A Day at the Supermarket
Lists + Functions
Functions can also take lists as inputs and perform various operations on those lists.
def count_small(numbers): total = 0 for n in numbers: if n < 10: total = total + 1 return total lotto = [4, 8, 15, 16, 23, 42] small = count_small(lotto) print small
- In the above example, we define a function
count_small
that has one parameter,numbers
. - We initialize a variable
total
that we can use in thefor
loop. - For each item
n
innumbers
, ifn
is less than 10, we incrementtotal
. - After the
for
loop, we returntotal
. - After the function definition, we create an array of numbers called
lotto
. - We call the
count_small
function, pass inlotto
, and store the returned result insmall
. - Finally, we print out the returned result, which is
2
since only4
and8
are less than 10.
Instructions
1.
Write a function that counts how many times the string "fizz"
appears in a list.
- Write a function called
fizz_count
that takes a listx
as input. - Create a variable
count
to hold the ongoing count. Initialize it to zero. for
eachitem in x:
,if
that item is equal to the string"fizz"
then increment thecount
variable.- After the loop, please
return
thecount
variable.
For example, fizz_count(["fizz","cat","fizz"])
should return 2
.