returns True or False

Introduction:

  • In Python, we can define a lambda function that returns either True or False. 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 True or False based on a condition:

    python
    lambda parameters: True if condition else False
    

Example:

  • Write a lambda function that takes a number as a parameter and returns True if the given number is even, or False if it is not:

    python
    lambda n: True if n % 2 == 0 else False
    

Examples:

  1. 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 returns True if the given number is even, or False if the number is not even.
    • Python Program:

      python
      isEven = 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
      

Exercises:

  1. Check If a Number Is Positive:
    • Write a lambda function that returns True if a given number is positive, or False if it is not.

      python
      isPositive = 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
      
  2. Check If a String Is Empty:
    • Write a lambda function that returns True if a given string is empty, or False if it is not.

      python
      isEmpty = 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, True or False. 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!