Global Variable in Python
Learn via video course

What is a Global Variable in Python?
A global variable in Python is a variable declared outside of the function or in the global scope. A global variable can be accessed from both inside and outside the function. A variable that you want to use throughout the scope of a program should be declared globally.
Create a Global Variable
To make a global variable in Python, you must declare it outside of the function or in the global scope.
Output:
How to Access the Global Variable Inside and Outside of a Function?
Let's see how we can access a global variable when it is used inside and outside a function:
Output:
Difference Between Global and Local Variables
Global variables are defined outside of any function and have a global scope. Whereas, local variables are defined inside a function and their scope is limited to that function only.
When you create a variable inside a function, it's usually local, meaning it may only be used within that function. The global keyword can be used to declare a global variable within a function. If you want to alter a global variable within a function, use the global keyword.
Now, we'll see how global and local variables behave in the same code, through an example:
Output:
In the above code, we declare the variable x as global and y as local inside the function. Next, we perform an operation on the variable x and leave y as it is. Then we call the function and observe that the value of x comes out to be 10, as we multiplied x by 5. We also print the value of y.
Learn More
In this article, we talked about global variables in python, and how they are created. We also learned how they are different from local variables, and how global variables can be used both inside and outside a function. However, would you like to learn more, just about python variables in general? To learn more about variables in python, head over to the following link and check out our dedicated article for the same. Variables in Python
Conclusion
- Global variables are those variables that can be accessed both inside and outside functions in a program.
- Global variables should be declared outside a function.
- Local variables are declared inside a function, and their scope is limited to that function only. This is what differentiates them from global variables.
- To declare a global variable inside a function, the word global should be used to initialize the variable. Example: global x, where x is the name of the variable.