Python Lambda
The whole function is one line: lambda price, tip: price + tip, kept under the name bill. bill(4, 1) is 5. What follows the colon is the value, so this line does not contain return, and nothing is indented under it.
You use the name bill afterward. bill(4, 1) fills price with 4 and tip with 1, in the order the names are written. print writes that result.
bill = lambda price, tip: price + tip
print(bill(4, 1))
The screen shows 5. print wrote it. The lambda line writes nothing by itself. 4 + 1 is 5, so bill(4, 1) is 5. Other numbers are added the same way. bill(4, 0) is 4.
The same addition can be written with def over several lines, with return on a line of its own. On this page the addition stays in the expression after the colon.
📊 One line or several
| Form | Where the value comes from |
|---|---|
| lambda price, tip: price + tip | the expression after the colon |
| def with return price + tip | the return line |
Where this line breaks
return does not belong after the colon. The program stops on lambda price, tip: return price + tip, because that spot takes one expression and return is not one. Leave the colon out and the program stops too. bill() and bill(4) stop as well: the line names two inputs, and both have to be filled.
The next page is a function that runs again from inside itself. This page only writes a function on one line.
On the screen
- What does print(bill(4, 1)) write?
- What is bill(4, 0)?
- You put return after the colon. Does the program finish?
- Is there an indented line under this function?
What the line does
lambda price, tip: price + tip is the whole function. bill(4, 1) is 5, and print writes that 5. The expression after the colon is the value, so return is not on the line. return after the colon stops the program. bill(4, 0) is 4.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top