Python Scope
Only within the created region is a variable available. This is known as scope.
Python has two types of scopes, which is :
- Local Scope
- Global Scope
Local Scope
A variable generated within a function inside is called as function's local scope and is only available in that function.
Example :- In this function a variable generated inside a function is available :
def myfunc():
x = 300
print(x)
myfunc()
# It gives an error
# print(x)
Output :-
Function Inside Function
The variable x
is not accesible outside of the function as described in the example above but is usable in any function inside the function :
Example :- A function within the function allows access to the local variable :
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Output :-
Related Links
Global Scope
A variable created in the outside of a function (python main body) is a global variable and is part of the global scope.
Global variables are available within any global or local scope.
Example :- An outside function produced variable is global and can be used :
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Output :-
300
Naming Variables
If within and outside one function you are operating with the same variable name, Python will treat them as two independent variables, one in the global scope (except the function) and the other in the local scope (within the function) :
Example :- It print the local x
, then the global x
is printed by the code :
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
Output:-
300
Related Links
Global Keyword
You can use the global
keyword if you need to build a global variable but are in the local field.
The variable is global with the global
keyword.
Example 1 :- The variable is the global scope if you use the global
keyword :
def myfunc():
global x
x = 300
myfunc()
print(x)
Output :-
Use the global
keyword to transform to a global variable within a function.
Example 2 :- To modify the value of a global variable within a function, use the global
keyword to refer to the variable :
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
Output :-