with two arguments

Introduction:

  • A lambda function in Python allows you to create small, anonymous functions that can take any number of arguments. Lambda functions are handy for short operations that you don't want to define using the standard def keyword.

Syntax:

  • To define a lambda function with two arguments, specify the parameters after the lambda keyword, separated by commas, followed by the function body:

    python
    lambda x, y: x * y
    

Examples:

  1. Find the Product of Two Numbers:
    • This example defines a lambda function that takes two arguments, x and y, and returns their product.

      python
      product = lambda x, y: x * y
      
      num1 = 5
      num2 = 3
      result = product(num1, num2)
      print(f"Product of {num1} and {num2} is {result}.")
      
    • Output:

       
      Product of 5 and 3 is 15.
      
  2. Lambda Function to Check If Two Numbers Are Even:
    • This example defines a lambda function that takes two arguments, x and y, and returns True if both numbers are even, otherwise returns False.

      python
      bothEven = lambda x, y: x % 2 == 0 and y % 2 == 0
      
      num1 = 8
      num2 = 14
      
      if bothEven(num1, num2):
          print("Both the numbers are even.")
      else:
          print("Both the numbers are not even.")
      
    • Output:

       
      Both the numbers are even.
      

Exercises:

  1. Sum of Two Numbers:
    • Define a lambda function that takes two arguments and returns their sum.

      python
      sum = lambda x, y: x + y
      
      print(sum(10, 5))  # Output: 15
      
  2. Greater Number:
    • Define a lambda function that takes two arguments and returns the greater of the two.

      python
      greater = lambda x, y: x if x > y else y
      
      print(greater(10, 15))  # Output: 15
      
  3. Difference of Two Numbers:
    • Define a lambda function that takes two arguments and returns their difference.

      python
      difference = lambda x, y: x - y
      
      print(difference(10, 5))  # Output: 5
      

Summary:

  • In this tutorial, we learned how to define a lambda function with two arguments in Python. Lambda functions are useful for short, simple operations that you want to define quickly and use immediately. Practice writing lambda functions with different operations to get comfortable using them in your Python programs!