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 scope print x # printing the redefined x x= "edpresso by educative" # defining x in the global scope foo() 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 x x = "edpresso by educative" # will generate an error since trying to modify x print x # Global scope x = "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 = 1 def foo(): print 'Inside foo() : ', y # uses global y since there is no local y # Variable 'y' is redefined as a local def goo(): y = 2 # redefines y in a local scope print 'Inside goo() : ', y def hoo(): global y #makes y global and hence, modifiable y = 3 print 'Inside hoo() : ',y # Global scope print 'global y : ',y foo() print 'global y : ',y goo() print 'global y : ',y hoo() print 'global y : ',y
RELATED TAGS
View all Courses