Sum of two numbers

Introduction:

  • To add two given numbers using a lambda function in Python, we can define a lambda function that takes two numbers as arguments and returns their sum.

Defining the Lambda Function:

  • Lambda functions in Python start with the lambda keyword. Here's how you can define a lambda function that takes two parameters, a and b, and returns their sum:

    python
    lambda a, b: a + b
    

Example: Finding the Sum of 5 and 3 Using a Lambda Function:

  • Let's use the lambda function we defined above to find the sum of two numbers. We'll assign the lambda function to a variable called sum so that we can call it by this name.

Python Program:

python
sum = lambda a, b: a + b

num1 = 5
num2 = 3
result = sum(num1, num2)
print(f"Sum of {num1} and {num2} is {result}.")

Output:

 
Sum of 5 and 3 is 8.

Explanation:

  1. We define the lambda function sum = lambda a, b: a + b.
  2. We assign two numbers, num1 and num2.
  3. We call the lambda function sum with num1 and num2 as arguments and store the result in the variable result.
  4. We print the result.

Exercises:

  1. Sum of Two Different Numbers:
    • Use the lambda function to find the sum of 7 and 2.

      python
      sum = lambda a, b: a + b
      
      print(sum(7, 2))  # Output: 9
      
  2. Sum of Negative Numbers:
    • Use the lambda function to find the sum of -3 and -6.

      python
      sum = lambda a, b: a + b
      
      print(sum(-3, -6))  # Output: -9
      
  3. Sum of Decimal Numbers:
    • Use the lambda function to find the sum of 2.5 and 3.7.

      python
      sum = lambda a, b: a + b
      
      print(sum(2.5, 3.7))  # Output: 6.2
      

Summary:

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