Python Scope Overview

Scope means ek area/region jaha tak koi bhi parameter apna work kar sakta hai. Technical way me kaha jaye to Scope means program ka wah region jaha ek parameter / function / variable  jo apni working se program ke dusre functionalities ko affect kar sake. Scope ke 2 parts hain – Local aur Global.

Python me Local Scope

Agar ek variable kisi function ke andar defined hai to wah variable sirf uss particular function ke process me helpful hoga aur outside se call hone par accessible nhi hoga.

def foo():
    x = 400                 #Local Variable
    print(x)

foo()                         # access by foo()

Function loop aur Local Scope

Function loop means function ke andar function. Agar x foo() function ka ek local variable hai aur foo_inner() ek nested function hai, to fir kya variable ‘x’ foo_inner() ke liye accessible hoga? Answer hai – Definitely hoga kyuki foo_inner() aur variable ‘x’ dono hi foo() function me locally scoped hain.

def foo():
    x = 300
    def foo_inner():
        print(x)
    foo_inner()

foo()

Python me Global Scope

jab bhi kisi variable ko program ke kisi bhi part me access kiya jata hai to wah Global scope ke category me aata hai. Jise Global variable bhi kaha jata hai. Aur yah global variable program me global scope ke sath-sath local scope me accessible hota hai.

x = 400
def foo():
    print(x)

foo()

Kya hoga jab same variable Local aur Global dono jagah defined hoga?

Agar ek variable Global aur local dono jagah defined hai to local function apne variable ko first priority dega. Example me global variable x = 400 aur local variable x = 500. jab foo() function call hoga to output 500 print karega aur wahi print(x) function 400 print karega.

x = 400
def foo():
    x = 500
    print(x)

foo()
print(x)

Global keyword ka use

Function ke andar present variable ko jab hume global banana hota hai tab hum “Global” keyword ka use karte hain.

def foo():
    global x
    x = 400
    print(x)

foo()
print(x)

ALSO READ :