Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

A function inside a function Python

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 = 99

def f(y):
    w = x + y
    def g():
        x = 10
        y = z * w
    print y

f(5)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...