Bytes

home

bytes

tutorials

python

python variable scope

Variable Scope in Python

Module - 6 Functions in Python
Variable Scope in Python

Overview

The scope of a variable alludes to where it can be accessed in a program. A variable's scope depends on where it is announced and is confined to the piece in which it was defined. Program engineers understand the contrast between local variables, limited to a particular block, and global variables, which can be accessed throughout the complete program.

Introduction

In Python programming, distinctive scopes of variables can be utilized to form effective programs. The scope of a variable refers to where it can be accessed and used inside a program. The scope decides which parts of the code can utilize the variable and its corresponding value. There are two fundamental types of scopes for variables:

  • Local variable
  • Global variable

Local variable:

Local variables are the variables that are declared inside a function. It can only be accessed within that function and is not visible to the rest of the program. Once the function has finished executing, the local variable is destroyed. Here's an example:

def my_function():
    x = 10
    print(x)

my_function()  # Output: 10
print(x)       # Output: NameError: name 'x' is not defined

In this example, we declare a local variable x inside the function my_function(). We can access this variable within the function, but outside of the function, it is not defined.

Global variable:

Global variables ūüďą are the variables that are declared outside of any function. It can be accessed anywhere in the program, including¬†within¬†functions. Here's an example:

x = 10

def my_function():
    print(x)

my_function()  # Output: 10
print(x)       # Output: 10

In this example, we declare a global variable x ūüďą outside the function my_function(). We can access this variable from inside the function as well as outside of it.

Global keyword

Suppose you want to modify the value of a global variable inside a function. In that case, you need to use the global keyword to tell Python that you are referring to the global variable, not a local variable with the same name. Here's an example:

x = 10

def my_function():
    global x
    x = 20
    print(x)

my_function()  # Output: 20
print(x)       # Output: 20

In this illustration, we announce a global variable x outside the function my_function(). Inside the function, we utilize the global keyword to indicate that we refer to the global variable x, not a local variable. We then adjust the value of x to 20 and print it out. After the function has wrapped up executing, the value of the global variable x has been upgraded to 20.

Nonlocal keyword

Nonlocal may be a keyword in Python utilized to declare a variable as nonlocal (outside the current scope). This implies that the variable can be referenced and adjusted inside a nested function. The nonlocal keyword declares a variable as nonlocal if defined outside the current scope.

def outer_func():
    x = "local"
    def inner_func():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)
    inner_func()
    print("outer:", x)

outer_func()

This code uses the nonlocal keyword to declare a variable as nonlocal (outside the current scope). The variable x is declared local in the outer_func() function and then modified as nonlocal in the inner_func() function. When inner_func() is called, the variable x is modified to "nonlocal", and then the outer_func() prints the value of x as "nonlocal".

LEGB rule

Apart from local and global variables, there are two more scopes. Let's explore them.

LEGB stands for Local, Enclosing, Global, and Built-in. The rule determines the order in which Python looks for a variable when referenced.

The LEGB rule states that Python looks for a variable in the following order:

  1. Local: The local scope refers to the current function or code piece. If the variable is declared inside that function or code block, it will be looked for first in the local scope.
  2. Enclosing: The encasing scope alludes to the function or code block that contains the current function or code block. If the variable is announced within the enclosing scope, it'll be looked for next in the enclosing scope.
  3. Global: The global scope refers to the whole program. If the variable is announced within the global scope, it'll be looked for next within the global scope.
  4. Built-in: The built-in scope alludes to Python's built-in capacities and modules. If the variable is announced within the built-in scope, it'll be looked for final within the built-in scope.

Conclusion

Python has two main types of variable scopes: local and globalūüĆŹ. Local variables are limited to the block in which they are declared, while global variables can be accessed throughout the programūüďĎ. To modify the value of a global variable inside a function, the global keyword is used. The nonlocal keyword is used to declare a nonlocal variable even if the variable is defined outside the current scope. Python uses the LEGB rule to determine the order in which it looks for a variable: Local, Enclosing, Global, and Built-in.

Key takeaways

  1. A variable declared inside a function is local to that function and can only be accessed inside the function.
  2. A variable declared outside a function is global and can be accessed anywhere within the program.
  3. In Python, the scope of a variable is decided by where it is declared.
  4. A variable declared within an if statement is only accessible inside the statement.
  5. A function can access global variables but cannot modify them without using the global keyword.
  6. A function can access variables declared in outer functions but cannot change them without using nonlocal.

Quiz:

  1. Which of the following is true about variable scope? 
    1. Local variables can be accessed globally 
    2. Global variables can be accessed locally 
    3. Instance variables can be accessed locally 
    4. Local and instance variables can be accessed globally

Answer:b. Global variables can be accessed locally

  1. What is the order in which Python looks for a variable when it is referenced?
    1. Local, Enclosing, Global, Built-in 
    2. Local, Global, Enclosing, Built-in 
    3. Enclosing, Local, Global, Built-in 
    4. Built-in, Global, Enclosing, Local

Answer:a. Local, Enclosing, Global, Built-in

  1. Which keyword is used to modify the value of a global variable inside a function?
    1. local
    2. global
    3. nonlocal
    4. var

Answer:b. global

  1. What happens to a local variable once the function has finished executing?
    1. The local variable is destroyed.  
    2. The local variable is converted to a global variable. 
    3. The local variable is returned to the calling function.  
    4. The local variable remains in memory until the program terminates.

Answer: a. The local variable is destroyed.

Recommended Courses
Masters in CS: Data Science and Artificial Intelligence
Course
20,000 people are doing this course
Join India's only Pay after placement Master's degree in Data Science. Get an assured job of 5 LPA and above. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.
Certification in Full Stack Data Science and AI
Course
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

Top Articles toRead

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2023 AlmaBetter