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=1 # global variable def sample(): print(c) #function calling sample()
When we run above program, the output will be:
1
However, we may have some scenarios where we need to modify the global variable from inside a function.
Example 2:
Modifying Global Variable From Inside the Function
c=1 # global variable def sample(): c=c+100 print(c) #function calling sample()
When we run above program, the output shows an error:
UnboundLocalError: local variable ‘c’ referenced before assignment
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.