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?!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…