How do I set a global variable inside of a python function?
To use global
variables inside a function, you need to do global <varName>
inside the function, like so.
testVar = 0
def testFunc():
global testVar
testVar += 1
print testVar
testFunc()
print testVar
gives the output
>>>
0
1
Keep in mind, that you only need to declare them global
inside the function if you want to do assignments / change them. global
is not needed for printing and accessing.
You can do,
def testFunc2():
print testVar
without declaring it global
as we did in the first function and it'll still give the value all right.
Using a list
as an example, you cannot assign a list
without declaring it global
but you can call it's methods and change the list. Like follows.
testVar = []
def testFunc1():
testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.
def testFunc2():
global testVar
testVar = [2] # Will change the global variable.
def testFunc3():
testVar.append(2) # Will change the global variable.
Consider the following code:
a = 1
def f():
# uses global because it hasn't been rebound
print 'f: ',a
def g():
# variable is rebound so global a isn't touched
a = 2
print 'g: ',a
def h():
# specify that the a we want is the global variable
global a
a = 3
print 'h: ',a
print 'global: ',a
f()
print 'global: ',a
g()
print 'global: ',a
h()
print 'global: ',a
Output:
global: 1
f: 1
global: 1
g: 2
global: 1
h: 3
global: 3
Basically you use a global variable when you need every function to access the same variable (object). This isn't always the best way though.
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