PythonPython · Chapterبەش 8 · Lectureوانە 8.4

Variable Scope: Local and Globalمەودای گۆڕاوەکان: ناوخۆیی و گشتی

Where a variable can be used: parameters and local variables live in their function (Python has no block scope, so loop variables stay), why one function cannot see another's variables, global variables and the global statement, UnboundLocalError, why parameters and return values beat global, and how Python looks names up (LEGB).

لە کوێ بەکار دێت: و لەناو دەژین (Python نییە، بۆیە دەمێننەوە)، بۆچی تر نابینێت، و global، UnboundLocalError، بۆچی و لە global باشترن و Python چۆن ناوەکان دەدۆزێتەوە ⁦(LEGB)⁩.

16 min read16 خولەک خوێندنەوە · 16 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Explain what the scope of a variable is, with the board-and-notebook picture.
  • Tell where parameters, local variables and loop variables can be used, and that Python has no block scope.
  • Read and update global variables correctly, and explain NameError and UnboundLocalError.
  • Replace global with parameters and return values, and explain why that is better.
  • ڕوونی بکەیتەوە چییە، بە وێنەی تەختە و دەفتەر.
  • بزانیت ، و لە کوێ بەکار دێن و کە Python نییە.
  • بە دروستی بخوێنیتەوە و نوێ بکەیتەوە و NameError و UnboundLocalError ڕوون بکەیتەوە.
  • global بە و بگۆڕیت و ڕوونی بکەیتەوە بۆچی ئەوە باشترە.

What is scope?مەودا چییە؟

The of a variable is the part of the program in which you can access it. Outside its scope, the name simply does not exist, and Python says NameError.

ئەو بەشەیە لە کە تێیدا دەتوانیت دەستت پێی بگات. لە دەرەوەی ، ناوەکە هەر بوونی نییە و Python دەڵێت NameError.

Definitionپێناسە

The part of a program where a name, such as a variable, can be used. A variable made inside a has ; one made outside all functions has .

ئەو بەشەی کە ناوێک، وەک ، تێیدا بەکار دێت. گۆڕاوێک کە لەناو دروست دەکرێت، تەنها لەناو دەناسرێت؛ گۆڕاوێک کە لە دەرەوەی هەموو دروست دەکرێت، دەکەوێتە ناو .

Why have scopes at all? They let every function be a small, closed box. You can write a function without checking which names the rest of the program uses, and a function cannot accidentally damage another function's variables. In Python there are two scopes you use every day: the inside a function, and the of the whole file.

بۆچی هەن؟ وا دەکەن هەر سندوقێکی بچووک و داخراو بێت. دەتوانیت بنووسیت بەبێ ئەوەی بپشکنیت باقیی چ ناوێک بەکار دەهێنێت و ناتوانێت بە هەڵە تر تێک بدات. لە Pythonـدا دوو هەن کە هەموو ڕۆژێک بەکاریان دەهێنیت: لەناو و هەموو فایلەکە.

Quick checkپشکنینی خێراYou use a variable outside its scope. What does Python say? لە دەرەوەی بەکار دەهێنیت. Python چی دەڵێت؟

Python variable scope 🔬Bro Code · Englishئینگلیزی · 42K viewsبینین · 2.1K likesلایک

A short first look at scope: a variable is only known inside the region where it was made, local inside a function, global outside.

یەکەم سەیرێکی کورتی : تەنها لەو بەشەدا دەناسرێت کە تێیدا دروستکراوە؛ لەناو ، لە دەرەوە .

Whole video (3:52): what scope is (0:19), then a local and a global variable with the same name (1:13).

هەموو ڤیدیۆکە ⁦(3:52)⁩: چییە ⁦(0:19)⁩، پاشان و بە هەمان ناو ⁦(1:13)⁩.

What is scope?مەودا چییە؟

An everyday picture: the board and the notebooksوێنەیەکی ڕۆژانە: تەختەکە و دەفتەرەکان

The board and the notebooksتەختەکە و دەفتەرەکان

Think of a classroom. The board at the front is like the global scope: everyone in the room can read what is written on it. Each student's notebook is like the local scope of a function: what Aram writes in his notebook, Shilan cannot read, and both can write answer = 12 in their own notebooks without any clash. Reading the board needs no permission, but writing on it does — in Python that permission is the global statement.

پۆلێکی خوێندن بهێنە بەرچاو. تەختەکەی پێشەوەی پۆل وەک وایە: هەموو کەسێکی ناو پۆلەکە دەتوانێت ئەوەی لەسەری نووسراوە بخوێنێتەوە. دەفتەری هەر قوتابییەک وەک لەناو وایە: ئەوەی ئارام لە دەفتەرەکەی خۆیدا دەینووسێت، شیلان ناتوانێت بیخوێنێتەوە. هەردووکیان دەتوانن لە دەفتەری خۆیاندا answer = 12 بنووسن بەبێ ئەوەی تێکبگیرێن. خوێندنەوەی تەختەکە پێویستی بە مۆڵەت نییە، بەڵام نووسین لەسەری مۆڵەتی دەوێت — لە Pythonـدا ئەو مۆڵەتە globalـە.

Where the analogy stops workingسنووری ئەم نموونەیە

A function gets a fresh, empty notebook at every call, and the notebook is thrown away when the call ends: nothing written in it is kept for the next call. And if a student writes a name in the notebook that is also on the board, then for the whole lesson (the whole function) that name means the notebook's value, not the board's.

هەر بانگکردنێک دەفتەرێکی نوێ و بەتاڵ وەردەگرێت و کاتێک بانگکردنەکە تەواو دەبێت فڕێ دەدرێت: هیچ شتێکی ناوی بۆ بانگکردنی داهاتوو نامێنێتەوە. هەروەها ئەگەر قوتابییەک ناوێک لە دەفتەرەکەیدا بنووسێت کە لەسەر تەختەکەش هەیە، ئەوا بۆ هەموو وانەکە (هەموو ) ئەو ناوە واتای نرخەکەی دەفتەرەکە دەدات، نەک هی تەختەکە.

Quick checkپشکنینی خێراIn the classroom picture, what is a function's local scope?لە وێنەی پۆلەکەدا، لەناو چییە؟

Parameters live inside their functionپارامیتەرەکان لەناو کردارەکەیان دەژین

The scope of a function's parameter is the entire function: every line of the body can use it. Here the scope of side_length is the whole cube_volume function — but not main:

هەموو : هەموو دێڕێکی جەستەکە دەتوانێت بەکاری بهێنێت. لێرەدا side_length هەموو cube_volumeـە — بەڵام main نا:

side_length belongs to cube_volume⁦side_length⁩ هی ⁦cube_volume⁩ـەcube_scope.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def main():
    print(cube_volume(10))


def cube_volume(side_length):
    return side_length ** 3    # side_length can be used anywhere in here


main()
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5-6

The scope of side_length: from the header to the end of cube_volume.

side_length: لە سەردێڕەکەوە تا کۆتایی cube_volume.

What if main tries to use side_length after the call? The parameter existed only while cube_volume was running, and only inside it:

ئەگەر main هەوڵ بدات دوای بانگکردنەکە side_length بەکار بهێنێت چی ڕوو دەدات؟ تەنها لە کاتی کارکردنی cube_volume و تەنها لەناو ئەودا بوونی هەبوو:

main cannot see the parametermain پارامیتەرەکە نابینێتparam_outside.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def main():
    print(cube_volume(10))
    print(side_length)         # main cannot see cube_volume's parameter


def cube_volume(side_length):
    return side_length ** 3


main()
Quick checkپشکنینی خێراWhere can the parameter side_length of cube_volume be used? side_lengthـی cube_volume لە کوێ بەکار دێت؟

Local variablesگۆڕاوە ناوخۆییەکان

A variable that is created inside a function is called a . It becomes available from the line where it first gets a value until the end of that function — including after a loop or an if it was created in.

کە لەناو دروست دەکرێت پێی دەوترێت . لەو دێڕەوە کە یەکەم جار نرخ وەردەگرێت تا کۆتایی ئەو بەردەستە — تەنانەت دوای ئەو یان ifـەش کە تێیدا دروست کرابوو.

Definitionپێناسە

