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.

28 min read27 خولەک خوێندنەوە · 27 stepsهەنگاو

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

  • Explain why functions make programs shorter, clearer and easier to fix.
  • Define a function with def and 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⁩ بدۆزەوە. بەبێ لەوانەیە هەمان سێ جار بنووسیت:

Three almost identical blocksسێ بلۆکی نزیکەی وەک یەکthree_sums.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
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)
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.

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

Definitionپێناسە

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 .

بلۆکێکی ناونراوی کۆدە کە کارێکی دیاریکراو ئەنجام دەدات و دەتوانیت بە بانگکردنی ناوەکەی چەندین جار بەکاری بهێنیتەوە. دەتوانێت وەربگرێت و بگەڕێنێتەوە.

Quick checkپشکنینی خێراIn three_sums.py, what is different between the three loops?لە three_sums.pyـدا، چی لە نێوان سێ جیاوازە؟

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ـدا ئەو هەنگاوە دەبێتە بانگکردنی .

Quick checkپشکنینی خێراWhich of these is a good reason to split a program into functions?کام لەمانە هۆیەکی باشە بۆ دابەشکردنی بۆ چەند ؟

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. هەر بانگکردنێک ژمارەی جیاواز دەنێرێت.

Write the loop once, use it three timesخولەکە یەک جار بنووسە و سێ جار بەکاری بهێنەsum_numbers.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
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()
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

The header: def, the name, the parameters start and stop, and a colon.

: def، ناوەکە، start و stop و دوو خاڵ.

Lineدێڕی 2-5

The body: the familiar loop. return total sends the result back.

: هەمان کە دەیناسیت. return total ئەنجامەکە دەگەڕێنێتەوە.

Lineدێڕی 8-11

main() calls sum_numbers three times with different arguments.

main() سێ جار sum_numbers بانگ دەکات بە جیاواز.

Lineدێڕی 14

This line starts the program by calling main().

ئەم دێڕە بە بانگکردنی main() دەست پێدەکات.

Quick checkپشکنینی خێراWhat does sum_numbers(1, 4) return?sum_numbers(1, 4) چی دەگەڕێنێتەوە؟

A function is like a tea-house orderکردار وەک داواکردنی چا لە چایخانەدا

The tea maker's recipeڕەچەتەکەی چایچی

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 لە هەر جارێکدا تەنها یەک بانگکردن ئەنجام دەدات — چاوەڕێ دەکات تا تەواو دەبێت — و هەمیشە ڕێک بەپێی کۆدەکەی دەڕوات: تەنها دەتوانن ئەنجامەکە بگۆڕن.

The recipe in Pythonڕەچەتەکە بە Pythontea_house.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
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)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-3

The recipe, written once. sugars is 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).

هەر داواکارییەک ئیستیکانی خۆی () گەڕاندەوە.

Quick checkپشکنینی خێراIn the tea-house picture, what plays the part of the argument?لە وێنەی چایخانەکەدا، چی ڕۆڵی دەگێڕێت؟

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»ـی کۆرسەکەوە هاتووە:

Define a function, then call itکردارێک بناسێنە، پاشان بانگی بکەhello.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def func_name():
  print("Hello World!")
func_name()
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

def creates a function named func_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 هەرگیز جێبەجێ نابێت:

never_called.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def greet(person):
    print("Hello,", person)

print("The program ends.")
Quick checkپشکنینی خێراWhat does hello.py print if you delete its last line, func_name()?ئەگەر دوایین دێڕی hello.py، واتە func_name()، بسڕیتەوە، چی چاپ دەکات؟

11- كرداره كان! Python FunctionsMR. Ant · Kurdish (Sorani)کوردی (سۆرانی) · 10K viewsبینین · 362 likesلایک

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ـەکەی جێبەجێ کردبێت. ئەگەر لە دێڕێکی پێشتردا بانگی بکەیت، ناوەکە هێشتا نەناسراوە:

Called one line too earlyیەک دێڕ زووتر بانگکراوەtoo_early.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
say_hello()          # called too early!

def say_hello():
    print("Hello World!")

Inside 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).

Quick checkپشکنینی خێراWhich order works?کام ڕیزبەندی کار دەکات؟

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:

سێ بەشی هەیە: ناوی ، و جەستەکەی. لە ناساندنەکەدا دەڵێیت چی بکات. شێوە گشتییەکەی ئەمەیە:

SyntaxداڕستنTEXT
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 function def larger(num1, num2): with labelled parts. Above the first line: ‘keyword’ points at def, ‘function name’ at larger, ‘parameters’ at (num1, num2), and a brace over larger(num1, num2) is labelled ‘signature: how to call it’. The first line is the header; an arrow says the colon ends the header. The five indented lines below (if, result = num1, else, result = num2, return result) are the body, indented 4 spaces; an arrow at return result says the return value goes back. Below, the line z = larger(x, y) is the caller's function call, and x and y are marked as arguments, the real values sent in.کرداری def larger(num1, num2): لەگەڵ بەشە ناونووسکراوەکانی. لە سەرووی یەکەم دێڕەوە: «وشەی کلیلەیی» ئاماژە بە def دەکات، «ناوی کردار» بە larger، «پارامیتەرەکان» بە (num1, num2) و کەوانەیەکی گەورە لە سەرووی larger(num1, num2) نووسراوە «واژووی کردار: چۆن بانگ دەکرێت». یەکەم دێڕ سەردێڕی کردارە؛ تیرێک دەڵێت دوو خاڵ کۆتایی سەردێڕەکەیە. ئەو پێنج دێڕەی خوارەوە کە بۆشایی سەرەتای دێڕیان هەیە (if، result = num1، else، result = num2، return result) جەستەی کردارن، بە 4 بۆشایی؛ تیرێک لە return result دەڵێت نرخی گەڕاوە دەگەڕێتەوە. لە خوارەوە دێڕی z = larger(x, y) بانگکردنی کردارە لە بانگکەرەوە و x و y وەک ئارگیومێنتەکان دیاری کراون، واتە ئەو نرخە ڕاستەقینانەی دەنێردرێن.
The parts of a function definition, and a call to it.بەشەکانی و بانگکردنێکی.CêIT
Quick checkپشکنینی خێراWhich part of a function definition ends with a colon?کام بەشی بە دوو خاڵ کۆتایی دێت؟

Python Functions - Visually ExplainedVisually Explained · Englishئینگلیزی · 403K viewsبینین · 13K likesلایک · Partبەشی 0:19–4:55 (ofلە 14:10)

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()
Quick checkپشکنینی خێراlen("Shilan") gives 6. What kind of function is len?len("Shilan") ژمارە 6 دەدات. len چ جۆرە ؟

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.

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

A call used as a valueبانگکردنێک وەک نرخmax_calls.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
larger = max(3, 4)       # the call is used as a value
print(larger)
print(max(3, 4))         # the value goes straight into print()
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

The call max(3, 4) becomes 4, which is stored in larger.

بانگکردنی 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 هەڵبگرە و چاپی بکە:

What does print give back?print چی دەگەڕێنێتەوە؟print_none.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
x = print("Programming is fun!")
print(x)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

The text is printed. x receives what print returns.

دەقەکە چاپ دەکرێت. x ئەوە وەردەگرێت کە print دەیگەڕێنێتەوە.

Lineدێڕی 2

x is None: "no value".

x بریتییە لە None: «هیچ نرخ».

Quick checkپشکنینی خێراWhich line uses the call of a value-returning function as a value?کام دێڕ بانگکردنی وەک بەکار دەهێنێت؟

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 (هۆکارەکەی لە خوارەوەیە).

Define it, then invoke itبیناسێنە، پاشان بانگی بکەlarger.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
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)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

Header: the name larger and the two parameters num1 and num2.

: ناوی larger و دوو num1 و num2.

Lineدێڕی 2-5

The body decides which number is larger.

بڕیار دەدات کام ژمارە گەورەترە.

Lineدێڕی 6

return result ends the function and sends the value back.

return result کۆتایی پێدێنێت و نرخەکە دەگەڕێنێتەوە.

