Python Variable Scope

FREE Online Courses: Transform Your Career – Enroll for Free!

We would have come across the word scope, which we use to refer to when we talk about the extent/ range of something. A similar meaning applies to scope in Python where we talk about the scope of a variable.

In this article, we will talk all about scope. Then the ‘LEGB’ rule that applies to these, and keywords used for modifications. So, let’s begin.

Variable Scope in Python

To revise, a variable is a name that stores the values/data. For example, to store the text “PythonGeeks” we can use the variable ‘text’ to store as shown below:

Example of variable in Python:

text="PythonGeeks" #variable 'text' stores "PythonGeeks"
print(text)

Output:

PythonGeeks

In Python, the scope of a variable refers to the part of the code where we can access the variable. We cannot access all the variables in the code from any part. For instance, look at the below example. Here we use ‘def func()’ to create a function with some statements to perform operations.

Example of scope of Variable in python:

name="PythonGeeks"
def func():
    name2="Python"
    print(name2)
    print(name)

func()

Output:

Python
PythonGeeks

We could access both the variables ‘name’ and ‘name2’ inside the function ‘func()’. What happens if we try to do the same outside the ‘func()’?

Example to show that scope of a variable in a function ends after the function:
print(name)
print(name2)

Outputs:

PythonGeeks
Traceback (most recent call last):
File “<pyshell#8>”, line 1, in <module>
print(name2)
NameError: name ‘name2’ is not defined

We could access ‘name’ but we got an error ‘name2’. This is because the scope of ‘name2’ is only within the ‘func()’.

Different types of variable scope in Python

Learning about what variable scope is, we will now dive into different types of scope. Based on the part of the code where we do the initialization of the variable, their scopes are of four types:

a. Local Scope in Python

When a variable is inside a function, then it is accessible only inside that function. This variable exists only while the function is executing and is called a local variable.

Example of local variable and showing that we cannot access it outside a function:

def func():
  a="PythonGeeks"
  print("Inside the function: value of a is ",a)

func()

print(a)

Output:

Inside the function: value of a is PythonGeeks

Traceback (most recent call last):
File “<pyshell#5>”, line 1, in <module>
print(a)
NameError: name ‘a’ is not defined

We see that we can print the variable ‘a’ only inside the ‘func(). But we get an error accessing it outside the function. This variable has local scope, that is the function ‘func()’.

b. Global Scope of variable in Python

This is the scope of the variable that is available from any part of the code.The variable is initialized outside the functions and is called global variable.

Example of creating a global variable:

text="PythonGeeks"
def func():
    print("Inside the function, the value of text is ", text)

  
func()
print(text)

Output:

Inside the function, the value of text is PythonGeeks
PythonGeeks

In the above example, the variable ‘text’ has global scope. This is because we could access it outside and inside the function ‘func().

c. Enclosed Scope in Python

This is the scope of the variable inside a function with a nested function (i.e., function inside another function). This variable is neither global nor local, so it is also called nonlocal scope.

To understand it clearly, look at the following example:

Example of enclosed scope:

def func():
  s="PythonGeeks"
  def nested_func(): #nested function
    p="Python"
    print("s=",s) 
    print("p=",p)
  nested_func() #calling nested function
  print("s=",s)
  
func()

Output:

s= PythonGeeks
p= Python
s= PythonGeeks

Here, ‘p’ has the local scope of the ‘nested_func()’, and ‘s’ has a nonlocal scope with ‘nested_func().

d. Built-in Scope in Python

All the keywords come under this scope. We can call them from any part of the program and have specific predefined purposes. These get loaded when the interpreter starts and there is no need for importing them separately.

This is the largest scope. Some examples of keywords are: print, def, True, if, else, type, and so on.

Example of built-in variable:

s="Python"
print(s)

def func():
    if(True):
        print("Inside the function")

    
func()

Output:

Python

Inside the function

In the above example we could use the keywords at any part of the program.

LEGB Rule in Python

Done with discussing different types of scopes, now let us know what is LEGB rule. The word LEGB stands for ‘Local -> Enclosing -> Global -> Built-in’.

This represents the preference the interpreter gives during execution. For understanding further see the below code.

Example of LEGB rule:

var="Geeks" #global scope
def func_out(): 
    var="Python" #enclosed scope
    def func_in():
        var="PythonGeeks" #local scope
        print("Printing var in func_in:",var)
    func_in()
    print("Printing var in func_out:",var)

  
func_out()
print("Printing var outside the functions:",var)

Output:

Printing var in func_in: PythonGeeks
Printing var in func_out: Python
Printing var outside the functions: Geeks

