Lesson 13
Lesson 13 of 34
Lambda Functions
Lesson Progress: 0%
Code Example
# lambda function
add = lambda a, b: a + b
print(add(2, 3))
# the lambda function does the same as
def add(a, b):
return a + b
print(add(2, 3))Instructions
▼ ← Click the triangle to hide or reveal instructions.Python Code Editor
Task Incomplete
Editor Input:
Editor Output:
lambda is a short way to make a small function in one line.a and b and quickly give back a result.def example do the same job.print() to see the answer that the function returns.Code Example
double = lambda x: x * 2
print(double(4))Instructions
▼ ← Click the triangle to hide or reveal instructions.Python Code Editor
Task Incomplete
Editor Input:
Editor Output:
lambda is a mini-tool that lets you write a whole math rule on just one short line.Code Example
# A quick way to say hello to someone
greet = lambda name: "Hello " + name
print(greet("Sam"))Instructions
▼ ← Click the triangle to hide or reveal instructions.Python Code Editor
Task Incomplete
Editor Input:
Editor Output:
lambda to build a quick "greeting machine" that adds words together for you.greet, and it will put "Hello" in front of any name you type.Code Example
shout = lambda word: word.upper()
print(shout("hello"))Instructions
▼ ← Click the triangle to hide or reveal instructions.Python Code Editor
Task Incomplete
Editor Input:
Editor Output:
.upper() inside your lambda, you tell Python to "shout" whatever word you give it.Code Example
is_even = lambda num: num % 2 == 0
print(is_even(4))
print(is_even(5))Instructions
▼ ← Click the triangle to hide or reveal instructions.Python Code Editor
Task Incomplete
Editor Input:
Editor Output:
% 2 == 0 part is a math trick that asks Python if a number can be split perfectly into two groups.Code Example
even_or_odd = lambda n: "Even" if n % 2 == 0 else "Odd"
print(even_or_odd(4))
print(even_or_odd(7))Instructions
▼ ← Click the triangle to hide or reveal instructions.Python Code Editor
Task Incomplete
Editor Input:
Editor Output:
lambda quickly checks a number and decides if it is even or odd.print() lines show the result for each number you test.Code Example
# Rule: If the score is 50 or more, you Pass. Otherwise, you Fail.
grade = lambda score: "Pass" if score >= 50 else "Fail"
print(grade(75))
print(grade(30))Instructions
▼ ← Click the triangle to hide or reveal instructions.Python Code Editor
Task Incomplete
Editor Input:
Editor Output:
if and else to decide which message to send back to you.Code Example
# Rule: If the hour is before 18 (6 PM), it is Day. Otherwise, it is Night.
time_of_day = lambda hour: "Day" if hour < 18 else "Night"
print(time_of_day(10))
print(time_of_day(20))Instructions
▼ ← Click the triangle to hide or reveal instructions.Python Code Editor
Task Incomplete
Editor Input:
Editor Output:
lambda function checks the hour and chooses between “Day” or “Night”.print() lines show what the function returns for different times.