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).
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
NameErrorandUnboundLocalError. - Replace
globalwith 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.
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ـدا دوو هەن کە هەموو ڕۆژێک بەکاریان دەهێنیت: لەناو و هەموو فایلەکە.
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وێنەیەکی ڕۆژانە: تەختەکە و دەفتەرەکان
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.
هەر بانگکردنێک دەفتەرێکی نوێ و بەتاڵ وەردەگرێت و کاتێک بانگکردنەکە تەواو دەبێت فڕێ دەدرێت: هیچ شتێکی ناوی بۆ بانگکردنی داهاتوو نامێنێتەوە. هەروەها ئەگەر قوتابییەک ناوێک لە دەفتەرەکەیدا بنووسێت کە لەسەر تەختەکەش هەیە، ئەوا بۆ هەموو وانەکە (هەموو ) ئەو ناوە واتای نرخەکەی دەفتەرەکە دەدات، نەک هی تەختەکە.
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 نا:
def main():
print(cube_volume(10))
def cube_volume(side_length):
return side_length ** 3 # side_length can be used anywhere in here
main()1000
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5-6
The scope of
side_length: from the header to the end ofcube_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 و تەنها لەناو ئەودا بوونی هەبوو:
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()1000
Traceback (most recent call last):
File "param_outside.py", line 10, in <module>
main()
File "param_outside.py", line 3, in main
print(side_length) # main cannot see cube_volume's parameter
^^^^^^^^^^^
NameError: name 'side_length' is not definedLocal 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ـەش کە تێیدا دروست کرابوو.
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 جیاوازن: نرخەکەیان لە نێوان بانگکردنەکاندا دەمێنێتەوە.)
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()100 385
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
squareis created inside the loop body ...squareلەناو جەستەی دروست دەکرێت ...- Lineدێڕی 7
... and can still be used here, after the loop: it holds the last square, . The total is .
... و هێشتا لێرە، دوای ، بەکار دێت: دوایین دووجا هەڵدەگرێت، . کۆکەی گشتی ـە.
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ـە:
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()10 385
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ـدا دروست دەکرێت تەنها ئەگەر ئەو لقە جێبەجێ بووبێت بوونی هەیە. ئەگەر جێبەجێ نەبووبێت، ناوەکە ناوخۆییە بەڵام نرخی نییە — سەرسوڕمانێکی باو:
def check(score):
if score >= 50:
message = "pass"
print(score, message)
check(70)
check(30)70 pass
Traceback (most recent call last):
File "if_branch.py", line 8, in <module>
check(30)
File "if_branch.py", line 4, in check
print(score, message)
^^^^^^^
UnboundLocalError: cannot access local variable 'message' where it is not associated with a valueFix: give message a value before the if (for example message = "fail"), or add an else.
چارەسەر: پێش if نرخێک بدە بە message (بۆ نموونە message = "fail")، یان elseـێک زیاد بکە.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-3
For 70 this branch runs and
messagegets a value; for 30 it is skipped.بۆ 70 ئەم لقە جێبەجێ دەبێت و
messageنرخ وەردەگرێت؛ بۆ 30 جێدەهێڵرێت.
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:
def main():
side_length = 10
result = cube_volume()
print(result)
def cube_volume():
return side_length ** 3 # Error
main()Traceback (most recent call last):
File "scope_problem.py", line 11, in <module>
main()
File "scope_problem.py", line 3, in main
result = cube_volume()
^^^^^^^^^^^^^
File "scope_problem.py", line 8, in cube_volume
return side_length ** 3 # Error
^^^^^^^^^^^
NameError: name 'side_length' is not definedThe 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 وەردەگرێت:
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()1000
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. ئەمانە دوو جیاوازن، هەر یەکەیان لە خۆیدا و بەسەر یەکدا ناکەون:
def main():
result = square(3) + square(4)
print(result)
def square(n):
result = n * n
return result
main()25
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
main'sresult: .resultـیmain: .- Lineدێڕی 7-8
square's ownresult, made fresh at each call and gone when the call ends.resultـی خودیsquare، کە لە هەر بانگکردنێکدا لە نوێوە دروست دەکرێت و کاتێک بانگکردنەکە تەواو دەبێت نامێنێت.
Global variablesگۆڕاوە گشتییەکان
Variables that are defined outside all functions are called . A function can read a global variable without doing anything special:
ئەو لە دەرەوەی هەموو ناسێنراون پێیان دەوترێت . دەتوانێت بەبێ هیچ کارێکی تایبەت بخوێنێتەوە:
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))1500 2500
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 ناسێنراوە، بەڵام دوای ئەو بانگ دەکرێت، بۆیە کار دەکات:
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 worksHello, Hana
def greet(name):
print(greeting + ",", name)
greet("Hana") # called before greeting exists
greeting = "Hello"Traceback (most recent call last):
File "called_too_early.py", line 5, in <module>
greet("Hana") # called before greeting exists
^^^^^^^^^^^^^
File "called_too_early.py", line 2, in greet
print(greeting + ",", name)
^^^^^^^^
NameError: name 'greeting' is not definedGlobal 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ـی گشتی دەردەهێنێت:
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)7500
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
global balance: in this function, the namebalancemeans the global variable.global balance: لەم ، ناویbalanceواتە .- Lineدێڕی 7
This assignment now changes the global: .
ئەم دێڕە ئێستا دەگۆڕێت: .