When we try accessing the value of a variable, the interpreter first checks if the variable is in the local scope. If not found, it checks for enclosed. If it still doesn’t find it, then it checks for global and so on.

This is the reason in the above example when we print ‘var’ in ‘func_in()’ output is “PythonGeeks”. It is more important to observe that when printed in ‘func_out()’ gives “Python”, and outside the functions, the output is “Geeks”.

Even though the value of the variable is changed in the func_in(), it is not reflected in the func_out() and in global. This is because when we assign “PythonGeeks” to ‘var’ in ‘func_in()’, it creates a new local variable. This neither changed the globally initialized nor the var in ‘func_out()’.

A similar concept applies to the var in ‘func_out()’. When the var is assigned the value ‘Python’ in ‘func_out()’, the interpreter creates a new ‘var’ under this function. This is the reason it did not show up when printed outside the function.

This leads to the concept of using ‘Global’ and ‘Nonlocal’ keywords. Let’s get to know what these are and why they are used.

Using Keywords in Python

a. Global Keyword in Python

We saw in the previous example that the changes in the enclosed scope did not get reflected in the global scope. We might come across cases where we want the change to get reflected. This is where we use the ‘global’ keyword. Besides this, it has other features too. Let’s look at all of them.

Global variable in Python

Using the global keyword outside the function has no effect as variables created outside the function. This is because they are accessible from any part of the code, that is they are global by default. This is shown below.

Example to show variable outside function is global:

name="PythonGeeks"
def func():
    print("Inside the function: name is",name)

  
func()

print(name)

Output:

Inside the function: name is PythonGeeks
PythonGeeks
Variable inside a function in Python

The variable created inside a function is local by default and we cannot access it outside the function. We need to use the ‘global’ keyword to make it globally accessible.

Example of getting error on accessing local variable locally:

def func():
  var="PythonGeeks"
  print("Inside the function, value of var:",var)

  
func()

print("Outside the function value of var:",var)

Output:

Inside the function, value of var: PythonGeeks

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    print("Outside the function value of var:",var)
NameError: name 'var' is not defined

On adding the ‘global’ keyword, we can access the local variables outside the function.

Example on accessing local variable by adding ‘global’ keyword:

def func():
  global var
  var="PythonGeeks"
  print("Inside the function,value of var:",var)

  
func()
print("Outside the function value of var:",var)

Output:

Inside the function,value of var: PythonGeeks

Outside the function value of var: PythonGeeks

Modifying the global variable inside a function in Python

When we try to modify a global variable inside a function it gives an error, as functions can only access.

Example to show locally modifying a global variable gives error:

var="PythonGeeks"
def func():
    var=var*2
    print(var)

  
func()

Output:

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    func()
  File "<pyshell#4>", line 2, in func
    var=var*2
UnboundLocalError: local variable 'var' referenced before assignment

Using global keyword in Python

If we try to modify a global variable locally, by assigning it a value, then it will not give any error. It neither shows change in the value globally. As seen before, for it to reflect change globally, we use the ‘global’ keyword.

Example on using global keyword inside a function:

var="PythonGeeks"
def func():
    global var
    var=var*2
    print("Inside the function var is ",var)

func()

print(var)

Output:

Inside the function var is PythonGeeksPythonGeeks

PythonGeeksPythonGeeks

By adding global, we are asking the interpreter to use the global variable rather than creating a new one. So now the changes made inside the function get reflected globally.

Using Global Keyword in Nested functions in Python

Similar to use in functions, it is also used in nested functions to reflect change globally. But this will not have an effect on the outer function if the same variable name already exists in the outer function.

Example on use of global keyword in nested functions:

def outer():
  x="Python"
  print("Value of x in outer function:",x)
  def inner():
    global x
    x="PythonGeeks"
    print("Value of x in inner function:",x)
  inner()
  print("Value of x in outer function after calling inner function:",x)

  
outer()

print("Value of x outside the functions:",x)

Output:

Value of x in outer function: Python
Value of x in inner function: PythonGeeks
Value of x in outer function after calling inner function: PythonValue of x outside the functions: PythonGeeks

We can see that the value in the outer function did not change and we could access the variable outside the functions.

Using Global Keyword across the modules in Python

We can share the global variables across different modules by using import options. Look at the below example.

Example of using a global variable in different modules:
Creating a file named var.py

n=5
name="Python"

Creating another module modify.py by accessing variables in var.py

import var

var.a=3
var.name="PythonGeeks"

Now create another file print.py to print the above variables by importing modules.

Example of accessing global variables from other Python files:

import var
import modify

print(var.a)
print(var.name)

Output:

3
PythonGeeks

We can see that by importing, we could access and modify the global variables.

