I'm trying to use a variable / list in a function that is defined in another function without making it global.
Here is my code:
def hi():
hello = [1,2,3]
print("hello")
def bye(hello):
print(hello)
hi()
bye(hello)
At the moment I am getting the error that "hello" in "bye(hello)" is not defined.
How can I resolve this?
You need to return hello from your hi
method.
By simply printing you are not able to gain access to what happens inside the hi
method. Variables created inside a method remain within the scope of that method.
Information on variable scope in Python:
http://gettingstartedwithpython.blogspot.ca/2012/05/variable-scope.html
You return hello
inside your hi
method, then, when you call hi
, you should store the result in a variable.
So, in hi
, you return:
def hi():
hello = [1,2,3]
return hello
Then when you call your method, you store the result of hi
in a variable:
hi_result = hi()
Then, you pass that variable to your bye
method:
bye(hi_result)
if you don't want to use a global variable, your best option is just to call bye(hello)
from within hi()
.
def hi():
hello = [1,2,3]
print("hello")
bye(hello)
def bye(hello):
print(hello)
hi()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With