How to Create a Global Variable in Python

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:

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:

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.

Subsequently, running test_function() would get:

'I am the modified global variable'

Here’s the Full Code:

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.