global, the outer box changes. Without it, Python makes a new, empty inner box — and crashes.بە global، سندوقە دەرەکییەکە دەگۆڕێت. بەبێ ئەو، Python سندوقێکی ناوەکیی نوێ و بەتاڵ دروست دەکات — و دەوەستێت.CêITGlobal 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ـێکی ناوخۆیی دەخوێنێتەوە کە هێشتا نرخی نییە:
balance = 10000 # A global variable
def withdraw(amount):
if balance >= amount:
balance = balance - amount
withdraw(2500)
print(balance)Traceback (most recent call last):
File "withdraw_no_global.py", line 9, in <module>
withdraw(2500)
File "withdraw_no_global.py", line 5, in withdraw
if balance >= amount:
^^^^^^^
UnboundLocalError: cannot access local variable 'balance' where it is not associated with a valueNotice 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). هەروەها کاتێک تەنها نرخ دادەنێت بەبێ ئەوەی سەرەتا بیخوێنێتەوە، بە بێدەنگی جیا دروست دەکات و دەستکاری ناکات:
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 untouchedinside: 2500 outside: 10000
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 changesbalance. 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 دەگەڕێنێتەوە. بڕیار دەدات چی لێ بکات:
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)7500 7500
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.
پارە بەس نییە: هەمان باڵانس دەگەڕێتەوە.
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 (فایلەکە)، Built-in (ناوەکانی وەک print و len). ئەمە بە یاسای LEGB ناو دەبەن:
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 scopeenclosing name global name 3
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 8
innerhas nonameof its own, so Python finds the enclosing one.innerهیچnameـێکی خۆی نییە، بۆیە Python ئەوەی دەوروبەر دەدۆزێتەوە.- Lineدێڕی 13
lenis in no scope of this file: Python finds it among the built-ins.lenلە هیچ ئەم فایلەدا نییە: Python لەناو ناوە ئامادەکاندا دەیدۆزێتەوە.
| Scope | What 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 |
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 defined | Return the value and store itنرخەکە بگەڕێنەوە و هەڵی بگرە |
| Expecting a called function to see the caller's variablesچاوەڕوانی ئەوە کە بانگکراو ببینێت | NameError | Pass them as argumentsوەک بیاننێرە |
Assigning to a global without global بۆ بەبێ global | UnboundLocalError | Better: 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ـێکدا | UnboundLocalError | Give 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ڕاهێنانەکان
What does this program print? Explain why the two lines differ.
ئەم چی چاپ دەکات؟ ڕوونی بکەرەوە بۆچی دوو دێڕەکە جیاوازن.
x = 10
def change():
x = 5
print("in change:", x)
change()
print("outside:", x)Show answerوەڵامەکە پیشان بدە
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ـە.
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 چاپ بکات.
count = 0
def add_visitor():
global count
count = count + 1
add_visitor()
add_visitor()
add_visitor()
print(count)3
Hintئاماژە
def add_visitor(count): return count + 1
def add_visitor(count): return count + 1
Show answerوەڵامەکە پیشان بدە
def add_visitor(count):
return count + 1
count = 0
count = add_visitor(count)
count = add_visitor(count)
count = add_visitor(count)
print(count)3
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 6
The caller stores what comes back: the change is visible in the call.
ئەوەی دەگەڕێتەوە هەڵدەگرێت: گۆڕانکارییەکە لە بانگکردنەکەدا دیارە.
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 چاپ بکات.
total = 0
def add(n):
total = total + n
add(5)
print(total)Traceback (most recent call last):
File "running_total.py", line 8, in <module>
add(5)
File "running_total.py", line 5, in add
total = total + n
^^^^^
UnboundLocalError: cannot access local variable 'total' where it is not associated with a valueShow 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 ناوخۆییە و لای ڕاست پێش ئەوەی نرخی هەبێت دەیخوێنێتەوە. کۆکە بنێرە ناوەوە و کۆی نوێ بگەڕێنەوە:
def add(total, n):
return total + n
total = 0
total = add(total, 5)
total = add(total, 7)
print(total)12
List every variable in this program and say whether it is local (to which function) or global. What is printed?
هەموو ئەم بنووسە و بڵێ ناوخۆییە (بۆ کام ) یان گشتی. چی چاپ دەکرێت؟
rate = 2
def scale(n):
result = n * rate
rate_note = "times " + str(rate)
return result
result = scale(4)
print(result)
print(rate)Show answerوەڵامەکە پیشان بدە
| Variable | Scope |
|---|---|
rate | global (only read inside scale)گشتی (لەناو scale تەنها دەخوێنرێتەوە) |
n, result, rate_note | local to scaleناوخۆیی بۆ scale |
result (line 10) | global — a different variable from scale's resultگشتی — جیاواز لە resultـی ناو scale |
8 2
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
ifbodies 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 →
UnboundLocalErrorif 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باشترن: هیچ شاراوە نییە و دووبارە بەکارهێنان و تاقیکردنەوەیان ئاسانترە.
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.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
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زاراوە سەرەکییەکان
Modules and importمۆدیوڵەکان و import
Related lecturesوانە پەیوەندیدارەکان
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.