Lineدێڕی 11

The call: x and y are the arguments. Their values 3 and 7 are passed to num1 and num2.

بانگکردنەکە: x و y . نرخەکانیان، 3 و 7، دەنێردرێن بۆ num1 و num2.

  • x and y in 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 return statement to give back its result.
  • The function ends as soon as a return statement runs.
  • x و y لە بانگکردنەکەدا ، کە زۆرجار پێیان دەگوترێت .
  • وەک شوێنگرێک وایە: کاتێک بانگ دەکرێت، نرخێکی پێ دەدرێت.
  • پێویستی بە ڕستەی return هەیە بۆ گەڕاندنەوەی ئەنجامەکەی.
  • هەر کە ڕستەیەکی return جێبەجێ بوو کۆتایی دێت.
Quick checkپشکنینی خێراIn z = larger(x, y), what are x and y?لە z = larger(x, y)ـدا، x و y چین؟

Example: the larger of two numbersنموونە: گەورەترینی دوو ژمارە

Parameters and argumentsپارامیتەرەکان و ئارگیومێنتەکان

AspectلایەنParameterArgument
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 parameteractual parameter
What it isچییەA name that waits for a valueناوێک کە چاوەڕێی نرخێک دەکاتThe value that is sentئەو نرخەی دەنێردرێت
A form at the post officeفۆرمێک لە پۆستەخانەدا

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ـدا هەر کە نەبێت دەبێت وەربگرێت، دەنا بانگکردنەکە شکست دەهێنێت:

One argument is missingئارگیومێنتێک کەمەmissing.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def larger(num1, num2):
    if num1 > num2:
        return num1
    return num2


print(larger(5))

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) لە ئارگیومێنتە شوێنییەکان، ئارگیومێنتە ناودارەکان و نرخە بنەڕەتییەکان فێر دەکرێن.

Quick checkپشکنینی خێراdef area(width, height): is called as area(3, 4). Which names are the parameters?def area(width, height): بەم شێوەیە بانگ دەکرێت: area(3, 4). کام ناوانە ؟

Python Functions | Python Tutorial for Absolute Beginners #1Programming with Mosh · Englishئینگلیزی · 1.3M viewsبینین · 21K likesلایک · Partبەشی 2:25–4:47 (ofلە 30:33)

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 چۆن جێبەجێ دەکات کە تێدایە؟ دێڕ بە دێڕ بەدوای ئەمەدا بڕۆ. ژمارەی دێڕەکان گرنگن: خوارەوە بەکاریان دەهێنێت.

The slides' program (with the function renamed 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 function
Trace table of larger_trace.py larger_trace.py
StepهەنگاوLineدێڕWhat happensچی ڕوو دەداتVariables now ئێستا
116main() is called; control jumps to line 10.main() بانگ دەکرێت؛ ڕەوتەکە باز دەداتە دێڕی ⁦10⁩.—
211i = 5i = 5i = 5
312j = 2j = 2i = 5, j = 2
413 → 2larger(i, j) is invoked: 5 is passed to num1, 2 to num2.larger(i, j) بانگ دەکرێت: 5 دەدرێتە num1 و 2 دەدرێتە num2.num1 = 5, num2 = 2
53–45>25 > 2 is true, so result = num1.5>25 > 2 ڕاستە، بۆیە result = num1.result = 5
68return result ends larger and sends 5 back to line 13.return result کۆتایی بە larger دێنێت و 5 دەگەڕێنێتەوە بۆ دێڕی ⁦13⁩.—
713k = 5k = 5i = 5, j = 2, k = 5
814The sentence is printed.ڕستەکە چاپ دەکرێت.—
Quick checkپشکنینی خێراAt step 6, return result runs. Which line does Python continue with?لە هەنگاوی 6دا return result جێبەجێ دەبێت. Python لە کام دێڕەوە بەردەوام دەبێت؟

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 دێڕی بانگکردنەکە جێدەهێڵێت و جێبەجێ دەکات. کاتێک تەواو دەبێت، دەگەڕێتەوە بۆ ئەو شوێنەی لێی بانگ کرا و بانگکردنەکە بە دەگۆڕدرێت.

