← Back to Python Course | Chapter 4: Functions | Lesson 8 of 9

Python में Scope और Lifetime

Scope इस बारे में है कि कोई नाम कहाँ दिखाई देता है, जैसे एक कमरे में फुसफुसाया गया राज़ जिसे दूसरे कमरों के लोग नहीं सुन सकते। किसी function के अंदर बनाए गए नाम आमतौर पर उसी के अंदर रहते हैं।
Syntax
python
global_variable = value

def function_name():
    local_variable = value
    global global_variable

Local Scope

किसी function के अंदर बनाया गया variable सिर्फ़ उस function के local scope में exist करता है -- यह function शुरू होने पर बनता है और return होने पर destroy हो जाता है, उस function के बाहर किसी भी code को दिखाई नहीं देता।

उदाहरण: Local Scope

python
def greet():
    message = "Hello"  # local variable, only exists inside greet()
    print(message)

greet()

Global Scope

किसी script के top level पर, किसी function के बाहर assign किए गए variables global scope में रहते हैं और किसी भी function के अंदर से बिना किसी special syntax के *पढ़े* जा सकते हैं -- सिर्फ़ उन्हें *दोबारा assign* करने के लिए extra steps चाहिए।

उदाहरण: Global Scope

python
count = 10  # global variable, defined outside any function

def show():
    print(count)  # can read the global variable without any special syntax

show()

global Keyword

किसी function के अंदर किसी global variable के नाम पर assign करने की कोशिश करना आमतौर पर outer variable को छूने के बजाय एक नया local variable बना देता है; इसे पहले global keyword से declare करना Python को बताता है कि आप असली outer variable को modify करना चाहते हैं।

उदाहरण: The global Keyword

python
count = 0

def increment():
    global count  # declares intent to modify the outer count, not create a local one
    count += 1

increment()
print(count)

Nonlocal Scope

किसी function के अंदर nested किसी दूसरे function में, nonlocal inner function को enclosing (लेकिन global नहीं) function के scope के किसी variable को modify करने देता है -- यह global से अलग है, जो सीधे module level तक पहुँचता है।

उदाहरण: Nonlocal Scope

python
def outer():
    value = 1
    def inner():
        nonlocal value  # refers to outer's value, not the global scope
        value += 1
    inner()
    print(value)

outer()

Built-in Scope

print(), len(), और int() जैसे built-in names Python के built-in scope में रहते हैं, जो सबसे बाहरी layer है और सबसे आख़िर में जाँचा जाता है, यही वजह है कि आप इन्हें बिना import या खुद define किए, कहीं से भी call कर सकते हैं।

उदाहरण: Built-in Scope

python
print(len("hello"))
print(int("42"))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.