Lambda Functions Part 2
Part of the Logic & Flow section of Coddy's Python journey — lesson 58 of 78.
Lambda functions can also include conditional logic using the if-else expression syntax.
Create a basic lambda function with an if-else condition:
# Format: lambda parameters: value_if_true if condition else value_if_false
is_adult = lambda age: "Adult" if age >= 18 else "Minor"Test the lambda function with different values:
print(is_adult(20)) # Output: "Adult"
print(is_adult(15)) # Output: "Minor"You can use more complex conditions as well:
grade_status = lambda score: "Amazing!" if score == 100 else "Pass" if score >= 60 else "Fail"
print(grade_status(75)) # Output: "Pass"Challenge
EasyCreate a lambda function named categorize_number that takes a number as an argument and returns:
- "Positive" if the number is greater than 0
- "Zero" if the number is equal to 0
- "Negative" if the number is less than 0
Then use this lambda function to categorize a number received from input.
Cheat sheet
Lambda functions can include conditional logic using the if-else expression syntax:
# Basic if-else in lambda
is_adult = lambda age: "Adult" if age >= 18 else "Minor"You can chain multiple conditions:
# Multiple conditions
grade_status = lambda score: "Amazing!" if score == 100 else "Pass" if score >= 60 else "Fail"The format is: lambda parameters: value_if_true if condition else value_if_false
Try it yourself
# Read a number from input
number = int(input())
# Define your lambda function here
categorize_number =
# Call your lambda function with the input number and print the result
print(categorize_number(number))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter