Local and Global Variables

When we declare a variable inside a function, it becomes a local variable. A local variable is a variable whose scope is limited only to that function where it is created. That means the local variable value is available only in that function and not outside of that function. In the following example, the variable 'a' is declared inside myfunction() and hence it is available inside that function. Once we come out of the function, the variable 'a' is removed from memory and it is not available. Consider the following code:

When a variable is declared above a function, it becomes global variable. Such variables are available to all the functions which are written after it. Consider the following code:

not available Whereas the scope of the local variable is limited only to the function where it is declared, the scope of the global variable is the entire program body written below it.

The Global Keyword

Sometimes, the global variable and the local variable may have the same name. In that case, the function, by default, refers to the local variable and ignores the global variable. So, the global variable is not accessible inside the function but outside of it, it is accessible.

A Python program to understand global and local variables.

When the programmer wants to use the global variable inside a function, he can use the keyword 'global' before the variable in the beginning of the function body as:

global a

In this way, the global variable is made available to the function and the programmer can work with it as he wishes. In the following program, we are showing how to work with a global variable inside a function.

A Python program to access global variable inside a function and modify it.