Code Explanation:
Lambda Function:
lambda a, b: abs(a - b) defines an anonymous function (lambda function) that takes two arguments, a and b.
The function calculates the absolute difference between a and b using the abs() function.
abs(x) returns the absolute value of x (i.e., it removes any negative sign from the result).
Assigning the Function:
absolute_diff = lambda a, b: abs(a - b) assigns the lambda function to the variable absolute_diff.
Now, absolute_diff can be used as a regular function to compute the absolute difference between two numbers.
Calling the Function:
result = absolute_diff(7, 12) calls the absolute_diff function with the arguments 7 and 12.
Inside the function:
a−b=7−12=−5.
abs(-5) evaluates to 5, as the abs() function removes the negative sign.
Printing the Result:
print(result) outputs the value of result to the console, which is 5.
Output:
The program prints:
5
0 Comments:
Post a Comment