Home > Net >  Please explain this code to me ... I have been trying to solve it on paper but i cant
Please explain this code to me ... I have been trying to solve it on paper but i cant

Time:11-02

def add(x, y):
 return x   y

def do twice(func, x, y):
  return func(func(x, y), func(x, y))

a = 5 
b = 10

print(do_twice(add, a, b))

Someone Please explain it to me in simple words..

CodePudding user response:

In Python, functions are objects too. You can pass a function as an argument to another function. In this case, add is passed as an argument to do_twice.

A function name with parentheses after it (add(3, 4)) calls the function; you end up with whatever the function returns. But a function name not followed by parentheses (just add) is a variable that refers to the function itself.

CodePudding user response:

Assuming you know what the add(x,y) function does:

def do_twice(func, x, y):
  return func(func(x, y), func(x, y))

What happens in the do_twice function is that the function that is passed into it is simply called with the input x, y. This means that func(func(x,y), func(x,y)) will simply be evaluated to add(add(x,y), add(x,y)so with your input x=5, y=10 the function with add will further be simplified to add(add(5,10), add(5,10)) -> add(15, 15) -> 30

CodePudding user response:

do_twice(add, a, b) with a = 5, b = 10 is essentially add(add(5,10), add(5,10)).

add(5,10) returns 5 10, which is 15. So add(add(5,10), add(5,10)) is add(15,15), which gives 30.

CodePudding user response:

Here we go:

do_twice(add, a, b)

We are going to use the function do_twice with func=add and the two numbers a and b. The function do_twice calls the function func=add three times: func(func(x, y), func(x, y))

Let's break this down.

First func(x, y) will just compute the sum of x and y. Which results in 15. So we are left with: func(15, 15)

Which again is summed up and we get 15 15 = 30 which is what is printed

CodePudding user response:

This is an example for "Passing function name as an argument". So in this example you gave

def add(x, y):
 return x   y

def do_twice(func, x, y):
  return func(func(x, y), func(x, y))

a = 5 
b = 10

print(do_twice(add, a, b))

You can pass the "name" of the function as an argument to another function by which you can invoke the function without calling the actual function name, Similar to have normal argument variables /parameters work for integers, strings ,etc.

Here we are passing the function name "add" as an value to the function do_twice where the function name "add" gets stored the variable "func" so whenever we call the do_twice function with "add", add () gets invoked twice and we are sending the resultant values back into the add() and returning the result.

Please read the guidelines before posting any questions and its a good practice to check the internet thoroughly before posting questions here.

Happy learning!

  • Related