returns True or False
Introduction:
- In Python, we can define a lambda function that returns either
TrueorFalse. Typically, this is a lambda function that evaluates a condition and returns a boolean value.
Syntax:
The structure of a typical lambda function that returns either
TrueorFalsebased on a condition:pythonlambda parameters: True if condition else False
Example:
Write a lambda function that takes a number as a parameter and returns
Trueif the given number is even, orFalseif it is not:pythonlambda n: True if n % 2 == 0 else False
Examples:
- Lambda Function That Returns True If the Given Number Is Even, or False If Not:
- In this example, we define a lambda function,
isEven, that returnsTrueif the given number is even, orFalseif the number is not even. Python Program:
pythonisEven = lambda n: True if n % 2 == 0 else False print("Is 8 even? ", isEven(8)) print("Is 7 even? ", isEven(7))Output:
Is 8 even? True Is 7 even? False
- In this example, we define a lambda function,
Exercises:
- Check If a Number Is Positive:
Write a lambda function that returns
Trueif a given number is positive, orFalseif it is not.pythonisPositive = lambda n: True if n > 0 else False print("Is 10 positive? ", isPositive(10)) # Output: Is 10 positive? True print("Is -5 positive? ", isPositive(-5)) # Output: Is -5 positive? False
- Check If a String Is Empty:
Write a lambda function that returns
Trueif a given string is empty, orFalseif it is not.pythonisEmpty = lambda s: True if s == "" else False print("Is '' empty? ", isEmpty("")) # Output: Is '' empty? True print("Is 'hello' empty? ", isEmpty("hello")) # Output: Is 'hello' empty? False
Summary:
- In this tutorial, we learned how to write a lambda function that returns a boolean value,
TrueorFalse. Lambda functions are useful for concise and efficient boolean evaluations. Practice writing lambda functions with conditions to get comfortable using them in your Python programs!