0

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.

user4444
  • 55
  • 5
  • use global keyword variable before you assignment.like global val val=1 – NAGA RAJ S Jun 27 '20 at 05:10
  • I don't understand what you mean. Could you please give an example using the code I provided? @NAGA RAJ S – user4444 Jun 27 '20 at 05:12
  • https://stackoverflow.com/questions/423379/using-global-variables-in-a-function – Ghost Jun 27 '20 at 05:13
  • 1
    You can't turn a local variable into a global one, and even if it could be done you would likely be better off using a different code structure. You can, however, update a preexisting global variable within your function. –  Jun 27 '20 at 05:15
  • yes thank you Ghost! – user4444 Jun 27 '20 at 05:16

2 Answers2

1

you have to make the variable global using a global keyword every time you assign the value to that variable .and if it is the main thread means there is no need to use the global keyword. follow this:

var=0

def func():
   global var
   var=1
greendino
  • 416
  • 3
  • 17
NAGA RAJ S
  • 452
  • 4
  • 12
1

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)
tersrth
  • 861
  • 6
  • 18