Local/Global Variables
Scope of Variables
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.
Example 1:
Inside the function local total : 30
Outside the function global total : 0
Example 2:
Global x = 10
Local variable x = 15
Global x = 10
Example 3:
Before function calling x = 10
In function Value = 15
After function calling x = 15
Example 4:
Hello World Times 1
Hello World Times 2
Hello World Times 3
Hello World Times 4
Hello World Times 5
Hello World Times 6
Hello World Times 7
Hello World Times 8
Hello World Times 9
Using variables from a function inside another function
Example 5:
Above program will give error
Nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope
Example 6:
30
30
100
Last updated