0

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

0

3 Answers 3

1

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 variable.

def Hello():
    global good
    good = 'Nice'
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. I had a quite big code that didn't work because of that, but now it totally works!! Thanks so much!!
Glad it helped you.
1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.