A created inside a . It can be used only inside that function and disappears when the function ends; the next call starts with a new one. (PHP's static variables are the exception: they keep their value between calls.)

کە لەناو دروست دەکرێت. تەنها لەناو ئەو بەکار دێت و کاتێک کارەکەی تەواو بوو لەناو دەچێت؛ بانگکردنی دواتر بە گۆڕاوێکی نوێ دەست پێ دەکات. (گۆڕاوە staticـەکانی PHP جیاوازن: نرخەکەیان لە نێوان بانگکردنەکاندا دەمێنێتەوە.)

square is still there after the loopsquare دوای خولەکە هێشتا هەیەsquare_total.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def main():
    total = 0
    for i in range(11):
        square = i * i       # square is created here ...
        total = total + square

    print(square, total)     # ... and still exists after the loop


main()
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

square is created inside the loop body ...

square لەناو جەستەی دروست دەکرێت ...

Lineدێڕی 7

... and can still be used here, after the loop: it holds the last square, 10×10=10010 \times 10 = 100. The total is 0+1+4+⋯+100=3850 + 1 + 4 + \cdots + 100 = 385.

... و هێشتا لێرە، دوای ، بەکار دێت: دوایین دووجا هەڵدەگرێت، 10×10=10010 \times 10 = 100. کۆکەی گشتی 0+1+4+⋯+100=3850 + 1 + 4 + \cdots + 100 = 385ـە.

Quick checkپشکنینی خێراWhich part of a Python program creates a new local scope?کام بەشی Python نوێ دروست دەکات؟

Local variablesگۆڕاوە ناوخۆییەکان

The loop variable stays tooگۆڕاوی خولەکەیش دەمێنێتەوە

A loop variable in a for statement is a local variable as well. Like any local variable, its scope reaches to the end of the function. After the loop it keeps its last value, which for range(11) is 10:

لە forـدا هەروەها . وەک هەر ، تا کۆتایی دەڕوات. دوای دوایین نرخی خۆی دەپارێزێت، کە بۆ range(11) ژمارە ⁦10⁩ـە:

i after the loopi دوای خولەکەloop_variable.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def main():
    total = 0
    for i in range(11):
        square = i * i
        total = total + square

    print(i, total)          # the loop variable keeps its last value


main()

Because Python has no block scope, a variable made inside an if exists only if that branch ran. When it did not, the name is local but has no value — a classic surprise:

لەبەر ئەوەی Python نییە، کە لەناو ifـدا دروست دەکرێت تەنها ئەگەر ئەو لقە جێبەجێ بووبێت بوونی هەیە. ئەگەر جێبەجێ نەبووبێت، ناوەکە ناوخۆییە بەڵام نرخی نییە — سەرسوڕمانێکی باو:

message exists only when score >= 50message تەنها کاتێک هەیە کە ⁦score >= 50⁩ بێتif_branch.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def check(score):
    if score >= 50:
        message = "pass"
    print(score, message)


check(70)
check(30)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2-3

For 70 this branch runs and message gets a value; for 30 it is skipped.

بۆ ⁦70⁩ ئەم لقە جێبەجێ دەبێت و message نرخ وەردەگرێت؛ بۆ ⁦30⁩ جێدەهێڵرێت.

Quick checkپشکنینی خێراAfter for i in range(5): pass inside a function, what is i?دوای for i in range(5): pass لەناو ، i چییە؟

A scope problemکێشەیەکی مەودا

Here main creates side_length and then calls cube_volume() without passing anything. cube_volume looks for side_length in its own scope and in the global scope — and finds nothing. main's local variables are private to main:

لێرەدا main side_length دروست دەکات و پاشان بەبێ ناردنی هیچ شتێک cube_volume() بانگ دەکات. cube_volume لە خۆی و لە بەدوای side_lengthـدا دەگەڕێت — و هیچ نادۆزێتەوە. main تایبەتن بە main:

cube_volume cannot see main's variable⁦cube_volume⁩ گۆڕاوەکەی main نابینێتscope_problem.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def main():
    side_length = 10
    result = cube_volume()
    print(result)


def cube_volume():
    return side_length ** 3   # Error


main()

The fix is the normal way functions share data: pass the value as an argument. Now cube_volume has its own parameter called side_length, which receives 10:

چارەسەرەکە ئەو ڕێگا ئاساییەیە کە پێی هاوبەش دەکەن: نرخەکە وەک بنێرە. ئێستا cube_volume خۆی هەیە بە ناوی side_length، کە ژمارە ⁦10⁩ وەردەگرێت:

Pass it inبینێرە ناوەوەscope_fixed.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def main():
    side_length = 10
    result = cube_volume(side_length)   # pass the value in
    print(result)


def cube_volume(side_length):
    return side_length ** 3


main()
Quick checkپشکنینی خێراmain has a variable price. How should a function add_tax() get it?main بە ناوی price هەیە. add_tax() چۆن دەبێت پێی بگات؟

The same name in two functionsهەمان ناو لە دوو کرداردا

You can use the same variable name more than once in a program. Below, both main and square have a variable called result. They are two different variables, each in its own function, and their scopes do not overlap:

دەتوانیت هەمان ناوی زیاتر لە جارێک لە بەکار بهێنیت. لە خوارەوە، هەم main و هەم square هەیە بە ناوی result. ئەمانە دوو جیاوازن، هەر یەکەیان لە خۆیدا و بەسەر یەکدا ناکەون:

Two variables called resultدوو گۆڕاو بە ناوی resultsame_name.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def main():
    result = square(3) + square(4)
    print(result)


def square(n):
    result = n * n
    return result


main()
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

main's result: 9+16=259 + 16 = 25.

resultـی main: 9+16=259 + 16 = 25.

Lineدێڕی 7-8

square's own result, made fresh at each call and gone when the call ends.

resultـی خودی square، کە لە هەر بانگکردنێکدا لە نوێوە دروست دەکرێت و کاتێک بانگکردنەکە تەواو دەبێت نامێنێت.

Nested boxes. The outer box is the built-in scope with print, len and range. Inside it the global scope of the file holds balance = 10000 and the function names main and square. Inside the global box are two separate local boxes: main() with result, and square(n) with n and result. Dashed arrows from both local boxes go out to the global box, marked 'can read'. Between the two local boxes a wall is marked 'cannot see each other's local variables'. A note at the bottom: Python looks outward — local, then global, then built-in.سندوقی ناو یەک. سندوقی دەرەوە مەودای ناوە ئامادەکانە لەگەڵ print، len و range. لەناو ئەودا مەودای گشتیی فایلەکە balance = 10000 و ناوی کردارەکانی main و square هەڵدەگرێت. لەناو سندوقە گشتییەکەدا دوو سندوقی ناوخۆیی جیا هەن: main() لەگەڵ result و square(n) لەگەڵ n و result. تیری پچڕپچڕ لە هەردوو سندوقە ناوخۆییەکەوە بەرەو سندوقە گشتییەکە دەڕۆن، بە نووسینی «دەتوانێت بیخوێنێتەوە». لە نێوان دوو سندوقە ناوخۆییەکەدا دیوارێک هەیە بە نووسینی «گۆڕاوە ناوخۆییەکانی یەکتر نابینن». تێبینییەک لە خوارەوە: Python بەرەو دەرەوە دەگەڕێت — ناوخۆیی، پاشان گشتی، پاشان ئامادە.
Every function call has its own box. Inner boxes can read outer boxes, never the other way round, and never each other.هەر بانگکردنێکی سندوقی خۆی هەیە. سندوقە ناوەکییەکان دەتوانن سندوقە دەرەکییەکان بخوێننەوە، بەڵام هەرگیز بە پێچەوانەوە نا و هەرگیز یەکتریش نا.CêIT
Quick checkپشکنینی خێراIn same_name.py, does square's result = n * n change main's result?لە same_name.pyـدا، ئایا result = n * nـی square resultـی main دەگۆڕێت؟

Global variablesگۆڕاوە گشتییەکان

Variables that are defined outside all functions are called . A function can read a global variable without doing anything special:

ئەو لە دەرەوەی هەموو ناسێنراون پێیان دەوترێت . دەتوانێت بەبێ هیچ کارێکی تایبەت بخوێنێتەوە:

A function reads a globalکردارێک گۆڕاوێکی گشتی دەخوێنێتەوەread_global.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
TEA_PRICE = 500              # a global variable (used as a constant)


def bill(glasses):
    return glasses * TEA_PRICE   # reading a global needs nothing special


print(bill(3))
print(bill(5))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

A name in capitals is a promise not to change it: a . Read-only globals like this are fine.

ناوێک بە پیتی گەورە بەڵێنێکە کە نەگۆڕدرێت: . لەم جۆرە کە تەنها دەخوێنرێنەوە کێشەیان نییە.

The slides say a global variable is visible to all functions that are defined after it. More exactly: what matters is that the global exists when the function runs, not where the def line stands. This function is defined before greeting exists, but it is called after, so it works:

سلایدەکان دەڵێن بۆ هەموو ئەو دوای ئەو ناسێنراون دیارە. وردتر: ئەوەی گرنگە ئەوەیە کە لە کاتی کارکردنی بوونی هەبێت، نەک ئەوەی دێڕی def لە کوێدایە. ئەم پێش بوونی greeting ناسێنراوە، بەڵام دوای ئەو بانگ دەکرێت، بۆیە کار دەکات:

Defined before, called after: it worksپێشتر ناسێنراو، دواتر بانگکراو: کار دەکاتdefined_before.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def greet(name):
    print(greeting + ",", name)   # greeting does not exist yet on this line


greeting = "Hello"     # created AFTER the def line ...
greet("Hana")          # ... but BEFORE the call: it works
Called before the global exists: NameErrorپێش بوونی گۆڕاوە گشتییەکە بانگ کراوە: NameErrorcalled_too_early.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def greet(name):
    print(greeting + ",", name)


greet("Hana")          # called before greeting exists
greeting = "Hello"
Quick checkپشکنینی خێراA function is defined on line 1 and uses the global rate, which is created on line 5. It is called on line 7. Does it work? لە دێڕی 1 ناسێنراوە و rate بەکار دەهێنێت، کە لە دێڕی 5 دروست دەکرێت. لە دێڕی 7 بانگ دەکرێت. ئایا کار دەکات؟

Global variablesگۆڕاوە گشتییەکان

Changing a global: the global statementگۆڕینی گۆڕاوێکی گشتی: ڕستەی global

Any function that wants to update a global variable must say so with a global declaration. Here withdraw takes money from a global balance:

هەر کە بیەوێت نوێ بکاتەوە دەبێت بە ناساندنێکی global ئەمە بڵێت. لێرەدا withdraw پارە لە balanceـی گشتی دەردەهێنێت:

withdraw with globalwithdraw لەگەڵ globalwithdraw_global.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
balance = 10000    # A global variable


def withdraw(amount):
    global balance    # This function intends to update the global balance variable
    if balance >= amount:
        balance = balance - amount


withdraw(2500)
print(balance)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5

global balance: in this function, the name balance means the global variable.

global balance: لەم ، ناوی balance واتە .

Lineدێڕی 7

This assignment now changes the global: 10000−2500=750010000 - 2500 = 7500.

ئەم دێڕە ئێستا دەگۆڕێت: 10000−2500=750010000 - 2500 = 7500.

Animation in two parts. Part A, with global: the global box shows balance = 10000. The call withdraw(2500) opens a local box with amount = 2500. The line global balance draws an arrow from the local box to the global balance. balance = balance - amount changes the global box to 7500; the local box disappears and print(balance) shows 7500. Part B, without the global line: the call opens a local box with amount = 2500 and an empty local balance box, because balance is assigned in the function. The line if balance >= amount reads the empty box and the program stops with UnboundLocalError.
Animation in two parts. Part A, with global: the global box shows balance = 10000. The call withdraw(2500) opens a local box with amount = 2500. The line global balance draws an arrow from the local box to the global balance. balance = balance - amount changes the global box to 7500; the local box disappears and print(balance) shows 7500. Part B, without the global line: the call opens a local box with amount = 2500 and an empty local balance box, because balance is assigned in the function. The line if balance >= amount reads the empty box and the program stops with UnboundLocalError.
With global, the outer box changes. Without it, Python makes a new, empty inner box — and crashes.بە global، سندوقە دەرەکییەکە دەگۆڕێت. بەبێ ئەو، Python سندوقێکی ناوەکیی نوێ و بەتاڵ دروست دەکات — و دەوەستێت.CêIT
Quick checkپشکنینی خێراWhat does global balance tell Python?global balance چی بە Python دەڵێت؟

Global variablesگۆڕاوە گشتییەکان

Without global: UnboundLocalErrorبەبێ ⁦global: UnboundLocalError⁩

If you omit the global declaration, the balance inside withdraw is considered a local variable. Python decides this before the function runs: because balance is assigned somewhere in the body, it is local in the whole body. So the very first line, if balance >= amount:, reads a local balance that has no value yet:

ئەگەر ناساندنی global لابەریت، balanceـی ناو withdraw بە دادەنرێت. Python ئەمە پێش جێبەجێکردنی بڕیار دەدات: لەبەر ئەوەی balance لە شوێنێکی جەستەکەدا نرخی بۆ دادەنرێت، لە هەموو جەستەکەدا ناوخۆییە. بۆیە یەکەم دێڕ، if balance >= amount:، balanceـێکی ناوخۆیی دەخوێنێتەوە کە هێشتا نرخی نییە:

The same program without globalهەمان بەرنامە بەبێ globalwithdraw_no_global.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
balance = 10000    # A global variable


def withdraw(amount):
    if balance >= amount:
        balance = balance - amount


withdraw(2500)
print(balance)

Notice the difference from the scope problem above: there the name did not exist anywhere (NameError); here the name exists as a local variable, but nothing has been put into it yet (UnboundLocalError). And when a function only assigns without reading first, it silently makes a separate local variable and leaves the global alone:

سەرنج بدە جیاوازییەکەی لەگەڵ کێشەی سەرەوە: لەوێ ناوەکە لە هیچ شوێنێک بوونی نەبوو (NameError)؛ لێرە ناوەکە وەک هەیە، بەڵام هێشتا هیچ شتێکی تێ نەکراوە (UnboundLocalError). هەروەها کاتێک تەنها نرخ دادەنێت بەبێ ئەوەی سەرەتا بیخوێنێتەوە، بە بێدەنگی جیا دروست دەکات و دەستکاری ناکات:

A separate local balancebalanceـێکی ناوخۆیی جیاseparate_local.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
balance = 10000


def show_change(amount):
    balance = 5000 - amount     # a NEW local variable called balance
    print("inside: ", balance)


show_change(2500)
print("outside:", balance)      # the global is untouched
Quick checkپشکنینی خێراcount = 0, then def add(): count = count + 1, then add(). What happens?count = 0، پاشان def add(): count = count + 1، پاشان add(). چی ڕوو دەدات؟

Why to avoid globalبۆچی خۆت لە global بپارێزیت

global works, but experienced programmers use it rarely. A function that changes a global has a : it changes something outside itself that the caller cannot see in the call. That causes three problems:

global کار دەکات، بەڵام بە ئەزموون کەم بەکاری دەهێنن. کە دەگۆڕێت هەیە: شتێک لە دەرەوەی خۆی دەگۆڕێت کە لە بانگکردنەکەدا نایبینێت. ئەمە سێ کێشە دروست دەکات:

  • Hard to follow. Reading withdraw(2500), you cannot tell that it changes balance. In a long program any function might be the one that changed it.
  • Hard to reuse and test. The function only works if a global with exactly that name exists. You cannot use it for two bank accounts at once.
  • Name clashes. Two parts of the program may use the same global name for different things.
  • بەدواداچوونی قورسە. کاتێک withdraw(2500) دەخوێنیتەوە، ناتوانیت بزانیت کە balance دەگۆڕێت. لە درێژدا هەر دەکرێت ئەوە بێت کە گۆڕیویەتی.
  • دووبارە بەکارهێنان و تاقیکردنەوەی قورسە. تەنها کاتێک کار دەکات کە بە ڕێک ئەو ناوە هەبێت. ناتوانیت لە یەک کاتدا بۆ دوو هەژماری بانک بەکاری بهێنیت.
  • پێکدادانی ناو. دوو بەشی لەوانەیە هەمان ناوی گشتی بۆ دوو شتی جیاواز بەکار بهێنن.

The better design gives the function everything it needs as parameters and gives the result back with return. The caller decides what to do with it:

دیزاینی باشتر هەموو ئەوەی پێویستیەتی وەک پێی دەدات و ئەنجامەکە بە return دەگەڕێنێتەوە. بڕیار دەدات چی لێ بکات:

No global: parameters in, result outبێ global: پارامیتەرەکان دەچنە ژوورەوە، ئەنجام دێتە دەرەوەwithdraw_better.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def withdraw(balance, amount):
    if balance >= amount:
        balance = balance - amount
    return balance


balance = 10000
balance = withdraw(balance, 2500)
print(balance)
balance = withdraw(balance, 9000)   # not enough money: no change
print(balance)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

Everything the function uses arrives as a parameter.

هەموو ئەوەی بەکاری دەهێنێت وەک دەگات.

Lineدێڕی 8

The caller can see the change: the new balance comes back and is stored.

گۆڕانکارییەکە دەبینێت: باڵانسە نوێیەکە دەگەڕێتەوە و هەڵدەگیرێت.

Lineدێڕی 10

Not enough money: the same balance comes back.

پارە بەس نییە: هەمان باڵانس دەگەڕێتەوە.

Quick checkپشکنینی خێراWhich version of withdraw is easiest to reuse for two different accounts?کام وەشانی withdraw بۆ دوو هەژماری جیاواز ئاسانترە دووبارە بەکار بهێنرێتەوە؟

Why You Shouldn't Use the Global Keyword in PythonTech With Tim · Englishئینگلیزی · 50K viewsبینین · 2.2K likesلایک · Partبەشی 14:03–17:58 (ofلە 17:58)

Why changing a global variable inside a function causes trouble, and how a parameter and a return value do the same job more safely.

بۆچی گۆڕینی لەناو کێشە دروست دەکات و چۆن و هەمان کار بە سەلامەتی زیاتر دەکەن.

Watch from 14:03: add_7() written with global result and then with return x + 7, and (16:41) why you should not rely on global.

لە ⁦14:03⁩ بەدواوە سەیر بکە: add_7() جارێک بە global result و پاشان بە return x + 7 دەنووسرێت، هەروەها ⁦(16:41)⁩ بۆچی نابێت پشت بە global ببەستیت.

Extra: where Python looks for a nameزیادە: Python لە کوێ بەدوای ناوێکدا دەگەڕێت

When Python meets a name, it searches the scopes from the inside out and stops at the first match: Local (the current function), Enclosing (a function around it, if functions are nested), Global (the file), Built-in (names like print and len). Programmers call this the LEGB rule:

کاتێک Python بە ناوێک دەگات، لە ناوەوە بەرەو دەرەوە بە دەگەڕێت و لە یەکەم دۆزینەوەدا دەوەستێت: Local (ئەو ئێستا کار دەکات)، Enclosing ( دەوروبەری، ئەگەر لەناو یەکدا بن)، Global (فایلەکە)، B⁦uilt-in⁩ (ناوەکانی وەک print و len). ئەمە بە یاسای LEGB ناو دەبەن:

Local, enclosing, global, built-inناوخۆیی، دەوروبەر، گشتی، ئامادەlookup.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
name = "global name"


def outer():
    name = "enclosing name"

    def inner():
        print(name)       # not local here: Python looks outward
    inner()


outer()
print(name)
print(len("tea"))         # len is found in the built-in scope
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 8

inner has no name of its own, so Python finds the enclosing one.

inner هیچ nameـێکی خۆی نییە، بۆیە Python ئەوەی دەوروبەر دەدۆزێتەوە.

Lineدێڕی 13

len is in no scope of this file: Python finds it among the built-ins.

len لە هیچ ئەم فایلەدا نییە: Python لەناو ناوە ئامادەکاندا دەیدۆزێتەوە.

Searched from top to bottom; the first match winsلە سەرەوە بۆ خوارەوە دەگەڕێت؛ یەکەم دۆزینەوە دەباتەوە
ScopeWhat is in itچی تێدایەExampleنموونە
LocalناوخۆییParameters and variables of the running function و ئەو کار دەکاتn, result
EnclosingدەوروبەرNames of an outer function, when one function is inside anotherناوەکانی دەرەکی، کاتێک لەناو یەکێکی تردایەname in outer()
GlobalگشتیNames made at the top level of the fileئەو ناوانەی لە ئاستی سەرەوەی فایلەکەدا دروست دەکرێنbalance, main
Built-inئامادەNames Python always hasئەو ناوانەی Python هەمیشە هەیەتیprint, len, range
What is Python scope resolution? 🔬Bro Code · Englishئینگلیزی · 57K viewsبینین · 1.7K likesلایک

The LEGB rule: Python looks for a name in the local, enclosing, global and then built-in scope, and stops at the first match.

یاسای LEGB: بە دوای ناوێکدا دەگەڕێت لە ، enclosing، ، پاشان built-in و لە یەکەم دۆزینەوەدا دەوەستێت.

Whole video (5:33): local (0:22), enclosed and global (1:17), built-in scope (4:04).

هەموو ڤیدیۆکە ⁦(5:33)⁩: ⁦(0:22)⁩، enclosed و ⁦(1:17)⁩، built-in ⁦(4:04)⁩.

Common mistakesهەڵە باوەکان

MistakeهەڵەWhat happensچی ڕوو دەداتFixچارەسەر
Using a function's local variable outside itبەکارهێنانی لە دەرەوەیNameError: name '…' is not definedReturn the value and store itنرخەکە بگەڕێنەوە و هەڵی بگرە
Expecting a called function to see the caller's variablesچاوەڕوانی ئەوە کە بانگکراو ببینێتNameErrorPass them as argumentsوەک بیاننێرە
Assigning to a global without global بۆ بەبێ globalUnboundLocalErrorBetter: parameter + return. Or add global name.باشتر: + return. یان global name زیاد بکە.
Assigning without reading first, expecting the global to change بەبێ خوێندنەوە، بە چاوەڕوانیی گۆڕانی A new local variable; the global stays the same, silently نوێ؛ بە بێدەنگی وەک خۆی دەمێنێتەوەReturn the new valueنرخە نوێیەکە بگەڕێنەوە
Creating a variable only inside an ifدروستکردنی تەنها لەناو ifـێکداUnboundLocalErrorGive it a value before the if, or add elseپێش if نرخێکی پێ بدە، یان else زیاد بکە
Thinking a loop variable is gone after the loopپێت وابێت دوای نامێنێتIt keeps its last valueدوایین نرخی خۆی دەپارێزێتUse a new name if the old value would confuseئەگەر نرخە کۆنەکە سەرت لێ دەشێوێنێت، ناوێکی نوێ بەکار بهێنە
Using global for a variable that is local to another functionبەکارهێنانی global بۆ کە ناوخۆییە بۆ ترIt does not reach itپێی ناگاتPass it as an argumentوەک بینێرە

Exercisesڕاهێنانەکان

ExerciseڕاهێنانInside and outsideناوەوە و دەرەوە

What does this program print? Explain why the two lines differ.

ئەم چی چاپ دەکات؟ ڕوونی بکەرەوە بۆچی دوو دێڕەکە جیاوازن.

predict.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
x = 10


def change():
    x = 5
    print("in change:", x)


change()
print("outside:", x)
Show answerوەڵامەکە پیشان بدە
Outputدەرئەنجام
in change: 5
outside: 10

x = 5 inside change creates a local x. The global x is never touched, so it is still 10.

x = 5 لەناو change ناوخۆیی x دروست دەکات. xـی گشتی هەرگیز دەستکاری ناکرێت، بۆیە هێشتا ⁦10⁩ـە.

ExerciseڕاهێنانA visitor counter without globalژمێرەری سەردانکەر بەبێ global

This counter works, but it uses global. Rewrite it so that add_visitor takes the count as a parameter and returns the new count. The program must still print 3.

ئەم کار دەکات، بەڵام global بەکار دەهێنێت. دووبارە بینووسەرەوە بە جۆرێک کە add_visitor ژمارەکە وەک وەربگرێت و ژمارە نوێیەکە بگەڕێنێتەوە. دەبێت هێشتا 3 چاپ بکات.

visitors_global.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
count = 0


def add_visitor():
    global count
    count = count + 1


add_visitor()
add_visitor()
add_visitor()
print(count)
Hintئاماژە

def add_visitor(count): return count + 1

def add_visitor(count): return count + 1

Show answerوەڵامەکە پیشان بدە
visitors.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def add_visitor(count):
    return count + 1


count = 0
count = add_visitor(count)
count = add_visitor(count)
count = add_visitor(count)
print(count)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 6

The caller stores what comes back: the change is visible in the call.

ئەوەی دەگەڕێتەوە هەڵدەگرێت: گۆڕانکارییەکە لە بانگکردنەکەدا دیارە.

ExerciseڕاهێنانFind the bugهەڵەکە بدۆزەرەوە

Shilan wrote a function that adds a number to a running total. Why does it crash? Fix it without global, then add 5 and 7 so that the program prints 12.

شیلان نووسیوە کە ژمارەیەک بۆ کۆیەکی بەردەوام زیاد دەکات. بۆچی دەوەستێت؟ بەبێ global چاکی بکەرەوە، پاشان 5 و 7 زیاد بکە بۆ ئەوەی ⁦12⁩ چاپ بکات.

running_total.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
total = 0


def add(n):
    total = total + n


add(5)
print(total)
Show answerوەڵامەکە پیشان بدە

total = total + n assigns to total, so total is local to add, and the right-hand side reads it before it has a value. Pass the total in and return the new one:

total = total + n نرخ بۆ total دادەنێت، بۆیە total بۆ add ناوخۆییە و لای ڕاست پێش ئەوەی نرخی هەبێت دەیخوێنێتەوە. کۆکە بنێرە ناوەوە و کۆی نوێ بگەڕێنەوە:

running_total_fixed.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def add(total, n):
    return total + n


total = 0
total = add(total, 5)
total = add(total, 7)
print(total)
ExerciseڕاهێنانLocal or global?ناوخۆیی یان گشتی؟

List every variable in this program and say whether it is local (to which function) or global. What is printed?

هەموو ئەم بنووسە و بڵێ ناوخۆییە (بۆ کام ) یان گشتی. چی چاپ دەکرێت؟

local_or_global.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
rate = 2


def scale(n):
    result = n * rate
    rate_note = "times " + str(rate)
    return result


result = scale(4)
print(result)
print(rate)
Show answerوەڵامەکە پیشان بدە
VariableScope
rateglobal (only read inside scale)گشتی (لەناو scale تەنها دەخوێنرێتەوە)
n, result, rate_notelocal to scaleناوخۆیی بۆ scale
result (line 10)global — a different variable from scale's resultگشتی — جیاواز لە resultـی ناو scale
Outputدەرئەنجام
8
2
Quick checkپشکنینی خێراWhich statement about Python scope is true?کام ڕستە دەربارەی لە Pythonـدا ڕاستە؟

Summaryپوختە

  • The scope of a variable is the part of the program where you can use it.
  • Parameters and variables created in a function are local: from their first assignment to the end of the function, during one call only.
  • In Python, loops and if bodies make no new scope (Java and C# have block scope).
  • Functions cannot see each other's local variables; the same name in two functions means two variables.
  • Global variables are made outside all functions. Any function can read one that exists when it runs; changing it needs global.
  • Assigning to a name anywhere in a function makes it local there → UnboundLocalError if you read it first.
  • Prefer parameters and return values to global: no hidden side effects, easier to reuse and test.
  • ئەو بەشەی کە تێیدا دەتوانیت بەکاری بهێنیت.
  • و ئەو لەناو دروست دەکرێن ناوخۆیین: لە یەکەم نرخدانانیانەوە تا کۆتایی ، تەنها لە ماوەی یەک بانگکردندا.
  • لە Pythonـدا و جەستەی if هیچ نوێ دروست ناکەن (Java و ⁦C#⁩ هەیە).
  • یەکتر نابینن؛ هەمان ناو لە دوو واتە دوو .
  • لە دەرەوەی هەموو دروست دەکرێن. هەر دەتوانێت ئەوەیان بخوێنێتەوە کە لە کاتی کارکردنیدا هەیە؛ گۆڕینی پێویستی بە global هەیە.
  • نرخدانان بۆ ناوێک لە هەر شوێنێکی وا دەکات لەوێ ناوخۆیی بێت ← ئەگەر سەرەتا بیخوێنیتەوە UnboundLocalError.
  • و لە global باشترن: هیچ شاراوە نییە و دووبارە بەکارهێنان و تاقیکردنەوەیان ئاسانترە.
Review questionsپرسیارەکانی پێداچوونەوە
What is the difference between NameError and UnboundLocalError?جیاوازیی نێوان NameError و UnboundLocalError چییە؟

NameError: the name exists in no scope that Python searched. UnboundLocalError: the name is local to the function (it is assigned there) but has no value yet.

NameError: ناوەکە لە هیچ ئەو Python تێیدا گەڕاوە نییە. UnboundLocalError: ناوەکە بۆ ناوخۆییە (لەوێ نرخی بۆ دادەنرێت) بەڵام هێشتا نرخی نییە.

Can two functions use a local variable with the same name?ئایا دوو کردار دەتوانن گۆڕاوێکی ناوخۆیی بە هەمان ناو بەکار بهێنن؟

Yes. Each function has its own scope, so they are two separate variables.

بەڵێ. هەر خۆی هەیە، بۆیە دوو جیان.

Why is global best avoided?بۆچی باشترە خۆت لە global بپارێزیت؟

It gives functions hidden side effects and ties them to one variable name. Parameters and return values keep each function a closed box.

شاراوە دەداتە و بە یەک ناوی دەیانبەستێتەوە. و هەر وەک سندوقێکی داخراو دەهێڵنەوە.

Next: Modules and import — how to keep functions in their own files and reuse them, and the ready-made modules of Python's standard library.

دواتر: مۆدیوڵەکان و import — چۆن لە فایلی خۆیاندا هەڵبگریت و دووبارە بەکاریان بهێنیتەوە، هەروەها ئامادەی Python.

Videoڤیدیۆ

Watch a videoسەیری ڤیدیۆیەک بکە

A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.

Python Tutorial: Variable Scope - Understanding the LEGB rule and global/nonlocal statementsCorey Schafer · Englishئینگلیزی · 414K viewsبینین · 12K likesلایک · Partبەشی 0:35–9:25 (ofلە 20:58)

How Python decides where a name can be used: local scope inside a function, global scope in the file, and the global statement.

چۆن بڕیار دەدات ناوێک لە کوێ بەکاردێت: لەناو ، لە و global.

Watch 0:35–9:25: the scoping rules, global and local scope (1:31) and the global statement (7:07). Stops before the built-in and enclosing scopes.

لە ⁦0:35⁩ تا ⁦9:25⁩ سەیر بکە: یاساکانی ، و ⁦(1:31)⁩ و global ⁦(7:07)⁩. پێش built-in و enclosing ڕادەوەستێت.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Modules and importمۆدیوڵەکان و import

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.