Python Variable Scope – Local, Global, Built-in, Enclosed
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
Today, we will discuss Python Variable Scope. Here, we will learn different types of variable scope in Python, Python Global Keyword and Python Non-local keywords.
So, let’s start our learning.
What is Python Variable Scope?
The scope of a variable in python is that part of the code where it is visible. Actually, to refer to it, you don’t need to use any prefixes then.
Let’s take an example, but before let’s revise python Syntax.
>>> b=8 >>> def func(): a=7 print(a) print(b) >>> func()
Output
8
>>> a
Output
File “<pyshell#6>”, line 1, in <module>
a
NameError: name ‘a’ is not defined
Also, the duration for which a variable is alive is called its ‘lifetime’.
Types of Python Variable Scope
There are 4 types of Variable Scope in Python, let’s discuss them one by one:
1. Local Scope in Python
In the above code, we define a variable ‘a’ in a function ‘func’. So, ‘a’ is local to ‘func’. Hence, we can read/write it in func, but not outside it.
When we try to do so, it raises a NameError. Look at this code.
>>> a=0 >>> def func(): print(a) a=1 print(a) >>> func()
Output
File “<pyshell#79>”, line 1, in <module>
func()
File “<pyshell#78>”, line 2, in func
print(a)
UnboundLocalError: local variable ‘a’ referenced before assignment
Here, we could’ve accessed the global Scope ‘a’ inside ‘func’, but since we also define a local ‘a’ in it, it no longer accesses the global ‘a’.
Then, the first print statement inside ‘func’ throws an error in Python, because we’re trying to access the local scope ‘a’ before assigning it.
However, it is bad practice to try to manipulate global values from inside local scopes. Try to pass it as a parameter to the function.
>>> def func(a=0): a+=1 print(a) >>> func()
Output
2. Global Scope in Python
We also declare a variable ‘b’ outside any other python Variable scope, this makes it global scope.
Consequently, we can read it anywhere in the program. Later in this article, we will see how to write it inside func.
3. Enclosing Scope in Python
Let’s take another example.
>>> def red(): a=1 def blue(): b=2 print(a) print(b) blue() print(a) >>> red()
Output
2
1
In this code, ‘b’ has local scope in Python function ‘blue’, and ‘a’ has nonlocal scope in ‘blue’.
Of course, a python variable scope that isn’t global or local is nonlocal. This is also called the enclosing scope.
4. Built-in Scope
Finally, we talk about the widest scope. The built-in scope has all the names that are loaded into python variable scope when we start the interpreter.
For example, we never need to import any module to access functions like print() and id().
Global Keyword in Python
So far, we haven’t had any kind of a problem with global scope. So let’s take an example.
>>> a=1 >>> def counter(): a=2 print(a) >>> counter()
Output
Now, when we make a reference to ‘a’ outside this function, we get 1 instead of 2.
>>> a
Output
Why does this happen? Well, this is because when we set ‘a’ to 2, it created a local variable ‘a’ in the local scope of ‘counter’.
This didn’t change anything for the global ‘a’. Now, what if you wanted to change the global version of ‘a’? We use the ‘global’ keyword in python for this.
>>> a=1 >>> def counter(): global a a=2 print(a) >>> counter()
Output
>>> a
Output
What we do here is, we declare that the ‘a’ we’re going to use in this function is from the global scope.
After this, whenever we make a reference to ‘a’ inside ‘counter’, the interpreter knows we’re talking about the global ‘a’.
In this example, it changed the value of the global ‘a’ to 2.
Nonlocal Keyword in Python
Like the ‘global’ keyword, you want to make a change to a nonlocal variable, you must use the ‘nonlocal’ keyword. Let’s first try this without the keyword.
>>> def red(): a=1 def blue(): a=2 b=2 print(a) print(b) blue() print(a) >>> red()
Output
2
1
As you can see, this did not change the value of ‘a’ outside function ‘blue’. To be able to do that, we use ‘nonlocal’.
>>> def red(): a=1 def blue(): nonlocal a a=2 b=2 print(a) print(b) blue() print(a) >>> red()
Output
2
2
See? This works perfectly fine.
Python Interview Question on Python Variable Scope
- What do you mean by scope?
- What are the types of variable scope?
- What is scope of variable with example?
- What are python variables?
- How do you declare a variable in Python 3?
Conclusion
We hope that the Python variable scope is clearer to you. We saw four types of scope- local scope, enclosed scope, global scope, and built-in scope.
We also saw two keywords- ‘global’ and ‘nonlocal’. Hope you had fun, see you again.
Your opinion matters
Please write your valuable feedback about DataFlair on Google
Great explanation.. very clear understanding for beginners
Thanks Pavani for such appreciable comment. Glad to read that our Python variable scope tutorial helped you. If you are beginner we recommend you check the sidebar and read accordingly. You will be going to enjoy your Python reading with us. In this sidebar, we have provided a complete series of Python tutorials which will help you to become a master in Python.
Happy learning.
Hello, thank you for tutorials. But i have a question.
a = 1
def func():
print(a)
a=0
print(a)
func() #okay this gives an error, but
def red():
a = 1
def blue():
print(a) #why doesnt this give an error? isnt it like the previous example
b = 2
print(a)
print(b)
blue()
print(a)
red()
In your code ,’b’ has local scope in python fun ‘blue’, and ‘a’ has nonlocal scope in ‘blue’, and Of course, a python variable scope that isn’t global or local is nonlocal. This is also called enclosing scope. that’s why it doesn’t give an error..
Yes, thats true.
In func(), a is a local variable and we are referencing it before assignment but in case of blue(), a is a global variable thus no error here.
in nonlocal keyword we called red ( ) , but skip this it takes blue( ),my question is behind the code how interpreter works ?
Hello Makin,
We do make a call to red() here. But inside red, we defined a function blue, and then made a call to that. So it isn’t skipping red, but rather making a call to blue from inside of red.
Hope, it helps.
Keep Learning and Keep Exploring DataFlair
In the first example printing the a and b, how the b can be printed, it is out side the function and it can’t be accessed. Please explain.
Hi Sai
Thanks for commenting. a is local to func and cannot be read outside it, but we can read b from inside func. If we had to modify b inside func, we would first have to declare it global.
I couldn’t understand what is build-in scope
Python built-in scope has all the names that are loaded into python variable scope when we start the interpreter.
>>> def red():
a=1
def blue():
b=2
print(a)
print(b)
blue()
print(b)
>>> red()
1
2
7
why b value is 7..please explain
b’s value is 1 output is 1 2 1. Please rerun your code and verify
Might be variable b is already assigned with ‘7’ before defining function in your Python Interpreter. If it is already not defined, “NameError: name ‘b’ is not defined” error would have thrown.
invaders=’big names’
pos=200
level=1
def play():
max_level=level+10
print(len(invaders)==0)
return max_level
res=play()
print(res)
can someone tell me what is local, global and built-in variable in this code.
invaders=’big names’
pos=200
level=1
def play():
print(“\n In play:, __name__: “, __name__)
print(“\t\t globals: “, [k for k in globals().keys() if not k.startswith(‘__’)])
print(“\t\t locals; “, [k for k in locals().keys() if not k.startswith(‘__’)])
max_level=level+10
print(len(invaders)==0)
print(“\t\t globals: “, [k for k in globals().keys() if not k.startswith(‘__’)])
print(“\t\t locals; “, [k for k in locals().keys() if not k.startswith(‘__’)])
return max_level
res=play()
print(res)
print(“\n At global scope, __name__: “, __name__)
print(“\t globals: “, [k for k in globals().keys() if not k.startswith(‘__’)])
print(“\t locals; “, [k for k in locals().keys() if not k.startswith(‘__’)])
Outputs the following:
In play:, __name__: __main__
globals: [‘invaders’, ‘pos’, ‘level’, ‘play’]
locals; []
False
globals: [‘invaders’, ‘pos’, ‘level’, ‘play’]
locals; [‘max_level’]
11
At global scope, __name__: __main__
globals: [‘invaders’, ‘pos’, ‘level’, ‘play’, ‘res’]
locals; [‘invaders’, ‘pos’, ‘level’, ‘play’, ‘res’]
Thanks a lot it’s actually helpful to learn the concept clearly 😅😅🤩🤩🤩✌️❤️
We are glad to see that you liked Python variable scope tutorial. Do not miss to check Free Python course by DataFlair
Good materials but one negative thing is a website full of popup ads this makes irritating.
Hey! Use Brave-Browser. No Ads at all.
global keyward does not let change value of variable if its inside nested function but nonlocal does. right?