Click here to Skip to main content
15,914,780 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
def foo(x):
def bar(x):
return x + 1
return bar(x * 2)

foo(3)


cannot get my head around this one..
Posted

1 solution

It's fairly simple: you define a function foo with parameter x, inside of foo is another function called bar, which also has a (separate) parameter x. When you call foo(3), it returns bar(x * 2), which in this case is equivalent to bar(6), which in turn returns x + 1, or in this case, 6 + 1, which equals 7. The syntax is a little weird, because most common languages do not allow proper functions (as opposed to lambdas and anonymous functions) inside of other functions, and even worse since both have the same parameter name. It might be a little clearer if they had different parameter names, like:
def foo(x):
    def bar(y):
        return y + 1
    return bar(x * 2)
 
foo(3)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900