Skip to the content

Closures

Python · Unit 21: Advanced Python

Inside a function you can define another function. The inner one only exists while the outer one runs, and it can use the outer variables without receiving them.

def greeting(name):
    def polite():
        return "Hello, " + name
    return polite()

print(greeting("Ana"))

Prints

Hello, Ana

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. Multiple choice

    After this code you write print(half()). What happens?

  3. 3. Predict the output

    What does this code print?

  4. 4. Complete the code

    Fill in the blank so repeat(2) hands back a function that repeats the text twice.

  5. 5. Find the bug

    It should print 15, because adder(10) hands back a function that adds 10. Which line has the error?

  6. 6. Predict the output

    What does this code print?

  7. 7. Complete the code

    Fill in the blank so the bag keeps adding up whatever you put in it.

  8. 8. Put the lines in order

    Put the lines in order to build a countdown that drops by one every time you call it.

  9. 9. Predict the output

    Remember that key takes a function saying what to compare by.

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 →