Code Explanation:
Lambda Function:
lambda x: x ** 0.5 defines an anonymous function (lambda function) that takes a single argument x.
The body of the function is x ** 0.5, which calculates the square root of x.
In Python, raising a number to the power of 0.5 is equivalent to taking its square root.
Assigning the Function:
sqrt = lambda x: x ** 0.5 assigns the lambda function to the variable sqrt.
Now, sqrt can be used as a regular function to compute square roots.
Calling the Function:
result = sqrt(16) calls the sqrt function with the argument 16.
Inside the function:
16 ** 0.5 is calculated.
The function returns 4.0.
Printing the Result:
print(result) outputs the value of result to the console, which is 4.0.
Output:
The program prints:
4.0
Note:
The result is 4.0 (a float), even though the square root of 16 is 4, because the ** operator with 0.5 produces a floating-point number.
If you want the output as an integer, you can cast the result to an int:
sqrt = lambda x: int(x ** 0.5)
result = sqrt(16)
print(result)
This would print:
4
0 Comments:
Post a Comment