Skip to the content

Functions as values

Python · Unit 10: More on functions

A function is a value too, like a number: you can pass it to another function.

Without parentheses, double is the function; with parentheses, double(7) calls it and gives 14.

def double(n):
    return n * 2

def apply(f, x):
    return f(x)

print(apply(double, 7))

Prints

14

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blank so apply uses the function double.

  3. 3. Multiple choice

    What does count_if(f, nums) return?

  4. 4. Find the case that fails

    longest(words) should return the longest word in the list, or "" if the list is empty. Which call breaks it?

  5. 5. Predict the output

    What does this code print?

  6. 6. Complete the code

    Fill in the blank to find the most expensive product.

  7. 7. Find the bug

    This program should print the name of the cheapest product. Which line has the bug?

  8. 8. Predict the output

    What does this code print?

  9. 9. Put the lines in order

    Put the function in order. It applies f to each item of the list and returns a list with the results.

  10. 10. Predict the output

    Which are the two dishes with the most votes?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →