Python Functions and Variable Scope LEGB

In this article, we will discuss Python variables and functions scope and how they work on their concept. Python is one of the popular languages, and we can easily learn and support cross-platform equally run on different operating systems such as Windows, Linux, UNIX, etc. Generally, variables and functions work in a defined way based on scope and data type. Functions will be defined by the 'def' keyword followed by the ':' syntax. Variables are defined based on value assigning, such as int, float, string, or boolean values.

Functions and variable scope have LEGB concepts with different scopes called local, enclosing, global, and built-in.

LEGP- Local scope, Enclosing scope, Global scope, Built-in scope

Local Scope

Local variables will work inside the function or class or any block statement. It won't work outside the scope.

def print_number():
    num = 1   
    print("The number defined is: ", num)

print_number()

#print("The number defined is: ", num) # NameError: name 'num' is not defined

Output

The number defined is: 1

Enclosing Scope

Enclosing variables are suitable for nested way coding, such as nested functions, classes, and loops. The outer variable can be accessed inside the nested function.

def outer():
    num = 1
    def inner():
        sec_num = 2
        # Scope: Inner
        print("num from outer: ", num)
        # Scope: Inner
        print("sec_num from inner: ", sec_num)
    inner()
    # Scope: Outer - access outside the function
    # print("sec_num from inner: ", sec_num)

outer()

Output

num from outer: 1
sec_num from inner: 2

Global Scope

Global Scope variable can be accessed anywhere in the code. Mostly, the Global variable defines the first portion of the coding itself. If we want to define in between the code, use the  'global' keyword and access outside the scope.

globalVar = "Hello"

def change(new_word):
    global globalVar     
    print(new_word,globalVar)

def world():
    world = "World"
    print(globalVar, world)

change("Hi")
world()

Output

Hi Hello
Hello World

Built-in Scope

Buil- in scope is the last scope; its special keyword reserved falls under the scope. Examples are keywords like class, def, print, and in.

print("Built-in scope print statement example")
list1 =[1,2,3,4,5]
for x in list1:
    print(x)

Output

Built-in scope print statement example.

1
2
3
4
5


Recommended Free Ebook
Similar Articles