In Python, a global variable is the one declared outside a function, known as the global scope. Every variable declared outside a function has a default global scope; it can be accessed anywhere but cannot be changed. A global variable can be accessed inside or outside of a function.
Let’s see an example:
def foo():x = "edpresso" # redifining x in the local scopeprint x # printing the redefined xx= "edpresso by educative" # defining x in the global scopefoo()print x # printing the global x
In the code above, before we call the function foo()
, the variable x
is defined as a string “edpresso by educative”
in the global scope.
When we redefine x
in the function, it has a local scope; its scope ends with the function. As the function ends, the global x
is printed since it had global scope.
We have successfully accessed and printed a variable from global scope. Now let us try to modify a variable of global scope in the following code:
def foo():print xx = "edpresso by educative" # will generate an error since trying to modify xprint x# Global scopex = "edpresso"foo()print x
Trying to modify a variable from the global scope in the local scope will generate an error. To make the above program work, we need to use the global
keyword.
global
keywordThe global
keyword in Python allows the user to modify a variable outside of its current scope. It is used to create a
global variable and make changes to it locally.
global
keyword is not needed for printing and accessing, just for modifying.
Note: A variable cannot be declared
global
and assigned a value in the same line.
Let us see a comprehensive example to sum up the functionality of the global
keyword:
y = 1def foo():print 'Inside foo() : ', y # uses global y since there is no local y# Variable 'y' is redefined as a localdef goo():y = 2 # redefines y in a local scopeprint 'Inside goo() : ', ydef hoo():global y #makes y global and hence, modifiabley = 3print 'Inside hoo() : ',y# Global scopeprint 'global y : ',yfoo()print 'global y : ',ygoo()print 'global y : ',yhoo()print 'global y : ',y
RELATED TAGS