Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a variable in a different function without using global

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?

like image 765
Humvee202 Avatar asked Dec 24 '22 13:12

Humvee202


2 Answers

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)
like image 169
idjaw Avatar answered Jan 30 '23 20:01

idjaw


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()
like image 33
QuakeCore Avatar answered Jan 30 '23 21:01

QuakeCore