Animation in seven steps. Left: main() with i = 5, j = 2, k = larger(i, j) and a print line. Right: the function larger(num1, num2). 1: main sets i to 5 and j to 2. 2: the call line lights up and an arrow jumps to the header of larger, carrying 5 into num1 and 2 into num2; boxes for num1 and num2 appear. 3: the if line is checked: 5 is larger than 2. 4: result = num1, the result box shows 5. 5: return result lights up and a dashed arrow carries 5 back to the call line. 6: the boxes of larger fade out and k becomes 5. 7: main prints ‘The larger number of 5 and 2 is 5’.
Animation in seven steps. Left: main() with i = 5, j = 2, k = larger(i, j) and a print line. Right: the function larger(num1, num2). 1: main sets i to 5 and j to 2. 2: the call line lights up and an arrow jumps to the header of larger, carrying 5 into num1 and 2 into num2; boxes for num1 and num2 appear. 3: the if line is checked: 5 is larger than 2. 4: result = num1, the result box shows 5. 5: return result lights up and a dashed arrow carries 5 back to the call line. 6: the boxes of larger fade out and k becomes 5. 7: main prints ‘The larger number of 5 and 2 is 5’.
The call jumps into larger(); the return value comes back to the call.بانگکردنەکە باز دەداتە ناو larger()؛ دەگەڕێتەوە بۆ شوێنی بانگکردنەکە.CêIT

Notice 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ـدا دەپارێزێت. مەودای گۆڕاوەکان ئەمە بە وردی ڕوون دەکاتەوە.

Quick checkپشکنینی خێراWhile larger is running, can main use the variable num1?لە کاتێکدا larger کار دەکات، ئایا main دەتوانێت num1 بەکار بهێنێت؟

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.

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

A signature with type hintsواژوویەک لەگەڵ تێبینییەکانی جۆرhints.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
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 hints
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

Read it as: larger takes 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.

کەواتە تێبینین بۆ مرۆڤ و بۆ ئامرازەکان: دەستکاریکەرێکی باش بەکاریان دەهێنێت بۆ ئاگادارکردنەوەت پێش جێبەجێکردنی .

Quick checkپشکنینی خێراWhat does -> int in def larger(num1: int, num2: int) -> int: say?-> int لە def larger(num1: int, num2: int) -> int:ـدا چی دەڵێت؟

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
Pythondef larger(num1, num2):
Python with type hintsPython لەگەڵ def larger(num1: int, num2: int) -> int:
Javastatic int larger(int num1, int num2)
Gofunc 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 ئەم دوو زمانە بەراورد دەکات.

Quick checkپشکنینی خێراIn which language must the types of num1 and num2 be correct before the program can run at all?لە کام زماندا دەبێت جۆری num1 و num2 دروست بن پێش ئەوەی بتوانێت هەر کار بکات؟

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() و دەستکاریکەرەکان پیشانی هەر کەسێک دەدەن کە بەکار دەهێنێت.

A one-line docstringزنجیرەنووسەیەکی بەڵگەنامە بە یەک دێڕdocstring.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def larger(num1, num2):
    """Return the larger of two numbers."""
    if num1 > num2:
        return num1
    return num2


print(larger.__doc__)
help(larger)
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() واژووەکە و پیشان دەدات.

Quick checkپشکنینی خێراWhere must a docstring stand? دەبێت لە کوێ بێت؟

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 بوو، ئیتر ئەو ناوە مانای نادات:

A variable named 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 function
Quick checkپشکنینی خێراWhy does print(sum([10, 20, 30])) fail in sum_hidden.py?بۆچی print(sum([10, 20, 30])) لە sum_hidden.pyـدا شکست دەهێنێت؟

Built-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 functionsTaught inلە کوێ فێر دەبیت
Input and output و input(), print()Input and Outputنێوخستە و دەرخستە
Converting valuesint(), 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، جۆرەکان، زنجیرەنووسەی بەڵگەنامە
A few number toolsچەند ئامرازێکی ژمارەtoolbox.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
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]))
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) is x ** y. With a third argument, pow(x, y, m) gives the remainder of x ** y divided by m — 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) ئەنجامی دابەشکردنی تەواو و پێکەوە دەدات.

