ይህ ትምህርት ገና ወደ አማርኛ አልተተረጎመም፤ ስለዚህ በእንግሊዝኛ ቀርቧል። የእንግሊዝኛውን ገጽ ክፈቱ
Functions are values
In lesson 4.2 you sorted words with key=str.lower and were promised an explanation.
Here it is: a function is a value, like a number or a list, so you can give it a second
name or hand it to another function. By the end you'll sort and pick from any list by
any rule you choose.
A function is a value
Predict what this prints.
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
def greet(name):
print(f"Selam, {name}!")
say = greet
say("Abel")Python prints
Selam, Abel!
say = greet gives the same function a second name, just like b = a gave a list a second name in lesson 4.8. Calling say calls that function.
def makes a function object and gives it a name. Assignment can give it another.
Step through it: two names, one function.
Two names, one function
Press Next to run one line at a time. Each arrow shows the object a name refers to. Each call gets its own frame of names, below the frame that called it.Each row is one step: the line that just ran, and the object each name refers to after it, frame by frame, oldest first.
Frames, oldest first: global. greet refers to a function, function greet.
Step 1 of 5
Step 1 of 5. Line 1: def greet(name):. greet now refers to a new function, function greet.
| Step | Line | Names and objects |
|---|---|---|
| 1 | 1 |
|
| 2 | 4 |
|
| 3 | 5 |
|
| 4 | 2 |
|
| 5 | 5 |
|
The frame is labeled greet, not say: the call runs the function object, whatever
name you reached it by. Because functions can be named, passed, and returned like any
other value, Python has
.
Passing a function to sorted
sorted can take a function as its key. It calls that function on each item and
sorts by the results, while keeping the items themselves. The three rounds of a coffee
ceremony, sorted by the length of their names:
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
rounds = ["bereka", "tona", "abol"]
print(sorted(rounds, key=len))Python prints
['tona', 'abol', 'bereka']
len gives 6, 4, and 4, so the two 4-letter words come first. They tie, and sorted keeps tied items in the order they had: tona was before abol. The key replaces alphabetical order entirely.
A
takes one item and returns what to compare. key=len compares lengths; key=str.lower
compares lowercase versions, so capitals no longer sort first. Items with equal keys
keep their original order. Pass the function itself, not a call:
ጥያቄ
In sorted(words, key=len), what is len?
Your own key, and lambda
Any function that takes one item works as a key. Here each item is an (item, price)
tuple, and the key picks out the price:
prices = [("coffee", 40), ("bread", 25), ("tea", 15)]
def price_of(pair):
return pair[1]
print(sorted(prices, key=price_of))
print(max(prices, key=price_of))In the editor, press Escape then Tab to move on.
max and min take a key too: max returns the whole tuple with the biggest price,
not just 40. For a key this small, writing a whole def feels heavy. A
is a one-line function with no name: lambda, the parameter, a colon, and the value
to return.
prices = [("coffee", 40), ("bread", 25), ("tea", 15)]
print(min(prices, key=lambda pair: pair[1]))In the editor, press Escape then Tab to move on.
lambda pair: pair[1] does exactly what price_of does. Use a lambda for a short key
used once. Use a named function when the rule takes more than one line, when you use
it in several places, or when a name like price_of explains it better than
pair[1] does.
መልመጃ
Contacts in name order
Some contacts were typed in lowercase, so plain sorted puts Hana and Selam
first. Print the names in alphabetical order, ignoring case, with each number.
abel: 0900 000 001
dawit: 0900 000 004
Hana: 0900 000 002
Selam: 0900 000 003Your code
contacts = {"Selam": "0900 000 003", "abel": "0900 000 001", "Hana": "0900 000 002", "dawit": "0900 000 004"}
for name in sorted(contacts):
print(f"{name}: {contacts[name]}")In the editor, press Escape then Tab to move on.
መፍትሄውን አሳይHide the solution
This is one way to solve it, not the only one. If yours prints the same thing, it works.
contacts = {"Selam": "0900 000 003", "abel": "0900 000 001", "Hana": "0900 000 002", "dawit": "0900 000 004"}
for name in sorted(contacts, key=str.lower):
print(f"{name}: {contacts[name]}")ዋና ዋና ነጥቦች
- A function is a value:
say = greetgives one function two names. key=takes a function, not a call:key=len, neverkey=len().sorted,min, andmaxcall the key on each item and compare the results; ties keep their order.lambda pair: pair[1]is a one-line function with no name, good for short keys.- Prefer a named function when the rule is long, reused, or needs a name to be clear.