Global and local variables in Python with examples


+ 1

In Python, declaration of variables is not required. Means you don't need to specify whether it is an integer or string etc as Python is a dynamically typed language. In this post, let's learn about Global and local variables in Python along with examples.

1. Global Variables

Global variables are the variables which are declared outside the function or in global scope. A global variable can be accessed through out the program means they can be accessible in both inside and outside of the functions.

Example: 1


Run here

If you run the above program, you can notice that x value is same in both inside and outside functions.

Results


Consider you want to modify the value of x inside function, let's see what will happen if you do so:


Run here

Results


This is because Python treats x inside the function as local variable. In order to make this work, use the global keyword as shown below.


Run here

When you run the above program, you can see that the x value gets changed and the results will look like below:

Results


2. Local Variables

Local variables are the variables which are declared inside the function's body or in local scope. A local variable can be accessed only inside the function which it got declared.


Run here

When you run the above program, it generates the below error:


This is because x is alive only inside the function and hence it can be accessable only inside the function it is declared.

Suppose if global and local variables shares the same name:


Run here

When you run the above program, you can notice that the x value inside function will be 10 and outside the function will be 5. Python treats global and local variables seperately even though it shares same name.

Result