Quick checkپشکنینی خێراWhat does pow(3, 2, 5) give?pow(3, 2, 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()
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-4

main uses greet, which is defined later. That is fine: this body runs only at line 11.

main greet بەکار دەهێنێت، کە دواتر ناسێنراوە. ئاساییە: ئەم جەستەیە تەنها لە دێڕی ⁦11⁩دا جێبەجێ دەبێت.

Lineدێڕی 11

The only top-level call: it starts the program.

تاکە بانگکردنی ئاستی سەرەکی: دەست پێدەکات.

Quick checkپشکنینی خێراmain calls greet, but greet is defined below main. When does that cause a NameError?main greet بانگ دەکات، بەڵام greet لە خوار mainـەوە ناسێنراوە. کەی ئەمە دەبێتە هۆی NameError؟

Lab: a pattern functionتاقیگە: کردارێکی شێوەکێشان

ExerciseڕاهێنانLab 2, Task 4تاقیگەی 2، ئەرکی 4

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وەڵامەکە پیشان بدە
pattern.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
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)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

Two parameters: the function works for any pair of numbers.

دوو : بۆ هەر جووتە ژمارەیەک کار دەکات.

Lineدێڕی 3-6

A nested loop: rows from i2 - i1 down to 1; in each row, numbers from row down to 1.

: لە i2 - i1ـەوە بۆ 1؛ لە هەر ژمارەکان لە rowـەوە بۆ 1.

Lineدێڕی 10-12

Three calls, three patterns: the loops are written once.

سێ بانگکردن، سێ شێوە: یەک جار نووسراون.

Quick checkپشکنینی خێراWhat is the first row printed by pattern(2, 9)?pattern(2, 9) یەکەم چی چاپ دەکات؟

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

MistakeهەڵەWhat happensچی ڕوو دەداتFixچارەسەر
Writing the name without (): say_helloنووسینی ناوەکە بەبێ (): say_helloNothing — the function is not calledهیچ — بانگ ناکرێتsay_hello()say_hello()
Calling a function above its defبانگکردنی لە سەرووی defـەکەیەوەNameError: name '…' is not definedNameError: name '…' is not definedPut 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 definitionIndent the body 4 spaces.جەستەکە بە 4 بەرەو ناوەوە ببە.
Too few or too many arguments کەمتر یان زیاترTypeError: … missing 1 required positional argumentTypeError: … missing 1 required positional argumentGive 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.
The forgotten parenthesesکەوانە لەبیرکراوەکانno_call.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def say_hello():
    print("Hello World!")


say_hello        # no ( ): nothing happens
print("Done")

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

ExerciseڕاهێنانA square functionکردارێکی دووجاکردن

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وەڵامەکە پیشان بدە
square.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def square(n):
    return n * n


print(square(4))
print(square(2) + square(3))

Because square returns its result, two calls can be added together: 4+9=134 + 9 = 13.

چونکە square ئەنجامەکەی دەگەڕێنێتەوە، دەتوانرێت دوو بانگکردن کۆ بکرێنەوە: 4+9=134 + 9 = 13.

ExerciseڕاهێنانA line drawerهێڵکێشێک

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وەڵامەکە پیشان بدە
menu.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def draw_line(width):
    print("-" * width)


draw_line(10)
print("Menu")
draw_line(10)
ExerciseڕاهێنانTrace itبەدوایدا بچۆ

Without running it, write down what this program prints. Then explain why double is called twice.

بەبێ جێبەجێکردنی، بنووسە ئەم چی چاپ دەکات. پاشان ڕوونی بکەرەوە بۆچی double دوو جار بانگ دەکرێت.

double.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def double(n):
    print("double got", n)
    return n * 2


def main():
    a = double(3)
    b = double(a)
    print(a, b)


main()
Show answerوەڵامەکە پیشان بدە
Outputدەرئەنجام
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.

