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
lambdakeyword. Here's how you can define a lambda function that takes two parameters,aandb, and returns their sum:pythonlambda 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
sumso 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:
- We define the lambda function
sum = lambda a, b: a + b. - We assign two numbers,
num1andnum2. - We call the lambda function
sumwithnum1andnum2as arguments and store the result in the variableresult. - We print the result.
Exercises:
- Sum of Two Different Numbers:
Use the lambda function to find the sum of 7 and 2.
pythonsum = lambda a, b: a + b print(sum(7, 2)) # Output: 9
- Sum of Negative Numbers:
Use the lambda function to find the sum of -3 and -6.
pythonsum = lambda a, b: a + b print(sum(-3, -6)) # Output: -9
- Sum of Decimal Numbers:
Use the lambda function to find the sum of 2.5 and 3.7.
pythonsum = 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!