Search code examples
pythonglobal

how to make a variable global inside a function


How do you declare a variable as global once it has been created inside a function? This is my example code (not what it is being used for):

def function():
    pancakes = input("pancakes input")
    pancakes = global(pancakes) #i don't know how to do this part

def function2(pancakes):
    print(pancakes)
    
function()
function2(pancakes)

By the way I know that returning the variable also works but it will not with my program.


Solution

  • Just declare a variable in the global scope (outside the function) and assign a value to it inside the function.

    pancakes = None
    def function():
        global pancakes
        pancakes_input = input("pancakes input")
        pancakes = pancakes_input
    
    def function2(pancakes):
        print(pancakes)
        
    function()
    function2(pancakes)