0
Python Scope Question
def apply_twice(func, arg): return func(func(arg)) def add_five(x): return x + 5 print(apply_twice(add_five, 10)) How many "func"s are in this code? Scope confuses me. It's just one right?
7 Answers
+ 3
21kHzBANK21kHZ
they are the same func.
(add_five, 10) becomes
add_five(add_five(10))
which is evaluated to
add_five(10+5)
add_five(15)
15+5
20
+ 5
It is the same! 'func' is equal to 'add_five' because that is the argument sent to the function when it is called using the print statement at the end.
'return func(func(arg))' could be visualized as 'return add_five(add_five(arg))' in this case.
+ 3
To get a better idea of what is going on I sometimes use print statements like this:
def apply_twice(func, arg):
print(func,arg) # debug
return func(func(arg))
def add_five(x):
print(x) # debug
return x + 5
print(apply_twice(add_five, 10))
The final print statement is literally adding 5 (add_five() function), twice (apply_twice() function) to 10.
+ 2
Each time a function is called, its the same 'function' however each one has its own scope. Variables defined inside a function cannot be used outside of it unless passed to another function or using 'return'. This applies even if the same function is called recursively!
+ 1
I mean to ask, in the declaration of apply_twice, is every usage of "func" the same, or are they different "func"s?
#first func
def apply_twice(func, arg):
#second and third func. same as first? unique?
return func(func(arg))
+ 1
Thanks! đđż
0
You have defined two functions here, one called "apply_twice" and one called "add_five"