I am a beginner of python and have a question, very confusing for me. If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function? for example:
def hello(x,y): good=hi(iy,ix) 'then do somethings,and use the parameter'good'.' return something def hi(iy,ix): 'code' return good
The scope of functions
helloandhiare entirely different. They do not have any variables in common.Note that the result of calling
hi(x,y)is some object. You save that object with the namegoodin the functionhello.The variable named
goodinhellois a different variable, unrelated to the variable namedgoodin the functionhi.They’re spelled the same, but the exist in different namespaces. To prove this, change the spelling the
goodvariable in one of the two functions, you’ll see that things still work.Edit. Follow-up: ‘so what should i do if i want use the result of
hifunction inhellofunction?’Nothing unusual. Look at
helloclosely.Some script evaluates
hello( 2, 3).Python creates a new namespace for the evaluation of
hello.In
hello,xis bound to the object2. Binding is done position order.In
hello,yis bound to the object3.In
hello, Python evaluates the first statement,fordf150 = hi( y, x ),yis 3,xis 2.a. Python creates a new namespace for the evaluation of
hi.b. In
hi,ixis bound to the object3. Binding is done position order.c. In
hi,iyis bound to the object2.d. In
hi, something happens andgoodis bound to some object, say3.1415926.e. In
hi, areturnis executed; identifying an object as the value forhi. In this case, the object is named bygoodand is the object3.1415926.f. The
hinamespace is discarded.good,ixandiyvanish. The object (3.1415926), however, remains as the value of evaluatinghi.In
hello, Python finishes the first statement,fordf150 = hi( y, x ),yis 3,xis 2. The value ofhiis3.1415926.a.
fordf150is bound to the object created by evaluatinghi,3.1415926.In
hello, Python moves on to other statements.At some point
somethingis bound to an object, say,2.718281828459045.In
hello, areturnis executed; identifying an object as the value forhello. In this case, the object is named bysomethingand is the object2.718281828459045.The namespace is discarded.
fordf150andsomethingvanish, as doxandy. The object (2.718281828459045), however, remains as the value of evaluatinghello.Whatever program or script called
hellogets the answer.