-1

Can someone explain why this code of python outputs 30? It seems like add = func ? But how does python knows this without declaring. It's a question in the python course from sololearn.com, a lot of people don't seem to understand

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))
jayelm
  • 7,236
  • 5
  • 43
  • 61
Timothy
  • 346
  • 6
  • 18
  • you pass the function `add` as the argument to `do_twice` so yeah, `func` is add when that is what is passed as the argument, in the same way as `x` is `5` because that is what `a` was equal to when you passed it as the argument for `x`.... – Tadhg McDonald-Jensen Jun 01 '16 at 15:57
  • It doesn't just *seem* like that; `func` is explicitly set to `add` when you call `do_twice`. – chepner Jun 01 '16 at 15:57
  • see [python function as a function argument?](http://stackoverflow.com/questions/6289646/python-function-as-a-function-argument) or [Passing Functions or Code as Parameters](https://mail.python.org/pipermail/tutor/2005-October/042616.html) – Tadhg McDonald-Jensen Jun 01 '16 at 15:59
  • 2
    5+10+5+10=30 Simple Math –  Jun 01 '16 at 16:01
  • If that's not what you expect, what *do* you expect, and why? – tripleee Jun 01 '16 at 16:04
  • Can you explain what you mean by "without declaring"? It's not clear what you are confused by – doctorlove Jun 01 '16 at 16:05

3 Answers3

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

when called with add, 5 and 10 will return

add(add(5, 10), add(5, 10))

i.e.

add(15, 15)

which is indeed 30

add has been passed as the first parameter, so is called func inside do_twice. Likewise a is 5 and b is 10.

doctorlove
  • 18,872
  • 2
  • 46
  • 62
1

A is set to 5 and B to 10. This add function simply returns the sum of two inputs. You call do_twice with the add function, 5, and, 10 as inputs. First, do_twice evaluates the sum of 5 and 10 in both inner calls of func(x, y). This leaves us with "return func(15, 15)". This adds 15 and 15, yielding 30. Finally, you print out this value. This is why it is 30. Feel free to follow up for any clarifications!

Willy
  • 322
  • 1
  • 17
1

Python don't care what you pass in for func for your function do-twice. But in the body of your function do_twice you are invoking func passed in i.e You are using func as if it supposed to be a callable(something you can invoke. A function is one such thing.). You can verify it by passing a string to do_twice and you should see an error stating string is not callable or something.

gipsy
  • 3,859
  • 1
  • 13
  • 21