简体   繁体   中英

Passing variables from function to function

I have a question about passing variables from function to another function by using this code:

def Hello():
    good = "Nice"
    return good

def Bye():
    print (good)

Hello()
Bye()

It returns "Global name "good" is not defined"

How can I solve this problem? Thanks

You need to learn about scopes. The variable good exists only within the scope of the function Hello - outside this function the variable is not known.

In your case, you should store the return value of Hello in a variable - and then pass this variable to the function Bye :

def Hello():
    good = "Nice"
    return good

def Bye(g):
    print (g)

g = Hello()
Bye(g)

From the docs :

A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one, unless a contained block introduces a different binding for the name.

[...]

When a name is not found at all, a NameError exception is raised. If the current scope is a function scope, and the name refers to a local variable that has not yet been bound to a value at the point where the name is used, an UnboundLocalError exception is raised. UnboundLocalError is a subclass of NameError.

If you want the variable good to be available to other functions without having to run the function Hello , you should declare good as a global function.

def Hello():
    global good
    good = 'Nice'
    ...

There is a simpler solution that follows more closely the original code:

def Hello():
    good = "Nice"
    return good

def Bye():
    print (good)

good = Hello()
Bye()

Python keeps variables defined in a local scope local, therefore you cannot read good outside of your function unless you explicitly return it (and store it). Python also doesn't allow you to write to variables defined in a larger scope unless you pass them as an input argument or use the global directive. But the OP didn't ask to write to good from within another function. Python DOES allow to read variables from a larger scope. So all you need to do is to store the variable good in your larger scope, it is been returned already by the OP's Hello function anyway.

With this you have to use global variables which are accessible for every function in every slide. Here is a video which will show you how to complete the thing you are looking for. https://youtu.be/lcEm0R7mwJk . Hope you get the answer you are looking for.

Denis Granulo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM