Introduction to global Keyword
In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.
Rules of global Keyword
The basic rules for global keyword in Python are:
• When we create a variable inside a function, it’s local by default.
• When we define a variable outside of a function, it’s global by default. You don’t have to use global keyword.
• We use global keyword to read and write a global variable inside a function.
• Use of global keyword outside a function has no effect
Example 1:
Accessing global Variable From Inside a Function
c=100 #global variable def sample(): print(c) #function calling sample() print(c)
Output:
100
100
>>>
However, if we try to modify the global variable from inside a function, we get an error as shown in the below program.
Example 2:
Modifying Global Variable From Inside the Function
c=100 #global variable def sample(): c=c+10 print(c) #function calling sample() print(c)
Output:
When we run above program, the output shows an error:
UnboundLocalError: local variable ‘c’ referenced before assignment
Note: This is because we can only access the global variable but cannot modify it from inside the function.
The solution for this is to use the global keyword.
Example 3:
Changing Global Variable From Inside a Function using global
c = 100 # global variable def abc(): global c c = c + 200 # increment by 200 print("Inside abc():", c) #function calling print("Outside Function abc() :", c) add() print("Outside Function abc() :", c)
Output:
Outside Function abc() : 100
Inside add(): 300
Outside Function abc() : 300
>>>
In the above program we have
global c
It states that c is a global variable and its value can be modified inside the function abc().
so when we increment the variable c by 200, i.e c = c + 200. we get the modified value as output.
As we can see, change also occurred on the global variable outside the function, c = 300.