Thursday, December 26, 2024
Google search engine
HomeLanguagesPython Scope of Variables

Python Scope of Variables

In Python, variables are the containers for storing data values. Unlike other languages like C/C++/JAVA, Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. 

Python Scope variable

The location where we can find a variable and also access it if required is called the scope of a variable.

Python Local variable

Local variables are those that are initialized within a function and are unique to that function. It cannot be accessed outside of the function. Let’s look at how to make a local variable.

Python3




def f():
 
    # local variable
    s = "I love GeeksforLazyroar"
    print(s)
 
 
# Driver code
f()


Output

I love GeeksforLazyroar

If we will try to use this local variable outside the function then let’s see what will happen.

Python3




def f():
     
    # local variable
    s = "I love GeeksforLazyroar"
    print("Inside Function:", s)
 
# Driver code
f()
print(s)


Output:

NameError: name 's' is not defined

Python Global variables

Global variables are the ones that are defined and declared outside any function and are not specified to any function. They can be used by any part of the program.

Example:

Python3




# This function uses global variable s
def f():
    print(s)
 
 
# Global scope
s = "I love GeeksforLazyroar"
f()


Output: 

I love GeeksforLazyroar

Global and Local Variables with the Same Name

Now suppose a variable with the same name is defined inside the scope of the function as well then it will print the value given inside the function only and not the global value.

Python3




# This function has a variable with
# name same as s.
def f():
    s = "Me too."
    print(s)
 
# Global scope
s = "I love GeeksforLazyroar"
f()
print(s)


Output:

Me too.
I love GeeksforLazyroar

The variable s is defined as the string “I love GeeksforLazyroar”, before we call the function f(). The only statement in f() is the print(s) statement. As there are no locals, the value from the global s will be used.
The question is, what will happen if we change the value of s inside of the function f()? Will it affect the global s as well? We test it in the following piece of code:

Python3




def f():
    print(s)
 
    # This program will NOT show error
    # if we comment below line.
    s = "Me too."
 
    print(s)
 
 
# Global scope
s = "I love GeeksforLazyroar"
f()
print(s)


Output: 

Traceback (most recent call last):
  File "/home/370cac45bae7f1e6096520b7a0edb604.py", line 13, in 
    f() 
  File "/home/370cac45bae7f1e6096520b7a0edb604.py", line 3, in f
    print(s) 
UnboundLocalError: local variable 's' referenced before assignment

To make the above program work, we need to use global keyword. We only need to use global keyword in a function if we want to do assignments / change them. global is not needed for printing and accessing. Why? Python “assumes” that we want a local variable due to the assignment to s inside of f(), so the first print statement throws this error message. Any variable which is changed or created inside of a function is local, if it hasn’t been declared as a global variable. 

To tell Python, that we want to use the global variable, we have to use the keyword global, as can be seen in the following

Example:

Python3




# This function modifies global variable 's'
def f():
    global s
    print(s)
    s = "Look for GeeksforLazyroar Python Section"
    print(s)
 
 
# Global Scope
s = "Python is great !"
f()
print(s)


Output:  

Python is great!
Look for GeeksforLazyroar Python Section
Look for GeeksforLazyroar Python Section

Consider the below example for a better understanding of the topic. 

Python3




# Python program to demonstrate
# scope of variable
 
a = 1
   
# Uses global because there is no local 'a'
def f():
    print('Inside f() : ', a)
   
# Variable 'a' is redefined as a local
def g():    
    a = 2
    print('Inside g() : ', a)
   
# Uses global keyword to modify global 'a'
def h():    
    global a
    a = 3
    print('Inside h() : ', a)
   
# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)


Output: 

global :  1
Inside f() :  1
global :  1
Inside g() :  2
global :  1
Inside h() :  3
global :  3

Python Nonlocal keyword

In Python, the nonlocal keyword is used in the case of nested functions. This keyword works similarly to the global, but rather than global, this keyword declares a variable to point to the variable of an outside enclosing function, in case of nested functions.

Example: 

Python3




# Python program to demonstrate
# nonlocal keyword
 
print("Value of a using nonlocal is : ", end="")
 
 
def outer():
    a = 5
 
    def inner():
        nonlocal a
        a = 10
    inner()
    print(a)
 
 
outer()
 
# demonstrating without non local
# inner loop not changing the value of outer a
# prints 5
print("Value of a without using nonlocal is : ", end="")
 
 
def outer():
    a = 5
 
    def inner():
        a = 10
    inner()
    print(a)
 
 
outer()


Output: 

Value of a using nonlocal is : 10
Value of a without using nonlocal is : 5

RELATED ARTICLES

Most Popular

Recent Comments