A Function Inside A Function Python
Solution 1:
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?!
Solution 2:
Although you define the function g()
inside the function f()
, you never actually call it. You'll need to make a call to it inside the f()
function as well.
Solution 3:
The function g()
was never called inside the f(y)
function. To properly get your code to work, it should look something like this.
x = 99deff(y):
w = x + y
defg():
x = 10
y = z * w
g(y) # <---- notice the function call for g().print y
f(5)
Post a Comment for "A Function Inside A Function Python"