python · level 3 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A function is a value you can pass around.
Write a function's name without brackets and you get the function itself, not its answer. You can store it in a variable, put it in a dictionary, or hand it to another function to call later.
sorted, max and min take a . They call it on every item and compare the answers, so sorted(words, key=len) puts the shortest words first.
For a one-off key, write a : lambda film: film[1] is a tiny function with no name that returns its one expression. Keep lambdas short. Anything bigger deserves a proper def.
films = [("Up", 2009), ("Jaws", 1975), ("Coco", 2017)]
oldest = min(films, key=lambda film: film[1])
by_title = sorted(films, key=lambda film: film[0])
print(oldest)
print(by_title)
shout = str.upper
print(shout("encore")) key=len hands over the function, while key=len() would try to call it straight away.
guess first
A function that calls a function. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def double(n):
return n * 2
def twice(action, value):
return action(action(value))
print(twice(double, 5))
print(twice(lambda word: word + "!", "hi"))
your turn
Your turn. Rank the players by score.
Each item is a pair like ("Ana", 42). Fill the blank so the lambda returns the score part of the pair. reverse=True puts the biggest first.
fix it
Shortest names first, but it crashes. Fix it!
- The crash happens on line 2, before
sortedeven starts. What do the brackets afterlendo? - Brackets call
lenstraight away, with nothing to measure.sortedwants the function itself. - Remove the brackets so it says
key=len, then run.
nailed it
you passed functions around like values. :D
- A name without brackets is the function itself.
key=tellssorted,maxandminwhat to compare.- A
lambdais a tiny one-line function with no name.
new words in your collection
- key function
- lambda
This lesson isn’t saved. A free account remembers every lesson you finish.