pythonfunctionvariablesgloballocal

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?


Solution

  • 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()