In Python, variables can be declared in two main scopes: global and local. Global variables are accessible from anywhere in the code, while local variables are only accessible within the function or block where they are defined.
Python has the "global"
keyword, which allows users to modify global variables from within the local scope.
What is global Keyword?
Let’s understand with an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Example of "global" keyword # Global variable var = "declared as global" def modify_var(): # Function's scope global var # Modified the global variable "var" var = "modified global" print(var) modify_var() print(var) |
In this example, the global variable var
is defined first, followed by the function modify_var()
.
Inside the modify_var()
function, the global var
statement is used to reference the global variable var
in the function’s scope and then the variable var
is modified and printed.
The function is then called. Upon running the code, you’ll get the following result.
1 2 |
modified global modified global |
You can observe that the global variable var
is modified.
In conclusion, the global
keyword is used to reference and modify a global variable within the scope of a function.
Not Using global Keyword
What happens if you do not use the global
keyword and attempt to modify a global variable within the local scope?
1 2 3 4 5 6 7 8 9 10 11 |
# Global variable var = "declared as global" def modify_var(): # Function's scope # Trying to modify the global variable "var" var = "modified global" print(var) modify_var() print(var) |
In this example, the global var
statement is removed from the function and an attempt is made to modify the variable var
.
1 2 |
modified global declared as global |
You can observe that the global variable var
remains unchanged.
Making Local Variable a Global One
The global
keyword can also be used to create a global variable in the local context.
1 2 3 4 5 6 |
def separate(): text = "Geek Python" print(text.split(" ")) separate() print(text) |
In this example, the text
variable is declared within the separate()
function and has scope within the function only.
The text
variable is being accessed outside of the function scope. This will result in an error.
1 2 3 4 5 6 |
['Geek', 'Python'] Traceback (most recent call last): ... print(text) ^^^^ NameError: name 'text' is not defined. Did you mean: 'next'? |
When you add a global statement just above the text
variable, it becomes the global variable, which may be accessed from anywhere in the code.
1 2 3 4 5 6 7 |
def separate(): global text # Added global stmt text = "Geek Python" print(text.split(" ")) separate() print(text) |
When you run the code, you’ll get the value stored in the text
variable.
Assigning Value to the Global Variable Within Local Scope
Consider the following example which attempts to change the global variable within the local scope without using the global statement.
1 2 3 4 5 6 7 8 9 10 |
# Global variable initial = 2 def increment(): for x in range(10): # Assigning value to the global var in local context initial += x increment() print(initial) |
A global variable named initial
is declared and initialized with the value 2.
The function named increment()
increments the global variable initial
. The function is then called and the value of the initial
variable is printed.
When you run the code, you’ll get the following result.
1 2 3 4 5 6 7 |
Traceback (most recent call last): ... increment() ... initial += x ^^^^^^^ UnboundLocalError: cannot access local variable 'initial' where it is not associated with a value |
The error message indicates that the local variable "initial"
cannot be accessed. Python interprets the function’s initial
variable as a new local variable, which is why the code failed to locate the initial
variable within the function’s scope and returned an error.
However, when you add a global statement (global initial
) within the function, Python will know that it is now referencing the existing global variable within the local scope.
1 2 3 4 5 6 7 8 9 10 11 |
# Global variable initial = 2 def increment(): global initial for x in range(10): # Assigning value to the global var in local context initial += x increment() print(initial) |
You won’t get an error when you run the code as the global statement has been added to the function scope.
1 |
47 |
Conclusion
The global
keyword can be used to reference and modify an existing global variable within a local scope. If the global variable does not already exist, the global
keyword can be used to create it within the local scope of a function.
πOther articles you might be interested in if you liked this one
β Yield Keyword in Python with Examples?
β Best Practices: Positional and Keyword Arguments in Python
β Python’s __getitem__ method?
β Create a WebSocket Server and Client in Python.
β Create and Interact with MySQL Database in Python
β Understanding the Different Uses of the Asterisk(*) in Python?
That’s all for now
Keep Codingββ