This is a problem asked before but I can't really understand the other explain of this kind of problem so I'm here to re-write it in more details. While studying I have encountered this kind of code that I am not at all familiar .. I can not understand how to interpret this g() function in f() function ! Why the piece of code inside g() where x = 10 and y = z*w does not run ? It's only print me the value of y I gave, calling f() with 5 !
x = 99def f(y):w = x + ydef g():x = 10y = z * wprint yf(5)
In Python, def
is a statement: takes a function name, possibly arguments, then an indented function body -- compiles it all into a function object, which it binds to the given name in the scope where def
appeared (here, locally to f
).
So you ask "Why the piece of code inside g() where x = 10 and y = z*w does not run" -- very simply, because you never call g
!
The fact that g
is local to f
(or as is also known "nested in f
") is not germane.
Whether local or global, anytime you def g
but then never call g
, the code in g
's body will not execute.
Incidentally, this is a detail in which Python coincides with every other language I've ever heard about. If a function is defined (some languages call that "declared") and never called, then the function's body code never runs. Have you ever heard of any language doing otherwise -- i.e, executing the code body of a function that's defined but never called?!