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?

5th Jan 2024, 7:53 PM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar
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
5th Jan 2024, 9:53 PM
Bob_Li
Bob_Li - avatar
+ 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.
5th Jan 2024, 9:58 PM
Keith
Keith - avatar
+ 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.
5th Jan 2024, 9:05 PM
Keith
Keith - avatar
+ 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!
5th Jan 2024, 9:51 PM
StuartH
StuartH - avatar
+ 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))
5th Jan 2024, 9:45 PM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar
+ 1
Thanks! 👍🏿
6th Jan 2024, 10:07 AM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar
0
You have defined two functions here, one called "apply_twice" and one called "add_five"
5th Jan 2024, 9:04 PM
StuartH
StuartH - avatar