How do I use global variables in python functions? [duplicate]

Posted on

Question :

How do I use global variables in python functions? [duplicate]

How do I set a global variable inside of a python function?

Asked By: stgeorge

||

Answer #1:

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.
Answered By: Sukrit Kalra

Answer #2:

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.

Answered By: korylprince

Answer #3:

A global can be accessed by any function, but it can only be modified if you explicitly declare it with the ‘global’ keyword inside the function. Take, for example, a function that implements a counter. You could do it with global variables like this:

count = 0

def funct():
    global count
    count += 1
    return count

print funct() # prints 1
a = funct() # a = 2
print funct() # prints 3
print a # prints 2

print count # prints 3

Now, this is all fine and good, but it is generally not a good idea to use global variables for anything except constants. You could have an alternate implementation using closures, which would avoid polluting the namespace and be much cleaner:

def initCounter():
    count = 0
    def incrementCounter():
        count += 1
        return count

    #notice how you're returning the function with no parentheses 
    #so you return a function instead of a value
    return incrementCounter 

myFunct = initCounter()
print myFunct() # prints 1
a = myFunct() # a = 2
print myFunct() # prints 3
print a # prints 2

print count # raises an error! 
            # So you can use count for something else if needed!
Answered By: James

Answer #4:

Explicit declaration by using global <variable name> inside a function should help

Answered By: vladfau

Answer #5:

In the example below we have a variable c defined outside of any other function. In foo we also declare a c, increment it, and print it out. You can see that repeatedly calling foo() will yield the same result over and over again, because the c in foo is local in scope to the function.

In bar, however, the keyword global is added before c. Now the variable c references any variable c defined in the global scope (ie. our c = 1 instance defined before the functions). Calling bar repeatedly updates the global c instead of one scoped locally.

>>> c = 1
>>> def foo():
...     c = 0
...     c += 1
...     print c
...
>>> def bar():
...     global c
...     c += 1
...     print c
...
>>> foo()
1
>>> foo()
1
>>> foo()
1
>>> bar()
2
>>> bar()
3
Answered By: sberry

Answer #6:

A normal variable is only usable inside of a function, a global variable can be called for outside the function, but don’t use this if you don’t need to, it can create errors and big programming companies consider this a rookie thing to do.

Answered By: Fox

Answer #7:

I’ve grappled with the same question / misunderstood what I wanted for a few days, and I think what you may be trying to accomplish is have a function output a result, that can be used after the function finishes running.

The way you can accomplish above is by using return “some result”, and then assigning that to a variable after a function.
Here’s an example below:

#function
def test_f(x):
    y = x + 2
    return y

#execute function, and assign result as another variable
var = test_f(3)
#can use the output of test_f()!
print var      #returns 5
print var + 3  #returns 8
Answered By: FlyingZebra1

Leave a Reply

Your email address will not be published. Required fields are marked *