b. Nonlocal Keyword in Python

We use this keyword when you want the changes done in the inner function to be reflected in the outer function (nonlocal scope). Let’s see an example for further discussion.

Example of use of nonlocal keyword:

def outer_func():
  name="Geeks"
  def inner_func():
    nonlocal name
    name="PythonGeeks"
    print("Printing name in inner_func:",name)
  inner_func()
  print("Printing name in outer_func:",name)

  
outer_func()

Output:

Printing name in inner_func: PythonGeeks
Printing name in outer_func: PythonGeeks

Here we added nonlocal to the variable. This is done to use the variable in the nonlocal scope and not create a new one. This made the change to the variable ‘name’ show up in the ‘outer_func()’ too.

Python Variable Scope Interview Questions

Q1. In Python, can you make a local variable global? Give a coding example.

Ans 1. To make the local variable global in Python we use the ‘global’ keyword. This will make the variable created in the function, accessible outside the function. The following code block gives the example.

Example on making local variable global:

def func():
  global a
  a= "PythonGeeks"
  print("Inside the function, value of a is ",a)

  
func()

print(a) #accessible outside the function

Output:

Inside the function, value of a is PythonGeeks
PythonGeeks

Q2. Using a coding example show the four types of variables concerning the scope in Python.

Ans 2. The four types of scopes are : local,global, enclosed and built-in. All are used in the below example.

a="PythonGeeks" #global variable
def fun1():
  b=4 #local variable
  def fun2():
    c=10.3 # enclosed variabel
    print("Inside fun2 c is:",c) #built-in variable
    print("Inside fun2 b is:",b) #built-in and local variable
    print("Inside fun2 a is:",a) #built-in and global variable
  fun2()
  print("Inside fun1 b is:",b) #built-in variable
  print("Inside fun1 a is:",a) #built-in and global variable


fun1()

print("Outside the functions a is:",a) #built-in and global variable

Output:

Inside fun2 c is: 10.3
Inside fun2 b is: 4
Inside fun2 a is: PythonGeeks
Inside fun1 b is: 4
Inside fun1 a is: PythonGeeksOutside the functions a is: PythonGeeks

Q3. Is it acceptable to use the same name for global and local variables? Give an example in Python.

Ans 3. Yes, we can use the same variable name for local and global variables. For example, in the below code the variable ‘a’ is used globally and locally. And the code ran without any error.

Example on using same name globally and locally:

a=4
def func():
    a=5
    print("Value of a inside the function:",a)

  
func()
print(a)

Output:

Value of a inside the function: 5
4

Q4. How do you make the local change in global variables affect the global level?

Ans 4. We can use the ‘global’ keyword to make the local changes on a global variable effective even at global level. The below code represents this.

var="Python"
def func():
    global var
    var="PythonGeeks"
    print("Inside the function var is ",var)

func()

print(var)

Output:

Inside the function var is PythonGeeks

PythonGeeks

Q5. Give an alternate way to the ‘nonlocal’ keyword to show the effect of change in inner function at the outer function level using an example.

Ans 5. We can use the reference based approach for changing the variable of outer function in inner function. In this approach, the variable has to be referenced to the function by function.variable. For example,

Example on alternate method to ‘nonlocal’ keyword:

def outer():
  outer.a="Python"
  def inner():
    outer.a="PythonGeeks"
    print("Inside inner function, value of a:",outer.a)
  inner()
  print("Inside outer function, value of a:",outer.a)

outer()

Output:

Inside inner function, value of a: PythonGeeks
Inside outer function, value of a: PythonGeeks

Quiz on Python Variable Scope

Conclusion

In this article, we have learned about the scope of variables in Python and different types of scope. Then we discussed the ‘LEGB’ rule and the problem of the reflection of changes. Then we talked about a solution to this, which is the use of ‘global’ and ‘nonlocal’ keywords.

Hope you understood the concepts discussed and do not fall into errors covered. Happy coding!

Your opinion matters
Please write your valuable feedback about PythonGeeks on Google | Facebook


5 Responses

  1. Roxana G says:

    The best explanation of LEGB I ever came across ?

  2. Adriano Fabio Querino de Brito says:

    Isn’t Question 14 supposed to be ‘Which of the following coding blocks gives the output as “PythonGeeks”?’?

  3. Adriano Fabio Querino de Brito says:

    Isn’t Question 4 supposed to be ‘Which of the following is a built-in keyword?’?

  4. Adriano Fabio Querino de Brito says:

    Shouldn’t the answer to Question 12 be ‘Local’ rather than ‘Nonlocal’?

Leave a Reply

Your email address will not be published. Required fields are marked *