In Python, variables that are created and available throughout the entire code are called Global variables. Global variables can be accessed from any part of your script, irrespective of scope, making them essential in many coding scenarios.
Step 1: Creating a Global Variable
To create a global variable in Python, we define the variable outside of all the functions, at the top of the program. This variable can then be accessed from any part of the code. Here’s an example:
1 |
global_var = "I am a global variable" |
Step 2: Accessing a Global Variable
Accessing a global variable in Python is also straightforward. You simply use the variable name in your code in the function or scope where you want to use it. Here’s an example:
1 2 |
def test_function(): print(global_var) |
By running test_function(), you would get:
'I am a global variable'
Step 3: Modifying a Global Variable
To modify a global variable in Python, you’ll need to use the global keyword. By declaring the variable as global in the function where you’re going to modify it, Python understands that you refer to the global variable instead of creating a new local one.
1 2 3 |
def modify_global(): global global_var global_var = "I am the modified global variable" |
Subsequently, running test_function() would get:
'I am the modified global variable'
Here’s the Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
global_var = "I am a global variable" def test_function(): print(global_var) def modify_global(): global global_var global_var = "I am the modified global variable" # Access the global variable test_function() # Modify the global variable modify_global() # Now access the modified global variable test_function() |
I am a global variable I am the modified global variable
Conclusion
In conclusion, a global variable in Python can be created, accessed, and modified anywhere in the code. It is powerful and useful in a lot of instances, but needs to be used with care due to its unrestricted scope, to avoid potential conflict with local variables.