Closures
Python · Unit 21: Advanced Python
- Full plan
- Python
- 9 exercises
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. Predict the output
What does this code print?
2. Multiple choice
After this code you write
print(half()). What happens?3. Predict the output
What does this code print?
4. Complete the code
Fill in the blank so
repeat(2)hands back a function that repeats the text twice.5. Find the bug
It should print 15, because
adder(10)hands back a function that adds 10. Which line has the error?6. Predict the output
What does this code print?
7. Complete the code
Fill in the blank so the bag keeps adding up whatever you put in it.
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. Predict the output
Remember that
keytakes a function saying what to compare by.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.