Understanding Python Scope
Not all variables can be accessed from anywhere in a program. The part of a program where a variable is accessible is called its scope. Scope defines the region in a program where a variable can be accessed.
In Python, there are two main types of scope:
- Local Scope
- Global Scope
Local Scope:
When we declare variables inside a function, these variables will have a local scope (within the function). We cannot access them outside the function. These types of variables are called local variables.
Examples:
- def func1():
x = 300
print(x)
func1()
Output: 300
As explained in the example above, the variable x is not available outside the function, but it is available for any function inside the function.
- def func2():
x = 550
def innerfunc():
print(x)
innerfunc()
func2()
Output: 550
The local variable can be accessed from a function within the function.
- def func3():
s = “I love Pakistan”
print(s)
func3()
Output: I love Pakistan
Note: If we will try to use this local variable outside the function then let’s see what will happen.
Def func4()
a = “Python Programming”
print(“Pakistan”)
func4()
print(a)
Output: NameError: name ‘a’ is not defined
Global Scope:
Global variables are the ones that are defined and declared outside any function and are not specified in any function. They can be used by any part of the program
This means that a global variable can be accessed inside or outside of the function (local and global).
Examples:
- x = 600
def myfunc():
print(x)
myfunc()
print(x)
Output: 600
600
A variable created outside of a function is global and can be used by anyone.
- x = “Python”
def func5()
print(“Local Variable”, x)
func5
print(‘Global Variable’, x)
Output: Local Variable Python
Global Variable Python