Lambda functions (anonymous functions) are used to perform a simple operation with a single line. Below are two ways of achieving the same result - one with a regular function, and the second one with a lambda function:
Here we define a lambda function and assign it to add, after which add acts as a regular function. In practice, it’s more common to pass lambda functions to other functions instead of assigning them. We’ll discuss those use cases soon.
The syntax for a lambda function is lambda followed by the arguments without brackets () followed by a colon : and a return statement without a return keyword.
We can have multiple arguments in a lambda function separated by a comma:
add = lambda x, y: x + y
print(add(2, 5)) # 7
print(add(1, 4)) # 5
Pay attention that the lambda functions can only be written on a single line and cannot span several lines. They are meant for simple one-time computations.
You are asked to implement the following function with a lambda expression:
The lambda function should return the value of the function given two floating-point values - x and y.
f = ...
x, y = float(input()), float(input())