PythonPython · Chapterبەش 8 · Lectureوانە 8.1
Defining and Calling Functionsناساندن و بانگکردنی کردارەکان
Why functions exist, how to define one (header, parameters, body) and call it, parameters versus arguments, how control jumps into a function and back, signatures and type hints, docstrings, built-in versus your own functions, main(), and the Lab 2 pattern function.
بۆچی هەن، چۆن بناسێنیت (، ، جەستە) و بانگی بکەیت، جیاوازیی و ، چۆن باز دەداتە ناو و دەگەڕێتەوە، و ، ، بەرامبەر خۆت، main() و شێوەکێشانی تاقیگەی 2.
What you will learnچی فێر دەبیت
- Explain why functions make programs shorter, clearer and easier to fix.
- Define a function with
defand name its parts: header, parameters and body. - Call value-returning functions as values and functions without a return value as statements.
- Tell parameters from arguments, and trace how control jumps into a function and back.
- Read a function signature, write a docstring, and avoid hiding built-in names.
- ڕوونی بکەیتەوە بۆچی کورتتر، ڕوونتر و ئاسانتر بۆ چاککردنەوە دەکەن.
- بە
defبناسێنیت و ناوی بەشەکانی بڵێیت: ، و جەستە. - وەک و وەک بانگ بکەیت.
- لە جیا بکەیتەوە و بەدوای ئەوەدا بچیت کە چۆن باز دەداتە ناو و دەگەڕێتەوە.
- بخوێنیتەوە، بنووسیت و خۆت لە شاردنەوەی ناوە ئامادەکان بپارێزیت.
Why functions?بۆچی کردارەکان؟
Here is a small problem: find the sum of the whole numbers from 1 to 10, from 20 to 37 and from 35 to 49. Without functions you might write the same loop three times:
کێشەیەکی بچووک: کۆی لە 1 تا 10، لە 20 تا 37 و لە 35 تا 49 بدۆزەوە. بەبێ لەوانەیە هەمان سێ جار بنووسیت:
sum = 0
for i in range(1, 11):
sum += i
print("Sum from 1 to 10 is", sum)
sum = 0
for i in range(20, 38):
sum += i
print("Sum from 20 to 37 is", sum)
sum = 0
for i in range(35, 50):
sum += i
print("Sum from 35 to 49 is", sum)Sum from 1 to 10 is 55 Sum from 20 to 37 is 513 Sum from 35 to 49 is 630
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-4
Sum from 1 to 10.
کۆ لە 1 تا 10.
- Lineدێڕی 6-9
The same code again — only 20 and 38 are different.
هەمان کۆد دیسان — تەنها 20 و 38 جیاوازن.
- Lineدێڕی 11-14
And again, with 35 and 50.
و دیسان، بە 35 و 50.
The three blocks are the same code; only the start and end numbers change. Copying code like this is slow and risky: if you find a mistake, you must fix it in three places. A solves this. You write the common code once, give it a name, and then use it as often as you like. Functions make code reusable, and they organise and simplify a program.
سێ بلۆکەکە هەمان کۆدن؛ تەنها ژمارەی سەرەتا و کۆتایی دەگۆڕێن. کۆپیکردنی کۆد بەم شێوەیە هێواشە و مەترسیدارە: ئەگەر هەڵەیەک بدۆزیتەوە، دەبێت لە سێ شوێندا چاکی بکەیتەوە. ئەم کێشەیە چارەسەر دەکات. کۆدە هاوبەشەکە یەک جار دەنووسیت، ناوێکی لێ دەنێیت و پاشان چەند جارێک بتەوێت بەکاری دەهێنیت. کۆد دووبارە بەکارهێنراو دەکەن و ڕێک و سادە دەکەن.
A named block of code that does one job and can be used again and again by calling its name. It can take and give back a .
بلۆکێکی ناونراوی کۆدە کە کارێکی دیاریکراو ئەنجام دەدات و دەتوانیت بە بانگکردنی ناوەکەی چەندین جار بەکاری بهێنیتەوە. دەتوانێت وەربگرێت و بگەڕێنێتەوە.
Why functions?بۆچی کردارەکان؟
Small pieces, one job eachپارچەی بچووک، هەریەکە بۆ یەک کار
A function is a named chunk of code that you can use again and again instead of writing it out many times. Functions also let you break a big problem into smaller pieces, each of which does one particular job — and each piece can be written and tested on its own. Planners call this decomposition.
پارچەیەکی ناونراوی کۆدە کە دەتوانیت چەندین جار بەکاری بهێنیتەوە لەبری ئەوەی چەندین جار بینووسیتەوە. هەروەها ڕێگەت پێدەدەن کێشەیەکی گەورە بکەیتە چەند پارچەیەکی بچووکتر کە هەریەکەیان کارێکی دیاریکراو دەکات — و هەر پارچەیەک دەتوانرێت بە تەنها بنووسرێت و تاقی بکرێتەوە. ئەمە پێی دەوترێت پارچەکردن.
Planning works the same way. In a flowchart, a step that is worked out somewhere else is drawn as a predefined process box (Flowchart symbols); in Python that step becomes a call to a function.
پلاندانانیش هەروایە. لە هەنگاوێک کە لە شوێنێکی تر ڕوون کراوەتەوە وەک سندوقی پرۆسەی ئامادە (predefined process) دەکێشرێت (هێماکانی هێڵکاریی ڕەوت)؛ لە Pythonـدا ئەو هەنگاوە دەبێتە بانگکردنی .
Why functions?بۆچی کردارەکان؟
One function, three sumsیەک کردار، سێ کۆ
Now the loop is written once, inside a function called sum_numbers. The two numbers that changed become its two parameters, start and stop. Each call passes different numbers.
ئێستا یەک جار نووسراوە، لەناو بە ناوی sum_numbers. ئەو دوو ژمارەیەی دەگۆڕان دەبنە دوو : start و stop. هەر بانگکردنێک ژمارەی جیاواز دەنێرێت.
def sum_numbers(start, stop):
total = 0
for i in range(start, stop): # stop is NOT included
total += i
return total
def main():
print("Sum from 1 to 10 is", sum_numbers(1, 11))
print("Sum from 20 to 37 is", sum_numbers(20, 38))
print("Sum from 35 to 49 is", sum_numbers(35, 50))
main()Sum from 1 to 10 is 55 Sum from 20 to 37 is 513 Sum from 35 to 49 is 630
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
The header:
def, the name, the parametersstartandstop, and a colon.:
def، ناوەکە،startوstopو دوو خاڵ.- Lineدێڕی 2-5
The body: the familiar loop.
return totalsends the result back.: هەمان کە دەیناسیت.
return totalئەنجامەکە دەگەڕێنێتەوە.- Lineدێڕی 8-11
main()callssum_numbersthree times with different arguments.main()سێ جارsum_numbersبانگ دەکات بە جیاواز.- Lineدێڕی 14
This line starts the program by calling
main().ئەم دێڕە بە بانگکردنی
main()دەست پێدەکات.
A function is like a tea-house orderکردار وەک داواکردنی چا لە چایخانەدا
In a tea house the tea maker knows one recipe: how to make a glass of tea. The recipe was learned once — that is the function's definition. Every time a customer orders, the tea maker follows the same steps — that is a call. The customer says how many sugar cubes they want — that is the argument. The waiter brings the glass back to the table — that is the return value.
لە چایخانەدا چایچی یەک ڕەچەتە دەزانێت: چۆن ئیستیکانێک چا دروست بکات. ڕەچەتەکە یەک جار فێر بووە — ئەمە . هەر جارێک موشتەرییەک داوای چا دەکات، چایچی هەمان هەنگاوەکان دەکات — ئەمە بانگکردنێکە. موشتەرییەکە دەڵێت چەند قەندی دەوێت — ئەمە . گارسۆنەکە ئیستیکانەکە دەگەڕێنێتەوە بۆ سەر مێزەکە — ئەمە .
Where the analogy stops workingسنووری ئەم نموونەیە
A real tea maker can prepare many glasses at once and may change the recipe on a whim. A Python function handles one call at a time — the caller waits until it is finished — and it always follows its code exactly: only the arguments can change the result.
چایچیی ڕاستەقینە دەتوانێت لە یەک کاتدا چەند ئیستیکانێک ئامادە بکات و لەوانەیە بە دڵی خۆی ڕەچەتەکە بگۆڕێت. Python لە هەر جارێکدا تەنها یەک بانگکردن ئەنجام دەدات — چاوەڕێ دەکات تا تەواو دەبێت — و هەمیشە ڕێک بەپێی کۆدەکەی دەڕوات: تەنها دەتوانن ئەنجامەکە بگۆڕن.
def make_tea(sugars):
"""Make one glass of tea with the given number of sugar cubes."""
return f"a glass of tea with {sugars} sugar cubes"
order1 = make_tea(2)
order2 = make_tea(0)
print(order1)
print(order2)a glass of tea with 2 sugar cubes a glass of tea with 0 sugar cubes
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-3
The recipe, written once.
sugarsis the parameter: a placeholder for the customer's wish.ڕەچەتەکە، یەک جار نووسراوە.
sugars: شوێنگرێک بۆ داوای موشتەرییەکە.- Lineدێڕی 6-7
Two orders = two calls, with the arguments 2 and 0.
دوو داواکاری = دوو بانگکردن، بە 2 و 0.
- Lineدێڕی 8-9
Each order brought back its own glass (string).
هەر داواکارییەک ئیستیکانی خۆی () گەڕاندەوە.
Your first functionیەکەم کرداری خۆت
The smallest useful function has no parameters and a one-line body. This example comes from the course's Python-and-Java report:
بچووکترین بەسوود هیچ نییە و جەستەکەی یەک دێڕە. ئەم نموونەیە لە ڕاپۆرتی «Python و Java»ـی کۆرسەکەوە هاتووە:
def func_name():
print("Hello World!")
func_name()Hello World!
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
defcreates a function namedfunc_name. The empty()means: no parameters.defبە ناویfunc_nameدروست دەکات.()ـی بەتاڵ واتە: هیچ نییە.- Lineدێڕی 2
The body. It must be indented (PEP 8 uses 4 spaces; this file uses 2, which Python also accepts).
. دەبێت هەبێت (PEP 8 چوار بەکار دەهێنێت؛ ئەم فایلە دوو بەکار دەهێنێت، کە Pythonـیش قبووڵی دەکات).
- Lineدێڕی 3
The call. Only now does the body run.
بانگکردنەکە. تەنها ئێستا جەستەکە جێبەجێ دەبێت.
func_name is only a placeholder. Give your functions names that say what they do, written in lowercase with underscores: say_hello, print_menu, sum_numbers.
func_name تەنها ناوێکی کاتییە. ناوێک بدە بە کە بڵێت چی دەکەن، بە پیتی بچووک و _: say_hello، print_menu، sum_numbers.
A def on its own prints nothing. It only creates the function and remembers it under its name. This program defines greet but never calls it, so greet's body never runs:
def بە تەنها هیچ چاپ ناکات. تەنها دروست دەکات و بە ناوەکەیەوە لە بیری دەهێڵێت. ئەم greet دەناسێنێت بەڵام هەرگیز بانگی ناکات، بۆیە جەستەی greet هەرگیز جێبەجێ نابێت:
def greet(person):
print("Hello,", person)
print("The program ends.")The program ends.
In Kurdish: writing and calling your own functions in Python.
بە کوردی: چۆن خۆت لە دەنووسیت و بانگیان دەکەیت.
Kurdish (Sorani), whole video (10:08): part 11 of MR. Ant's Python course.
ڤیدیۆیەکی کوردی (سۆرانی)، هەموو ڤیدیۆکە (10:08): بەشی 11 لە کۆرسی MR. Ant.
Your first functionیەکەم کرداری خۆت
Define first, then callسەرەتا بیناسێنە، پاشان بانگی بکە
Python runs a file from top to bottom, and def is itself a : the function exists only after Python has run its def line. Call it on an earlier line and the name is still unknown:
Python فایل لە سەرەوە بۆ خوارەوە جێبەجێ دەکات و def خۆی : تەنها دوای ئەوە هەیە کە Python دێڕی defـەکەی جێبەجێ کردبێت. ئەگەر لە دێڕێکی پێشتردا بانگی بکەیت، ناوەکە هێشتا نەناسراوە:
say_hello() # called too early!
def say_hello():
print("Hello World!")Traceback (most recent call last):
File "too_early.py", line 1, in <module>
say_hello() # called too early!
^^^^^^^^^
NameError: name 'say_hello' is not definedInside a function body it is different: there you may call a function that is defined further down the file, because the body runs only when the function is called — by then every def has run. That is why the slides can put main() first and call it on the very last line (see A main() function).
لەناو جیاوازە: لەوێ دەتوانیت بانگ بکەیت کە لە خوارتری فایلەکەدا ناسێنراوە، چونکە جەستەکە تەنها کاتی بانگکردنی جێبەجێ دەبێت — تا ئەو کاتە هەموو defـەکان جێبەجێ بوون. بۆیە سلایدەکان دەتوانن main() لە سەرەوە دابنێن و لە دوایین دێڕدا بانگی بکەن (بڕوانە کرداری main).
The parts of a functionبەشەکانی کردارێک
A has three parts: the function's name, its parameters and its body. In the definition you say what the function is to do. The general form is:
سێ بەشی هەیە: ناوی ، و جەستەکەی. لە ناساندنەکەدا دەڵێیت چی بکات. شێوە گشتییەکەی ئەمەیە:
def function_name(list of parameters):
# function body- The header is the first line. It begins with the
def, then the function's name and its parameters in parentheses, and it ends with a colon. - The variables in the header are the formal parameters, or simply parameters.
- Parameters are optional: a function may have none, like
def say_hello():. - The body is the indented block under the header: the statements that do the work.
- یەکەم دێڕە. بە
defدەست پێدەکات، پاشان ناوی و لەناو کەوانەدا دێت و بە دوو خاڵ (:) کۆتایی دێت. - بەو لە سەردێڕەکەدان دەگوترێت یان تەنها .
- ناچاری نین: دەکرێت هیچی نەبێت، وەک
def say_hello():. - ئەو بلۆکەیە کە لە ژێر سەردێڕەکەدا هەیە: کە کارەکە ئەنجام دەدەن.
The parts of a def line and body, and what happens step by step when a function is called and returns.
بەشەکانی (def) و ، هەروەها هەنگاو بە هەنگاو چی ڕوودەدات کاتێک بانگ دەکرێت و دەگەڕێتەوە.
Plays 0:19-4:55: function syntax, then how Python executes a call; stops before the namespaces chapter.
لە 0:19 تا 4:55 پەخش دەبێت: ، پاشان چۆن جێبەجێ دەکات؛ پێش بەشی namespaces ڕادەوەستێت.
The parts of a functionبەشەکانی کردارێک
Two kinds of functionsدوو جۆری کردار
Some functions compute a value and give it back: max(3, 4) gives 4, len("tea") gives 3, sum_numbers(1, 11) gives 55. Such a function is a . Other functions perform actions — such as printing — without returning a useful value: print() and say_hello() are examples. They are called . (Strictly speaking, in Python they return the special value None; the next lesson explains it.)
هەندێک دەژمێرن و دەیگەڕێننەوە: max(3, 4) ژمارە 4 دەدات، len("tea") ژمارە 3 و sum_numbers(1, 11) ژمارە 55. وا . تر کارێک ئەنجام دەدەن — وەک چاپکردن — بەبێ ئەوەی نرخێکی بەسوود بگەڕێننەوە: print() و say_hello() نموونەن. پێیان دەگوترێت . (بە وردی، لە Pythonـدا نرخی تایبەتی None دەگەڕێننەوە؛ وانەی داهاتوو ڕوونی دەکاتەوە.)
| Kindجۆر | Examplesنموونە | How you call itچۆن بانگی دەکەیت |
|---|---|---|
max(3, 4), len("tea"), sum_numbers(1, 11) | As a value: k = max(3, 4) or print(max(3, 4))وەک : k = max(3, 4) یان print(max(3, 4)) | |
print("Hi"), say_hello() | As a statement on its own line: say_hello()وەک لەسەر دێڕی خۆی: say_hello() |
Calling a functionبانگکردنی کردار
Calling (or invoking) a function runs the code in its body. A definition alone does nothing — to use a function you must call it. The code that calls a function is its .
بانگکردنی کۆدی جەستەکەی جێبەجێ دەکات. ناساندن بە تەنها هیچ ناکات — بۆ بەکارهێنانی دەبێت بانگی بکەیت. ئەو کۆدەی بانگ دەکات پێی دەگوترێت .
There are two ways to call a function, depending on whether it returns a value. If it returns a value, the call is usually treated as a value: store it in a variable, or pass it straight into another call.
دوو ڕێگە بۆ بانگکردنی هەیە، بەپێی ئەوەی دەگەڕێنێتەوە یان نا. ئەگەر بگەڕێنێتەوە، بانگکردنەکە زۆرجار وەک مامەڵەی لەگەڵ دەکرێت: لە هەڵیبگرە یان ڕاستەوخۆ بیدە بە بانگکردنێکی تر.
larger = max(3, 4) # the call is used as a value
print(larger)
print(max(3, 4)) # the value goes straight into print()4 4
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
The call
max(3, 4)becomes 4, which is stored inlarger.بانگکردنی
max(3, 4)دەبێتە 4، کە لەlargerـدا هەڵدەگیرێت.- Lineدێڕی 3
Here the value 4 goes straight into
print().لێرەدا نرخی 4 ڕاستەوخۆ دەچێتە ناو
print().
If a function does not return a value, the call must be a statement on its own line. print() is such a function: print("Programming is fun!") shows the text but gives nothing useful back. You can check this — store the "result" of print and print it:
ئەگەر نەگەڕێنێتەوە، دەبێت بانگکردنەکە بێت لەسەر دێڕی خۆی. print() وایە: print("Programming is fun!") دەقەکە پیشان دەدات بەڵام هیچ شتێکی بەسوود ناگەڕێنێتەوە. دەتوانیت ئەمە بپشکنیت — «ئەنجامی» print هەڵبگرە و چاپی بکە:
print give back?print چی دەگەڕێنێتەوە؟print_none.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەx = print("Programming is fun!")
print(x)Programming is fun! None
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
The text is printed.
xreceives whatprintreturns.دەقەکە چاپ دەکرێت.
xئەوە وەردەگرێت کەprintدەیگەڕێنێتەوە.- Lineدێڕی 2
xisNone: "no value".xبریتییە لەNone: «هیچ نرخ».
Example: the larger of two numbersنموونە: گەورەترینی دوو ژمارە
The slides define a function that returns the larger of two numbers. It compares num1 and num2, stores the larger one in result and returns result. We call it larger (the reason follows below).
سلایدەکان دەناسێنن کە گەورەترینی دوو ژمارە دەگەڕێنێتەوە. num1 و num2 بەراورد دەکات، گەورەترەکەیان لە resultـدا هەڵدەگرێت و result دەگەڕێنێتەوە. ئێمە ناوی دەنێین larger (هۆکارەکەی لە خوارەوەیە).
def larger(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
x = 3
y = 7
z = larger(x, y) # x and y are the arguments
print(z)7
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Header: the name
largerand the two parametersnum1andnum2.: ناوی
largerو دووnum1وnum2.- Lineدێڕی 2-5
The body decides which number is larger.
بڕیار دەدات کام ژمارە گەورەترە.
- Lineدێڕی 6
return resultends the function and sends the value back.return resultکۆتایی پێدێنێت و نرخەکە دەگەڕێنێتەوە.- Lineدێڕی 11
The call:
xandyare the arguments. Their values 3 and 7 are passed tonum1andnum2.بانگکردنەکە:
xوy. نرخەکانیان، 3 و 7، دەنێردرێن بۆnum1وnum2.
xandyin the call are the actual parameters, usually called .- A parameter is like a placeholder: when the function is invoked, a value is passed to it.
- A value-returning function needs a
returnstatement to give back its result. - The function ends as soon as a
returnstatement runs.
xوyلە بانگکردنەکەدا ، کە زۆرجار پێیان دەگوترێت .- وەک شوێنگرێک وایە: کاتێک بانگ دەکرێت، نرخێکی پێ دەدرێت.
- پێویستی بە ڕستەی
returnهەیە بۆ گەڕاندنەوەی ئەنجامەکەی. - هەر کە ڕستەیەکی
returnجێبەجێ بوو کۆتایی دێت.
Example: the larger of two numbersنموونە: گەورەترینی دوو ژمارە
Parameters and argumentsپارامیتەرەکان و ئارگیومێنتەکان
| Aspectلایەن | Parameter | Argument |
|---|---|---|
| Whereلە کوێ | In the header of the definitionلە سەردێڕی ناساندنەکەدا | In the callلە بانگکردنەکەدا |
| Exampleنموونە | num1, num2 in def larger(num1, num2): | x, y (or 3, 7) in larger(x, y) |
| Also calledناوی تری | formal parameter | actual parameter |
| What it isچییە | A name that waits for a valueناوێک کە چاوەڕێی نرخێک دەکات | The value that is sentئەو نرخەی دەنێردرێت |
Think of a form at the post office. The printed field "Name: ______" is the parameter. What you write into it — "Shilan" — is the argument. The same form is filled in with a different name by every customer.
فۆرمێک لە پۆستەخانەدا بهێنە بەرچاوت. خانە چاپکراوەکەی «ناو: ______» . ئەوەی تێیدا دەنووسیت — «Shilan» — . هەمان فۆرم هەر موشتەرییەک بە ناوێکی جیاواز پڕی دەکاتەوە.
Where the analogy stops workingسنووری ئەم نموونەیە
You may leave a field on a paper form empty. In Python every parameter without a default value must get an argument, or the call fails:
دەتوانیت خانەیەکی فۆرمی کاغەز بە بەتاڵی جێبهێڵیت. لە Pythonـدا هەر کە نەبێت دەبێت وەربگرێت، دەنا بانگکردنەکە شکست دەهێنێت:
def larger(num1, num2):
if num1 > num2:
return num1
return num2
print(larger(5))Traceback (most recent call last):
File "missing.py", line 7, in <module>
print(larger(5))
^^^^^^^^^
TypeError: larger() missing 1 required positional argument: 'num2'Default values, which let you leave out an argument, and keyword arguments, written as name=value, are taught in Positional, Keyword and Default Arguments.
ڕێگە دەدەن نەنووسیت. ئەمانە و (بە شێوەی name=value) لە ئارگیومێنتە شوێنییەکان، ئارگیومێنتە ناودارەکان و نرخە بنەڕەتییەکان فێر دەکرێن.
The difference between a parameter (the name in the definition) and an argument (the value given in the call).
جیاوازیی نێوان (ناوەکە لە ) و (ئەو لە دەدرێت).
Plays 2:25-4:47, "Parameters vs Arguments".
لە 2:25 تا 4:47 پەخش دەبێت، بەشی Parameters vs Arguments.
Tracing a program with a functionبەدواداچوونی بەرنامەیەک کە کرداری تێدایە
How does Python run a program that contains functions? Follow this one line by line. The line numbers matter: the below uses them.
Python چۆن جێبەجێ دەکات کە تێدایە؟ دێڕ بە دێڕ بەدوای ئەمەدا بڕۆ. ژمارەی دێڕەکان گرنگن: خوارەوە بەکاریان دەهێنێت.
larger)بەرنامەکەی سلایدەکان (ناوی کردارەکە گۆڕدراوە بۆ larger)larger_trace.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە# Return the larger of two numbers
def larger(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
def main():
i = 5
j = 2
k = larger(i, j) # Call the larger function
print("The larger number of", i, "and", j, "is", k)
main() # Call the main functionThe larger number of 5 and 2 is 5
| Stepهەنگاو | Lineدێڕ | What happensچی ڕوو دەدات | Variables now ئێستا |
|---|---|---|---|
| 1 | 16 | main() is called; control jumps to line 10.main() بانگ دەکرێت؛ ڕەوتەکە باز دەداتە دێڕی 10. | — |
| 2 | 11 | i = 5i = 5 | i = 5 |
| 3 | 12 | j = 2j = 2 | i = 5, j = 2 |
| 4 | 13 → 2 | larger(i, j) is invoked: 5 is passed to num1, 2 to num2.larger(i, j) بانگ دەکرێت: 5 دەدرێتە num1 و 2 دەدرێتە num2. | num1 = 5, num2 = 2 |
| 5 | 3–4 | is true, so result = num1. ڕاستە، بۆیە result = num1. | result = 5 |
| 6 | 8 | return result ends larger and sends 5 back to line 13.return result کۆتایی بە larger دێنێت و 5 دەگەڕێنێتەوە بۆ دێڕی 13. | — |
| 7 | 13 | k = 5k = 5 | i = 5, j = 2, k = 5 |
| 8 | 14 | The sentence is printed.ڕستەکە چاپ دەکرێت. | — |
Tracing a program with a functionبەدواداچوونی بەرنامەیەک کە کرداری تێدایە
Where does control go?ڕەوتی جێبەجێکردن بۆ کوێ دەچێت؟
When a function is invoked, control is transferred to the function: Python leaves the line with the call and runs the function's body. When the function is finished, control returns to where it was called, and the call is replaced by the return value.
کاتێک بانگ دەکرێت، دەگوازرێتەوە بۆ : Python دێڕی بانگکردنەکە جێدەهێڵێت و جێبەجێ دەکات. کاتێک تەواو دەبێت، دەگەڕێتەوە بۆ ئەو شوێنەی لێی بانگ کرا و بانگکردنەکە بە دەگۆڕدرێت.


larger(); the return value comes back to the call.بانگکردنەکە باز دەداتە ناو larger()؛ دەگەڕێتەوە بۆ شوێنی بانگکردنەکە.CêITNotice in the animation that num1, num2 and result exist only during the call. When larger returns, they are gone; main keeps only the returned value in k. Variable Scope explains this in detail.
لە ئەنیمەیشنەکەدا سەرنج بدە کە num1، num2 و result تەنها لە کاتی بانگکردنەکەدا هەن. کاتێک larger دەگەڕێتەوە، نامێنن؛ main تەنها لە kـدا دەپارێزێت. مەودای گۆڕاوەکان ئەمە بە وردی ڕوون دەکاتەوە.
The function signatureواژووی کردار
The is the part of the header that tells you how to call the function: its name, its parameters and — where the language writes them — the types of the parameters and of the result. You can use a function from its signature alone, without reading its body.
ئەو بەشەی سەردێڕەکەیە کە پێت دەڵێت چۆن بانگ بکەیت: ناوەکەی، و — لەو زمانانەی دەینووسن — جۆری و جۆری ئەنجامەکە. دەتوانیت تەنها بە واژووەکەی بەکار بهێنیت، بەبێ خوێندنەوەی جەستەکەی.
def larger(num1: int, num2: int) -> int:
if num1 > num2:
return num1
return num2
print(larger(5, 2))
print(larger("7", "10")) # strings: Python does not check the hints5 7
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Read it as:
largertakes two ints and returns an int.وا بیخوێنەوە:
largerدوو int وەردەگرێت و int دەگەڕێنێتەوە.- Lineدێڕی 8
Python does not check hints: two strings work too.
"7" > "10"is true because strings are compared character by character, and "7" comes after "1".Python ناپشکنێت: تەنانەت دوو کار دەکەن.
"7" > "10"ڕاستە، چونکە بە بەراورد دەکرێن و «7» دوای «1» دێت.
So hints are notes for people and for tools: a good editor uses them to warn you before you run the program.
کەواتە تێبینین بۆ مرۆڤ و بۆ ئامرازەکان: دەستکاریکەرێکی باش بەکاریان دەهێنێت بۆ ئاگادارکردنەوەت پێش جێبەجێکردنی .
The function signatureواژووی کردار
Signatures in other languagesواژووی کردار لە زمانەکانی تردا
Every language writes a signature in its own way, but it always answers the same question: how do I call this function? Here is larger in four styles:
هەموو زمانێک بە شێوەی خۆی دەنووسێت، بەڵام هەمیشە وەڵامی هەمان پرسیار دەداتەوە: چۆن ئەم بانگ بکەم؟ ئەمە largerـە بە چوار شێوە:
| Languageزمان | Signature of largerواژووی larger |
|---|---|
| Python | def larger(num1, num2): |
| Python with type hintsPython لەگەڵ | def larger(num1: int, num2: int) -> int: |
| Java | static int larger(int num1, int num2) |
| Go | func larger(num1 int, num2 int) int |
In Java every function lives inside a class and is called a method; the types are compulsory and the compiler checks them. Python Next to Java compares the two languages.
لە Javaـدا هەموو لەناو و پێی دەگوترێت ؛ جۆرەکان ناچارین و دەیانپشکنێت. Python لە تەنیشت Java ئەم دوو زمانە بەراورد دەکات.
Describing a function: docstringsوەسفکردنی کردارێک: زنجیرەنووسەی بەڵگەنامە
A is a string in triple quotes written as the first line of the body. It says what the function does. Unlike a # , Python keeps it: help() and editors show it to anyone who uses your function.
لەناو سێ کۆتەیشندا کە وەک یەکەم دێڕی جەستە دەنووسرێت. دەڵێت چی دەکات. بە پێچەوانەی #، Python هەڵیدەگرێت: help() و دەستکاریکەرەکان پیشانی هەر کەسێک دەدەن کە بەکار دەهێنێت.
def larger(num1, num2):
"""Return the larger of two numbers."""
if num1 > num2:
return num1
return num2
print(larger.__doc__)
help(larger)Return the larger of two numbers.
Help on function larger in module __main__:
larger(num1, num2)
Return the larger of two numbers.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
One short sentence that starts with a capital letter and ends with a full stop.
یەک ڕستەی کورت کە بە پیتی گەورە دەست پێدەکات و بە خاڵ کۆتایی دێت.
- Lineدێڕی 8
The docstring is stored in
__doc__.لە
__doc__ـدا هەڵدەگیرێت.- Lineدێڕی 9
help()shows the signature and the docstring.help()واژووەکە و پیشان دەدات.
Built-in functions and your ownکردارە ئامادەکان و کردارەکانی خۆت
Python comes with many that are ready to use: print(), input(), len(), int(), max(), min(), sum(), range() and more. The functions you write yourself with def are . Both are called in exactly the same way.
Python لەگەڵ زۆر دێت کە دەتوانیت یەکسەر بەکاریان بهێنیت: print()، input()، len()، int()، max()، min()، sum()، range() و هی تر. ئەو خۆت بە def دەیاننووسیت . هەردووکیان ڕێک بە هەمان شێوە بانگ دەکرێن.
Built-in names are not reserved, so you can reuse them — and that is a trap. Once a variable is called sum, the name no longer means the function:
ناوە ئامادەکان پارێزراو نین، بۆیە دەتوانیت دووبارە بەکاریان بهێنیتەوە — و ئەمە تەڵەیەکە. هەر کە ناوی sum بوو، ئیتر ئەو ناوە مانای نادات:
sum hides sum()گۆڕاوێک بە ناوی sum sum() دەشارێتەوەsum_hidden.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەsum = 0
for i in range(1, 4):
sum += i
print(sum)
print(sum([10, 20, 30])) # sum is now the number 6, not the function6
Traceback (most recent call last):
File "sum_hidden.py", line 5, in <module>
print(sum([10, 20, 30])) # sum is now the number 6, not the function
^^^^^^^^^^^^^^^^^
TypeError: 'int' object is not callableBuilt-in functions and your ownکردارە ئامادەکان و کردارەکانی خۆت
Python's built-in toolboxسندوقی ئامرازی کردارە ئامادەکان
You do not have to learn all the built-in functions at once. It helps to know them by the job they do:
پێویست ناکات هەموو پێکەوە فێر ببیت. باشە بەپێی ئەو کارەی دەیکەن بیانناسیت:
| Jobکار | Built-in functions | Taught inلە کوێ فێر دەبیت |
|---|---|---|
| Input and output و | input(), print() | Input and Outputنێوخستە و دەرخستە |
| Converting values | int(), float(), str(), bool() | Variables and Typesگۆڕاوەکان و جۆرەکان |
| Making collectionsدروستکردنی کۆکراوە | list(), tuple(), set(), dict() | Lists, Tuples, Sets and Dictionariesلیستەکان، تاپڵەکان، کۆمەڵەکان و فەرهەنگەکان |
| Characters and their codes و کۆدەکانیان | chr(), ord() | Stringsوانەی زنجیرەنووسەکان |
| Numbersژمارەکان | abs(), round(), divmod(), pow() | Operators and the example belowکارپێکەرەکان و نموونەکەی خوارەوە |
| Many values at onceچەند نرخێک پێکەوە | len(), max(), min(), sum(), sorted() | List functionsکردارەکانی لیست |
| Othersهی تر | range(), type(), help() | range, types, docstringsrange، جۆرەکان، زنجیرەنووسەی بەڵگەنامە |
print(abs(-7), abs(3.5))
print(pow(2, 10))
print(pow(2, 10, 1000)) # (2 ** 10) % 1000
print(divmod(17, 5))
print(round(3.14159, 2))
print(len("Erbil"), max(4, 9, 2), sum([10, 20, 30]))7 3.5 1024 24 (3, 2) 3.14 5 9 60
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
abs()gives the distance from 0: the number without its minus sign.abs()دووری لە 0 دەدات: ژمارەکە بەبێ نیشانەی سالب.- Lineدێڕی 2-3
pow(x, y)isx ** y. With a third argument,pow(x, y, m)gives the remainder ofx ** ydivided bym— fast even for huge powers.pow(x, y)هەمانx ** yـە. بە سێیەم،pow(x, y, m)x ** yدابەش بەmدەدات — تەنانەت بۆ زۆر گەورەش خێرایە.- Lineدێڕی 4
divmod(17, 5)gives the whole-number quotient and the remainder together.divmod(17, 5)ئەنجامی دابەشکردنی تەواو و پێکەوە دەدات.
A main() functionکرداری main
The slides put the main steps of a program into a function called main() and call it on the last line of the file. Python does not need this (Java does: every Java program starts in main), but it is a tidy habit. main can stand at the top of the file, where a reader looks first, and it may call helper functions that are defined below it — when main() finally runs on the last line, every def has already been executed.
سلایدەکان هەنگاوە سەرەکییەکانی دەخەنە ناو بە ناوی main() و لە دوایین دێڕی فایلەکەدا بانگی دەکەن. Python پێویستی بەمە نییە (Java پێویستی پێیەتی: هەموو Java لە mainـەوە دەست پێدەکات)، بەڵام نەریتێکی ڕێکە. main دەتوانێت لە سەرەوەی فایلەکەدا بێت، کە خوێنەر سەرەتا سەیری دەکات. هەروەها دەتوانێت یاریدەدەر بانگ بکات کە لە خوارییەوە ناسێنراون — کاتێک main() لە کۆتاییدا لە دوایین دێڕدا جێبەجێ دەبێت، هەموو defـەکان پێشتر جێبەجێ بوون.
main first, helpers below, one call at the endسەرەتا main، یاریدەدەرەکان لە خوارەوە، یەک بانگکردن لە کۆتاییداmain_first.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەdef main():
name = "Shilan"
greet(name)
greet("Karwan")
def greet(person):
print("Hello,", person)
main()Hello, Shilan Hello, Karwan
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-4
mainusesgreet, which is defined later. That is fine: this body runs only at line 11.maingreetبەکار دەهێنێت، کە دواتر ناسێنراوە. ئاساییە: ئەم جەستەیە تەنها لە دێڕی 11دا جێبەجێ دەبێت.- Lineدێڕی 11
The only top-level call: it starts the program.
تاکە بانگکردنی ئاستی سەرەکی: دەست پێدەکات.
Lab: a pattern functionتاقیگە: کردارێکی شێوەکێشان
Write a function def pattern(i1, i2) that prints a number pattern, then call it with (1, 6), (10, 20) and (3, 25). The rule: the first row counts down from i2 - i1 to 1, each following row starts one lower, and the last row is just 1. Print an empty line after each pattern. pattern(1, 6) must give:
def pattern(i1, i2) بنووسە کە شێوەیەکی ژمارەیی چاپ بکات، پاشان بە (1, 6)، (10, 20) و (3, 25) بانگی بکە. یاساکە: یەکەم لە i2 - i1ـەوە بەرەو 1 دەژمێرێت، هەر دواتر یەکێک خوارتر دەست پێدەکات و دوایین تەنها 1ـە. دوای هەر شێوەیەک دێڕێکی بەتاڵ چاپ بکە. pattern(1, 6) دەبێت ئەمە بدات:
pattern(1, 6)pattern(1, 6)5 4 3 2 1 4 3 2 1 3 2 1 2 1 1
Hintئاماژە
Use the nested loops from the previous lesson inside the function. The outer loop is range(i2 - i1, 0, -1).
وانەی پێشوو لەناو بەکار بهێنە. range(i2 - i1, 0, -1)ـە.
Show answerوەڵامەکە پیشان بدە
def pattern(i1, i2):
# The first row starts at i2 - i1 and counts down to 1.
for row in range(i2 - i1, 0, -1):
for n in range(row, 0, -1):
print(n, end=" ")
print()
print() # a blank line after each pattern
pattern(1, 6)
pattern(10, 20)
pattern(3, 25)5 4 3 2 1 4 3 2 1 3 2 1 2 1 1 10 9 8 7 6 5 4 3 2 1 9 8 7 6 5 4 3 2 1 8 7 6 5 4 3 2 1 7 6 5 4 3 2 1 6 5 4 3 2 1 5 4 3 2 1 4 3 2 1 3 2 1 2 1 1 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 14 13 12 11 10 9 8 7 6 5 4 3 2 1 13 12 11 10 9 8 7 6 5 4 3 2 1 12 11 10 9 8 7 6 5 4 3 2 1 11 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 9 8 7 6 5 4 3 2 1 8 7 6 5 4 3 2 1 7 6 5 4 3 2 1 6 5 4 3 2 1 5 4 3 2 1 4 3 2 1 3 2 1 2 1 1
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Two parameters: the function works for any pair of numbers.
دوو : بۆ هەر جووتە ژمارەیەک کار دەکات.
- Lineدێڕی 3-6
A nested loop: rows from
i2 - i1down to 1; in each row, numbers fromrowdown to 1.: لە
i2 - i1ـەوە بۆ 1؛ لە هەر ژمارەکان لەrowـەوە بۆ 1.- Lineدێڕی 10-12
Three calls, three patterns: the loops are written once.
سێ بانگکردن، سێ شێوە: یەک جار نووسراون.
Common mistakesهەڵە باوەکان
| Mistakeهەڵە | What happensچی ڕوو دەدات | Fixچارەسەر |
|---|---|---|
Writing the name without (): say_helloنووسینی ناوەکە بەبێ (): say_hello | Nothing — the function is not calledهیچ — بانگ ناکرێت | say_hello()say_hello() |
Calling a function above its defبانگکردنی لە سەرووی defـەکەیەوە | NameError: name '…' is not definedNameError: name '…' is not defined | Put the def first, or call from main() at the end.سەرەتا def دابنێ، یان لە کۆتاییدا لە main()ـەوە بانگی بکە. |
| No colon after the headerنەبوونی دوو خاڵ دوای سەردێڕەکە | SyntaxError: expected ':'SyntaxError: expected ':' | def say_hello():def say_hello(): |
| Body not indentedجەستە نییە | IndentationError: expected an indented block after function definitionIndentationError: expected an indented block after function definition | Indent the body 4 spaces.جەستەکە بە 4 بەرەو ناوەوە ببە. |
| Too few or too many arguments کەمتر یان زیاتر | TypeError: … missing 1 required positional argumentTypeError: … missing 1 required positional argument | Give one argument for each parameter.بۆ هەر یەک بدە. |
Naming a function or variable max, sum, print …ناونانی یان بە max، sum، print … | The built-in is hidden; later calls fail دەشاردرێتەوە؛ بانگکردنەکانی دواتر شکست دەهێنن | larger, total, show_menu …larger، total، show_menu … |
| Defining a function but never calling itناساندنی بەبێ ئەوەی هەرگیز بانگ بکرێت | The program seems to do nothingوا دەردەکەوێت هیچ ناکات | Add the call.بانگکردنەکە زیاد بکە. |
| Printing inside a function when the caller needs the valueچاپکردن لەناو کاتێک پێویستی بە نرخەکەیە | The caller gets None None وەردەگرێت | Use return — see Return Values and None.return بەکار بهێنە — بڕوانە نرخە گەڕاوەکان و None. |
def say_hello():
print("Hello World!")
say_hello # no ( ): nothing happens
print("Done")Done
Hello World! never appears: line 5 only names the function.
Hello World! هەرگیز دەرناکەوێت: دێڕی 5 تەنها ناوی دەبات.
Exercisesڕاهێنانەکان
Write a value-returning function square(n) that returns n * n. Print square(4) and square(2) + square(3).
square(n) بنووسە کە n * n بگەڕێنێتەوە. square(4) و square(2) + square(3) چاپ بکە.
Show answerوەڵامەکە پیشان بدە
def square(n):
return n * n
print(square(4))
print(square(2) + square(3))16 13
Because square returns its result, two calls can be added together: .
چونکە square ئەنجامەکەی دەگەڕێنێتەوە، دەتوانرێت دوو بانگکردن کۆ بکرێنەوە: .
Write a function draw_line(width) without a return value that prints width dashes. Use it to print the word Menu between two lines of 10 dashes.
draw_line(width) بنووسە کە ژمارە width هێڵی کورت چاپ بکات. بەکاری بهێنە بۆ ئەوەی وشەی Menu لە نێوان دوو هێڵدا چاپ بکەیت کە هەریەکەیان 10 هێڵی کورت بێت.
Show answerوەڵامەکە پیشان بدە
def draw_line(width):
print("-" * width)
draw_line(10)
print("Menu")
draw_line(10)---------- Menu ----------
Without running it, write down what this program prints. Then explain why double is called twice.
بەبێ جێبەجێکردنی، بنووسە ئەم چی چاپ دەکات. پاشان ڕوونی بکەرەوە بۆچی double دوو جار بانگ دەکرێت.
def double(n):
print("double got", n)
return n * 2
def main():
a = double(3)
b = double(a)
print(a, b)
main()Show answerوەڵامەکە پیشان بدە
double got 3 double got 6 6 12
main calls double(3), which prints its line and returns 6 into a. Then double(a) is double(6): it prints and returns 12 into b.
main double(3) بانگ دەکات، کە دێڕەکەی خۆی چاپ دەکات و 6 دەگەڕێنێتەوە بۆ a. پاشان double(a) واتە double(6): چاپ دەکات و 12 دەگەڕێنێتەوە بۆ b.
Turn the star triangle from Nested Loops into a function triangle(rows). Call it with 3 and then with 2, with a line --- between them.
سێگۆشەی ئەستێرەکان لە خولە ناوەکییەکان بکە بە بە ناوی triangle(rows). بە 3 و پاشان بە 2 بانگی بکە، لەگەڵ دێڕی --- لە نێوانیاندا.
Show answerوەڵامەکە پیشان بدە
def triangle(rows):
for i in range(1, rows + 1):
for j in range(i):
print("*", end=" ")
print()
triangle(3)
print("---")
triangle(2)* * * * * * --- * * *
Challenges: functions in bigger programsڕاهێنانی قورستر: کردارەکان لە بەرنامەکانی گەورەتردا
In the Fibonacci sequence each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13 … Write a function fibonacci(n) without a return value that prints the first n numbers on one line. Call it with 10 and with 3.
لە زنجیرەی فیبۆناچیدا هەر ژمارەیەک کۆی ئەو دوو ژمارەیەیە کە پێش خۆی دێن: 0، 1، 1، 2، 3، 5، 8، 13 … بە ناوی fibonacci(n) بنووسە کە یەکەم n ژمارە لەسەر یەک دێڕ چاپ بکات. بە 10 و بە 3 بانگی بکە.
Hintئاماژە
Keep the last two numbers in two variables, a and b. In each round print a, then move both one step on: the new a is b, and the new b is a + b.
دوو ژمارەی کۆتایی لە دوو هەڵبگرە، a و b. لە هەر جارێکدا a چاپ بکە، پاشان هەردووکیان یەک هەنگاو ببە پێشەوە: aـی نوێ bـە و bـی نوێ a + bـە.
Show answerوەڵامەکە پیشان بدە
def fibonacci(n):
"""Print the first n numbers of the Fibonacci sequence."""
a = 0
b = 1
for i in range(n):
print(a, end=" ")
following = a + b # the number after b
a = b
b = following
print()
fibonacci(10)
fibonacci(3)0 1 1 2 3 5 8 13 21 34 0 1 1
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 7-9
Save
a + bfirst: aftera = bthe oldawould be gone.سەرەتا
a + bهەڵبگرە: دوایa = bنرخی کۆنیaنامێنێت.
Python can swap the values in one line, a, b = b, a + b — see packing and unpacking. A recursive version is possible too, but it is very slow for big n: see Recursion.
Python دەتوانێت لە یەک دێڕدا نرخەکان بگۆڕێتەوە، a, b = b, a + b — بڕوانە پێچانەوە و کردنەوە. هەروەها دەکرێت بە بنووسرێت، بەڵام بۆ nـی گەورە زۆر هێواشە: بڕوانە خۆبانگکردنەوە.
Write check_login(username, password), which returns True only for the right pair, and login(), which asks for both at most three times. After three wrong tries it prints that the account is blocked.
check_login(username, password) بنووسە کە تەنها بۆ جووتە دروستەکە True بگەڕێنێتەوە و login() کە زۆرترین سێ جار داوای هەردووکیان بکات. دوای سێ هەوڵی هەڵە چاپ دەکات کە داخراوە.
Hintئاماژە
Loop for attempt in range(1, 4):. A return inside the loop ends login() as soon as the user gets in.
for attempt in range(1, 4):ـە. returnـێک لەناو هەر کە چووە ژوورەوە login() کۆتایی پێدێنێت.
Show answerوەڵامەکە پیشان بدە
def check_login(username, password):
"""Return True if both the username and the password are right."""
return username == "dilan" and password == "chai-2026"
def login():
for attempt in range(1, 4):
username = input("Username: ")
password = input("Password: ")
if check_login(username, password):
print("Welcome,", username)
return True
print("Wrong username or password. Tries left:", 3 - attempt)
print("Account blocked after 3 wrong tries.")
return False
login()Username: dilan Password: chai Wrong username or password. Tries left: 2 Username: dilan Password: Chai-2026 Wrong username or password. Tries left: 1 Username: dilan Password: chai-2026 Welcome, dilan
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-3
One job: compare. It returns a boolean, so it can stand in an
if.یەک کار: بەراوردکردن. دەگەڕێنێتەوە، بۆیە دەتوانێت لەناو
ifـدا بێت.- Lineدێڕی 7-13
Three rounds at most;
return Trueleaves early on success.زۆرترین سێ جار؛
return Trueلە کاتی سەرکەوتندا زوو دەردەچێت.- Lineدێڕی 14-15
Reached only after three failures.
تەنها دوای سێ شکست دەگاتە ئێرە.
Challenges: functions in bigger programsڕاهێنانی قورستر: کردارەکان لە بەرنامەکانی گەورەتردا
Challenge: a small bank accountڕاهێنانی قورستر: هەژمارێکی بانکیی بچووک
An account starts with 50,000 dinars and must always keep at least 10,000. Write deposit(balance, amount) and withdraw(balance, amount), which return the new balance; withdraw refuses if too little would be left. Then write a main() with a menu: 1 deposit, 2 withdraw, 3 show the balance, 4 quit.
هەژمارێک بە 50٬000 دینار دەست پێدەکات و دەبێت هەمیشە لانیکەم 10٬000ی تێدا بمێنێتەوە. deposit(balance, amount) و withdraw(balance, amount) بنووسە کە بڕە نوێیەکەی پارە بگەڕێننەوە؛ withdraw ڕەتی دەکاتەوە ئەگەر بڕێکی زۆر کەم بمێنێتەوە. پاشان main()ـێک بنووسە لەگەڵ : 1 دانانی پارە، 2 ڕاکێشانی پارە، 3 پیشاندانی بڕی پارە، 4 دەرچوون.
Hintئاماژە
main() keeps the balance in a variable and replaces it with what each function returns: balance = deposit(balance, amount).
main() بڕی پارە لە هەڵدەگرێت و بەو نرخە دەیگۆڕێت کە هەر دەیگەڕێنێتەوە: balance = deposit(balance, amount).
Show answerوەڵامەکە پیشان بدە
MINIMUM = 10000 # every account must keep at least 10,000 dinars
def deposit(balance, amount):
"""Return the new balance after putting money in."""
return balance + amount
def withdraw(balance, amount):
"""Return the new balance, or the old one if too little would be left."""
if balance - amount < MINIMUM:
print("Refused: at least", MINIMUM, "dinars must stay in the account.")
return balance
return balance - amount
def main():
balance = 50000
choice = ""
while choice != "4":
print("1. Deposit 2. Withdraw 3. Balance 4. Quit")
choice = input("Choose: ")
if choice == "1":
balance = deposit(balance, int(input("Amount: ")))
elif choice == "2":
balance = withdraw(balance, int(input("Amount: ")))
elif choice == "3":
print("Balance:", balance, "dinars")
print("Goodbye!")
main()1. Deposit 2. Withdraw 3. Balance 4. Quit Choose: 2 Amount: 45000 Refused: at least 10000 dinars must stay in the account. 1. Deposit 2. Withdraw 3. Balance 4. Quit Choose: 1 Amount: 25000 1. Deposit 2. Withdraw 3. Balance 4. Quit Choose: 2 Amount: 45000 1. Deposit 2. Withdraw 3. Balance 4. Quit Choose: 3 Balance: 30000 dinars 1. Deposit 2. Withdraw 3. Balance 4. Quit Choose: 4 Goodbye!
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
A name in capitals marks a value that never changes (PEP 8 style for constants).
ناوێک بە پیتی گەورە نیشانەی نرخێکە کە هەرگیز ناگۆڕێت (شێوازی PEP 8 بۆ ).
- Lineدێڕی 9-14
An early
returnfor the refused case, then the normal case.returnـێکی زوو بۆ حاڵەتی ڕەتکردنەوە، پاشان حاڵەتە ئاساییەکە.
Ideas to grow it later: several accounts kept in a dictionary, or a savings option that uses the interest function from Return Values.
بیرۆکە بۆ گەورەکردنی دواتر: چەند هەژمارێک لە فەرهەنگێکدا، یان بژاردەیەکی پاشەکەوت کە قازانجی ساڵانە لە نرخە گەڕاوەکان بەکار دەهێنێت.
Summaryپوختە
- A function is a named block of code: write it once, call it many times. Functions make code reusable and split a big problem into small jobs.
- A definition has a header —
def, the name, the parameters in( )and a colon — and an indented body. defonly creates the function. A call runs it; the code that calls is the caller.- Parameters are the names in the header; arguments are the values in the call.
- A value-returning function's call is used as a value; a function without a return value is called as a statement.
- A call moves control into the function;
returnbrings it back with the result. - Name functions in lowercase with underscores, describe them with a docstring, and never reuse built-in names such as
maxorsum.
- بلۆکێکی ناونراوی کۆدە: یەک جار بینووسە و چەندین جار بانگی بکە. کۆد دووبارە بەکارهێنراو دەکەن و کێشەیەکی گەورە دەکەنە چەند کارێکی بچووک.
- ناساندن دوو بەشی هەیە: —
def، ناو، لەناو( )و دوو خاڵ — و جەستەیەک کە هەیە. defتەنها دروست دەکات. بانگکردن جێبەجێی دەکات؛ ئەو کۆدەی بانگ دەکات .- ئەو ناوانەن کە لە سەردێڕەکەدان؛ ئەو نرخانەن کە لە بانگکردنەکەدان.
- بانگکردنی وەک بەکار دێت؛ وەک بانگ دەکرێت.
- بانگکردن دەباتە ناو ؛
returnلەگەڵ ئەنجامەکەدا دەیگەڕێنێتەوە. - ناوی بە پیتی بچووک و
_بنووسە، بە وەسفیان بکە و هەرگیز ناوە ئامادەکانی وەکmaxیانsumدووبارە بەکار مەهێنەوە.
What is the difference between a parameter and an argument?جیاوازیی نێوان پارامیتەر و ئارگیومێنت چییە؟
A parameter is a name in the function header; an argument is the actual value passed in a call.
ناوێکە لە سەردێڕی ؛ ئەو نرخە ڕاستەقینەیەیە کە لە بانگکردنێکدا دەنێردرێت.
What happens when Python reaches return?کاتێک Python دەگاتە return چی ڕوو دەدات؟
The function ends at once and the value goes back to the place of the call.
یەکسەر کۆتایی دێت و نرخەکە دەگەڕێتەوە بۆ شوێنی بانگکردنەکە.
Why should you not name a function max?بۆچی نابێت ناوی کردارێک بنێیت max؟
It hides Python's built-in max() for the rest of the file.
max()ـی ئامادەی Python بۆ باقیی فایلەکە دەشارێتەوە.
The rest of this chapter
باقیی ئەم بەشە
- Functions with and without return values — Return Values and None
- Positional and keyword arguments, and default arguments — Positional, Keyword and Default Arguments
- The scope of variables — Variable Scope
- Modularizing code — Modules and import
- بە و بەبێ ئەو — نرخە گەڕاوەکان و None
- ، و — ئارگیومێنتە شوێنییەکان، ئارگیومێنتە ناودارەکان و نرخە بنەڕەتییەکان
- — مەودای گۆڕاوەکان
- دابەشکردنی کۆد بۆ — مۆدیوڵەکان و import
Next: Return Values and None — what return can give back, and what happens when it is missing.
دواتر: نرخە گەڕاوەکان و None — return چی دەتوانێت بگەڕێنێتەوە و کاتێک نەبێت چی ڕوو دەدات.
Videoڤیدیۆ
Watch a videoسەیری ڤیدیۆیەک بکە
A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
Defining a function with def, calling it, passing arguments to parameters, and getting a value back with return.
بە def و ، ناردنی بۆ و وەرگرتنەوەی بە return.
Whole video (10:38). Chapters: 0:00 functions, 1:49 arguments, 4:28 exercise, 6:12 return, 8:27 exercise.
هەموو ڤیدیۆکە (10:38). بەشەکان: 0:00 ، 1:49 ، 4:28 ڕاهێنان، 6:12 return، 8:27 ڕاهێنان.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Return Values and Noneنرخە گەڕاوەکان و None
Related lecturesوانە پەیوەندیدارەکان
- Return Values and Noneنرخە گەڕاوەکان و None
- Positional, Keyword and Default Argumentsئارگیومێنتە شوێنییەکان، ئارگیومێنتە ناودارەکان و نرخە بنەڕەتییەکان
- Variable Scope: Local and Globalمەودای گۆڕاوەکان: ناوخۆیی و گشتی
- Modules and importمۆدیوڵەکان و import
- Algorithms, Pseudocode and Flowchartsئەلگۆریزمەکان، نیمچەکۆد و هێڵکارییەکانی ڕەوت
- Python Next to JavaPython لە تەنیشت Javaـەوە
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- Python tutorial 4.8–4.9: Defining functions, documentation strings, function annotations
- Python glossary: argument, parameter, function, docstring
- Python language reference 7.6: The return statement
- Harvard CS50P, lecture 0 notes: Def, Returning Values, main
- PEP 8 — Style Guide for Python Code (function names, blank lines)
- Liang, Introduction to Programming Using Python — table of contents (chapter 6, Functions)
- Python documentation: Built-in Functions (abs, divmod, pow with a modulus, round)
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.