Tuesday, March 13, 2018

Scope of Variables


Scope of Variables in Python 3


All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier.

 There are two basic scopes of variables in Python-

· Global variables
· Local variables


Global vs. Local variables

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.

Following is a simple example-




and the output is :