ExerciseڕاهێنانPackage the triangleسێگۆشەکە بخە ناو کردارێکەوە

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وەڵامەکە پیشان بدە
triangle.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def triangle(rows):
    for i in range(1, rows + 1):
        for j in range(i):
            print("*", end=" ")
        print()


triangle(3)
print("---")
triangle(2)
Quick checkپشکنینی خێراWhich statement about def is true?کام ڕستە دەربارەی def ڕاستە؟

Challenges: functions in bigger programsڕاهێنانی قورستر: کردارەکان لە بەرنامەکانی گەورەتردا

ExerciseڕاهێنانThe Fibonacci sequenceزنجیرەی فیبۆناچی

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وەڵامەکە پیشان بدە
fibonacci.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
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)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 7-9

Save a + b first: after a = b the old a would 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ـی گەورە زۆر هێواشە: بڕوانە خۆبانگکردنەوە.

ExerciseڕاهێنانThree tries to log inسێ هەوڵ بۆ چوونەژوورەوە

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وەڵامەکە پیشان بدە
login.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
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()
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 True leaves early on success.

زۆرترین سێ جار؛ return True لە کاتی سەرکەوتندا زوو دەردەچێت.

Lineدێڕی 14-15

Reached only after three failures.

تەنها دوای سێ شکست دەگاتە ئێرە.

Quick checkپشکنینی خێراfibonacci(5) prints which numbers?fibonacci(5) کام ژمارانە چاپ دەکات؟

Challenges: functions in bigger programsڕاهێنانی قورستر: کردارەکان لە بەرنامەکانی گەورەتردا

Challenge: a small bank accountڕاهێنانی قورستر: هەژمارێکی بانکیی بچووک

ExerciseڕاهێنانDeposit and withdraw with functionsدانان و ڕاکێشانی پارە بە کردارەکان

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وەڵامەکە پیشان بدە
bank.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
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()
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 return for 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.

بیرۆکە بۆ گەورەکردنی دواتر: چەند هەژمارێک لە فەرهەنگێکدا، یان بژاردەیەکی پاشەکەوت کە قازانجی ساڵانە لە نرخە گەڕاوەکان بەکار دەهێنێت.

Quick checkپشکنینی خێراIn bank.py the balance is 30,000 dinars. What does withdraw(30000, 25000) return?لە bank.pyـدا بڕی پارە ⁦30⁩٬⁦000⁩ دینارە. withdraw(30000, 25000) چی دەگەڕێنێتەوە؟

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.
  • def only 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; return brings it back with the result.
  • Name functions in lowercase with underscores, describe them with a docstring, and never reuse built-in names such as max or sum.
  • بلۆکێکی ناونراوی کۆدە: یەک جار بینووسە و چەندین جار بانگی بکە. کۆد دووبارە بەکارهێنراو دەکەن و کێشەیەکی گەورە دەکەنە چەند کارێکی بچووک.
  • ناساندن دوو بەشی هەیە: — def، ناو، لەناو ( ) و دوو خاڵ — و جەستەیەک کە هەیە.
  • def تەنها دروست دەکات. بانگکردن جێبەجێی دەکات؛ ئەو کۆدەی بانگ دەکات .
  • ئەو ناوانەن کە لە سەردێڕەکەدان؛ ئەو نرخانەن کە لە بانگکردنەکەدان.
  • بانگکردنی وەک بەکار دێت؛ وەک بانگ دەکرێت.
  • بانگکردن دەباتە ناو ؛ return لەگەڵ ئەنجامەکەدا دەیگەڕێنێتەوە.
  • ناوی بە پیتی بچووک و _ بنووسە، بە وەسفیان بکە و هەرگیز ناوە ئامادەکانی وەک max یان sum دووبارە بەکار مەهێنەوە.
Review questionsپرسیارەکانی پێداچوونەوە
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

باقیی ئەم بەشە

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.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.

Functions in Python are easy 📞Bro Code · Englishئینگلیزی · 1.4M viewsبینین · 37K likesلایک

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زاراوە سەرەکییەکان

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

Return Values and Noneنرخە گەڕاوەکان و None

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

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