0
Can anyone explain it easily?
See the code below and explain me how does it work? def square (x): return x*x def test (func,x): print (func(x)) test(square,42)
3 odpowiedzi
+ 4
Hello there :)
With the first piece of code, you declare a function (def), named 'square'.
It declares a variable named 'x'.
This function should return the value of 'x' * value of 'x'.
In the second function, you declare again 2 variables: func and x.
This function should return to print the variable x in the parentheses of a function (func variable).
At the end you call the function 'test'.
You assign to the variable 'func' = square, and to x = 42.
Just put these 2 values inside the test function parenthesis.
This returns to square(42).
And at the end your function square will return to 42*42, == x*x. :)
+ 3
First we will understand
def square(x):
return x*x
Here we created a function name 'square' that takes one argument, 'x' then returns the value x*x.
The Python return statement is a special statement that you can use inside a function or method to send the function's result back to the caller. A return statement consists of the return keyword followed by an optional return value.
Now,
def test(func, x):
print(func, x)
here we define the function TEST
this test function tells us that the test will take the 1st function against the argument and then the 2nd function against argument result of the 1st
Next we define the function WITHIN our test function and set the argument (x) as a placeholder, i.e: test(square, 42)
Now when we call our functions we add
42 as the argument which takes x`s place
test()...42 is our first argument
So, 42 * 42 = 1764
1764 becomes our argument after the first function
1764 * 1764 = 3111696 is our output (answer)
0
You call a function called test, passing in two arguments: (square, 42). The test function assigns your 2 arguments (square, 42) to 2 parameters (func, x) and prints the result of calling func with x: print(func(x)). That means it prints square(42) because of the arguments you provided. So, square must be a function.
We see above square is indeed a function that takes one argument: something called x. In this case, that's 42. This square function multiplies that x argument by itself and returns it, which in this case is return 42 * 42. The result of that is what ends up getting printed.