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

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

What the return statement gives back and why it ends a function at once; early returns for special cases; why every branch must return a value and how a missing return becomes None; functions without return values; returning versus printing; and the Lab 2 pyramid, average and grade tasks, the triangle-perimeter quiz, two mystery functions, and practice with traffic lights, discounts and formulas.

ڕستەی return چی دەگەڕێنێتەوە و بۆچی یەکسەر کۆتایی پێدێنێت؛ returnـی زوو بۆ حاڵەتە تایبەتەکان؛ بۆچی هەموو لقێک دەبێت نرخێک بگەڕێنێتەوە و چۆن returnـێکی ون دەبێتە None؛ ؛ گەڕاندنەوە بەرامبەر چاپکردن؛ و ئەرکەکانی هەرەم، و نمرەی تاقیگەی 2، تاقیکردنەوەی چێوەی سێگۆشە، دوو نهێنی و ڕاهێنان لەسەر گڵۆپی هاتووچۆ، داشکاندن و .

24 min read23 خولەک خوێندنەوە · 23 stepsهەنگاو

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

  • Use return to send any expression back to the caller, and explain why the function ends at that moment.
  • Handle special cases with an early return.
  • Make every branch return a value, and recognise None when a branch forgets.
  • Choose between returning and printing, and write functions without return values that are called as statements.
  • return بەکار بهێنیت بۆ ناردنەوەی هەر بۆ و ڕوونی بکەیتەوە بۆچی لەو کاتەدا کۆتایی دێت.
  • بە returnـی زوو مامەڵە لەگەڵ حاڵەتە تایبەتەکان بکەیت.
  • وا بکەیت هەموو لقێک نرخێک بگەڕێنێتەوە و None بناسیتەوە کاتێک لقێک لەبیری دەکات.
  • لە نێوان گەڕاندنەوە و چاپکردندا هەڵبژێریت و بنووسیت کە وەک بانگ دەکرێن.

What return doesreturn چی دەکات

You use the return statement to state the result of a function. After the word return you can write any expression. Python works out its value and sends that value back to the , where the call is replaced by it.

ڕستەی return بەکار دەهێنیت بۆ دیاریکردنی ئەنجامی . دوای وشەی return دەتوانیت هەر بنووسیت. Python نرخەکەی دەژمێرێت و ئەو نرخە دەنێرێتەوە بۆ ، کە لەوێ بانگکردنەکە بەو نرخە دەگۆڕدرێت.

A useful picture: a value-returning function is like a machine. Arguments go in, one value — the — comes out. A function without a return value is different: it does something, such as printing on the screen, and gives back only None.

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

Two rows. Top, a value-returning function: the caller x = cube_volume(2) sends the argument 2 to a machine labelled cube_volume with return side_length ** 3; a thick arrow brings the return value 8 back to the caller, and print(x) shows 8. Bottom, a function without a return value: the caller result = box_string("Hi") sends the argument "Hi" to a machine labelled box_string that prints a box; the box ----, |Hi|, ---- appears on a screen; a dashed arrow brings back only None, and print(result) shows None.دوو ڕیز. سەرەوە، کردارێکی نرخگەڕێنەر: بانگکەر x = cube_volume(2) ئارگیومێنتی 2 دەنێرێت بۆ ئامێرێک بە ناوی cube_volume کە return side_length ** 3ـی تێدایە؛ تیرێکی ئەستوور نرخی گەڕاوەی 8 دەگەڕێنێتەوە بۆ بانگکەر و print(x) ژمارە 8 پیشان دەدات. خوارەوە، کردارێکی نەگەڕێنەر: بانگکەر result = box_string("Hi") ئارگیومێنتی "Hi" دەنێرێت بۆ ئامێرێک بە ناوی box_string کە چوارچێوەیەک چاپ دەکات؛ چوارچێوەی ----، |Hi|، ---- لەسەر شاشەیەک دەردەکەوێت؛ تیرێکی پچڕپچڕ تەنها None دەگەڕێنێتەوە و print(result) وشەی None پیشان دەدات.
Values in, one value out — or an action and None.نرخ دەچێتە ژوورەوە و یەک نرخ دێتە دەرەوە — یان کارێک و None.CêIT
Quick checkپشکنینی خێراWhat does return do?return چی دەکات؟

12- ئه و كردارانه ی كه نرخێك ئه گه ڕێننه وه! Return StatementMR. Ant · Kurdish (Sorani)کوردی (سۆرانی) · 8.4K viewsبینین · 260 likesلایک

In Kurdish: functions that give back a value with the return statement.

بە کوردی: ، کە بە return دەگەڕێننەوە.

Kurdish (Sorani), whole video (7:52): part 12 of MR. Ant's Python course.

ڤیدیۆیەکی کوردی (سۆرانی)، هەموو ڤیدیۆکە ⁦(7:52)⁩: بەشی ⁦12⁩ لە کۆرسی ⁦MR. Ant⁩.

Returning an expression directlyگەڕاندنەوەی دەربڕینێک ڕاستەوخۆ

Often you do not need a variable for the result. Instead of saving the value in a variable and returning the variable, you can return the expression itself. Both versions below give the same answers:

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

Two steps: a variable, then returnدوو هەنگاو: گۆڕاوێک، پاشان returncube_two_steps.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def cube_volume(side_length):
    volume = side_length ** 3
    return volume


print(cube_volume(2), cube_volume(10))
One step: return the expressionیەک هەنگاو: دەربڕینەکە بگەڕێنەوەcube.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def cube_volume(side_length):
    return side_length ** 3


print(cube_volume(2), cube_volume(10))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

** is the power operator: side_length ** 3 is side_length * side_length * side_length.

** توانە: side_length ** 3 واتە side_length * side_length * side_length.

Lineدێڕی 5

Two calls inside one print: their return values 8 and 1000 are printed.

دوو بانگکردن لەناو یەک printـدا: ، 8 و ⁦1000⁩، چاپ دەکرێن.

Quick checkپشکنینی خێراWhich one-line body returns the area of a rectangle?کام جەستەی یەک دێڕی ڕووبەری لاکێشەیەک دەگەڕێنێتەوە؟

return ends the function at oncereturn یەکسەر کردارەکە کۆتایی پێدێنێت

When a return statement runs, the function exits immediately; the lines after it are not executed. Many programmers use this on purpose to deal with special cases at the start of a function. A cube cannot have a negative side, so for a negative value this function returns 0 and stops:

کاتێک ڕستەیەکی return جێبەجێ دەبێت، یەکسەر دەردەچێت؛ دێڕەکانی دوای ئەو جێبەجێ ناکرێن. زۆر بەرنامەساز بە ئەنقەست ئەمە بەکار دەهێنن بۆ مامەڵەکردن لەگەڵ حاڵەتە تایبەتەکان لە سەرەتای . درێژیی لای مکەعەبێک ناتوانێت سالب بێت، بۆیە بۆ نرخێکی سالب ئەم 0 دەگەڕێنێتەوە و دەوەستێت:

Handle the special case firstسەرەتا حاڵەتە تایبەتەکە چارەسەر بکەcube_check.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def cube_volume(side_length):
    if side_length < 0:
        return 0          # special case: the function stops here
    # Handle the regular case.
    return side_length ** 3


print(cube_volume(-2))
print(cube_volume(3))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2-3

The special case: for a negative side the function returns 0 and stops here.

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

Lineدێڕی 4-5

The regular case is reached only when side_length is 0 or more.

تەنها کاتێک دەگاتە حاڵەتە ئاساییەکە کە side_length 0 یان زیاتر بێت.

Animation of cube_check.py. First the call cube_volume(-2): side_length shows -2, the line if side_length < 0 is checked and is true, return 0 lights up, lines 4 and 5 are crossed out and marked skipped, and 0 appears in the output. Then the call cube_volume(3): side_length shows 3, the condition is false so return 0 is crossed out, return side_length ** 3 lights up and 27 appears under the 0.
Animation of cube_check.py. First the call cube_volume(-2): side_length shows -2, the line if side_length < 0 is checked and is true, return 0 lights up, lines 4 and 5 are crossed out and marked skipped, and 0 appears in the output. Then the call cube_volume(3): side_length shows 3, the condition is false so return 0 is crossed out, return side_length ** 3 lights up and 27 appears under the 0.
return 0 fires and the rest of the body is skipped.return 0 جێبەجێ دەبێت و باقیی جەستەکە جێدەهێڵرێت.CêIT
Quick checkپشکنینی خێراWhat does cube_volume(-5) return in cube_check.py?لە cube_check.pyـدا cube_volume(-5) چی دەگەڕێنێتەوە؟

return ends the function at oncereturn یەکسەر کردارەکە کۆتایی پێدێنێت

Code after return never runsکۆدی دوای return هەرگیز جێبەجێ نابێت

A line written directly after return, in the same block, can never run. Python does not warn you — it simply skips it:

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

unreachable.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def greet(name):
    return "Hello, " + name
    print("This line never runs")


message = greet("Dilan")
print(message)
Quick checkپشکنینی خێراHow many times is line 3 of unreachable.py executed?دێڕی 3ی unreachable.py چەند جار جێبەجێ دەبێت؟

Every branch should return a valueهەموو لقێک دەبێت نرخێک بگەڕێنێتەوە

If a function returns a value in some branches of an if, then every branch should return one. Look at this incorrect function: it returns a volume for 0 and positive sides, but nothing for a negative side.

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

No return value for a negative sideبۆ لایەکی سالب هیچ نرخی گەڕاوە نییەcube_incorrect.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def cube_volume(side_length):
    if side_length >= 0:
        return side_length ** 3
    # Error: no return value if side_length < 0


print(cube_volume(2))
print(cube_volume(-2))

Python does not report this as an error. When the if condition is false, the function simply reaches the end of its body — it "falls off the end" — and Python returns the special value None ().

Python ئەمە وەک ڕاناگەیەنێت. کاتێک if هەڵەیە، تەنها دەگاتە کۆتایی جەستەکەی — «لە کۆتاییەوە دەکەوێتە خوارەوە» — و Python نرخی تایبەتی None () دەگەڕێنێتەوە.

A flow diagram. The call cube_volume(side_length) leads to the decision side_length >= 0. The True branch goes to return side_length ** 3, and the caller gets a number, for example cube_volume(2) gives 8. The False branch goes to a dashed box ‘no return here: the end is reached’, and the caller gets None, for example cube_volume(-2) gives None.هێڵکارییەکی ڕەوت. بانگکردنی cube_volume(side_length) دەگاتە بڕیاری side_length >= 0. لقی True دەچێت بۆ return side_length ** 3 و بانگکەر ژمارەیەک وەردەگرێت، بۆ نموونە cube_volume(2) ژمارە 8 دەدات. لقی False دەچێت بۆ سندوقێکی پچڕپچڕ «لێرەدا return نییە: دەگاتە کۆتایی» و بانگکەر None وەردەگرێت، بۆ نموونە cube_volume(-2) None دەدات.
A branch with no return falls off the end and gives None.لقێک کە returnـی تێدا نەبێت دەگاتە کۆتایی و None دەدات.CêIT
Quick checkپشکنینی خێراWhat does print(cube_volume(-2)) show for cube_incorrect.py?بۆ cube_incorrect.py، print(cube_volume(-2)) چی پیشان دەدات؟

Every branch should return a valueهەموو لقێک دەبێت نرخێک بگەڕێنێتەوە

Where the missing value bitesنرخە ونبووەکە لە کوێ زیان دەگەیەنێت

A missing return is a : the program runs, but the wrong value travels on. The crash often comes later, on a line that looks innocent:

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

The error appears far from its causeهەڵەکە دوور لە هۆکارەکەی دەردەکەوێتnone_bites.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def cube_volume(side_length):
    if side_length >= 0:
        return side_length ** 3


total = cube_volume(-2) + 1
print(total)

The traceback points at line 6, but the real mistake is the missing else branch in the function. When you see NoneType in an error message, look for a function that forgot to return a value. More on reading errors: Errors and Debugging.

ئاماژە بە دێڕی 6 دەکات، بەڵام هەڵە ڕاستەقینەکە نەبوونی لقی elseـە لە . کاتێک لە NoneType دەبینیت، بەدوای بگەڕێ کە گەڕاندنەوەی نرخێکی لەبیر کردووە. زیاتر دەربارەی خوێندنەوەی هەڵەکان: هەڵەکان و کرمەکوژی.

Quick checkپشکنینی خێراYou see TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'. What is the most likely cause?TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' دەبینیت. ئەگەری زۆرتر هۆکارەکەی چییە؟

Every branch should return a valueهەموو لقێک دەبێت نرخێک بگەڕێنێتەوە

Two correct versionsدوو وەشانی دروست

The slides fix the function in two ways. The first gives the else branch its own return:

سلایدەکان بە دوو شێوە چاک دەکەنەوە. یەکەمیان returnـێکی تایبەت دەدات بە لقی else:

A return in every branchreturnـێک لە هەموو لقێکداcube_two_returns.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def cube_volume(side_length):
    if side_length >= 0:
        return side_length ** 3
    else:
        return 0


print(cube_volume(2))
print(cube_volume(-2))

The second way avoids several return statements: store the result in a variable in each branch, and return that variable once, in the last statement of the function.

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

One return at the endیەک return لە کۆتاییداcube_one_return.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def cube_volume(side_length):
    if side_length >= 0:
        volume = side_length ** 3
    else:
        volume = 0
    return volume          # one return, at the end


print(cube_volume(2))
print(cube_volume(-2))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2-5

Both branches set volume.

هەردوو لقەکە نرخ دەدەن بە volume.

Lineدێڕی 6

A single exit: easy to see what comes back.

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

Quick checkپشکنینی خێراIn cube_one_return.py, what would happen if you deleted the else part (lines 4–5)?لە cube_one_return.pyـدا، ئەگەر بەشی else (دێڕەکانی ⁦4–5⁩) بسڕیتەوە چی ڕوو دەدات؟

Functions without return valuesکردارە نەگەڕێنەرەکان

Sometimes you need to carry out a sequence of instructions that does not produce a value. If that sequence is needed several times, you still package it into a function. This one prints a string inside a box:

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

Print a string in a boxزنجیرەنووسەیەک لەناو چوارچێوەیەکدا چاپ بکەbox.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def box_string(content):
    n = len(content)
    print("-" * (n + 2))
    print("|" + content + "|")
    print("-" * (n + 2))


box_string("Stage 1: IT Department")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

len(content) is the number of characters: 22 here.

len(content) ژمارەی نووسەکانە: لێرەدا ⁦22⁩.

Lineدێڕی 3

"-" * (n + 2) repeats the dash n+2n + 2 times: two more for the two | signs.

"-" * (n + 2) هێڵی کورت n+2n + 2 جار دووبارە دەکاتەوە: دوو دانە زیاتر بۆ دوو نیشانەی |.

Lineدێڕی 8

The call is a statement on its own line.

بانگکردنەکە لەسەر دێڕی خۆی.

box_string does not compute any value. It performs some actions and then returns to the caller. Strictly speaking it does return something — the special value None — but there is nothing useful you can do with it. So you call such a function as a statement, not as part of an expression.

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

What comes back from box_string?چی لە box_stringـەوە دەگەڕێتەوە؟box_none.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def box_string(content):
    n = len(content)
    print("-" * (n + 2))
    print("|" + content + "|")
    print("-" * (n + 2))


result = box_string("Hi")
print(result)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 8

The box is printed while the function runs; result receives None.

چوارچێوەکە لە کاتی کارکردنی چاپ دەکرێت؛ result None وەردەگرێت.

Quick checkپشکنینی خێراHow should you call box_string?چۆن box_string بانگ بکەیت؟

None: the value that means "nothing"None: ئەو نرخەی واتای «هیچ» دەدات

None is Python's special value for "no value" (). It has its own type, NoneType, and print shows it as the word None. A function returns None in three situations: it has no return statement, it runs a bare return with nothing after it, or it reaches the end of its body without meeting a return.

None نرخی تایبەتی Pythonـە بۆ «هیچ نرخ» (). جۆری تایبەتی خۆی هەیە (NoneType) و print وەک وشەی None پیشانی دەدات. لە سێ حاڵەتدا None دەگەڕێنێتەوە: هیچ ڕستەیەکی returnـی نییە، returnـێکی بەتاڵ (بەبێ هیچ شتێک لە دوایدا) جێبەجێ دەکات، یان دەگاتە کۆتایی جەستەکەی بەبێ ئەوەی بگاتە returnـێک.

none_type.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
print(None)
print(type(None))

Sometimes None is returned on purpose, to say "I found nothing". The caller then checks for it with is None:

هەندێک جار None بە ئەنقەست دەگەڕێنرێتەوە، بۆ ئەوەی بڵێت «هیچم نەدۆزییەوە». ئەوسا بە is None دەیپشکنێت:

None as a deliberate answerNone وەک وەڵامێکی ئەنقەستیfirst_even.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def find_first_even(a, b, c):
    for n in (a, b, c):
        if n % 2 == 0:
            return n
    return None          # no even number: say "nothing" on purpose


result = find_first_even(3, 8, 5)
print(result)

result = find_first_even(1, 3, 5)
if result is None:
    print("No even number")
print(type(result))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2-4

return n inside the loop ends the whole function at the first even number.

return n لەناو هەموو لە یەکەم ژمارەی جووتدا کۆتایی پێدێنێت.

Lineدێڕی 5

Written out on purpose: if no number was even, say so with None.

بە ئەنقەست نووسراوە: ئەگەر هیچ ژمارەیەک جووت نەبوو، بە None بیڵێ.

Lineدێڕی 12

is None is the correct test for None.

is None پشکنینی دروستە بۆ None.

Quick checkپشکنینی خێراWhich of these does not make a function return None?کام لەمانە وا ناکات None بگەڕێنێتەوە؟

Returning versus printingگەڕاندنەوە بەرامبەر چاپکردن

Shouting versus servingهاوارکردن بەرامبەر هێنانی چا

In a tea house, a tea maker who shouts "Your tea is ready!" across the room has told you something — but there is no glass on your table. That is print: the message goes to the screen, and the program gets nothing it can use. A waiter who puts the glass on your table has given you something you can drink, sweeten or pass to a friend. That is return: the value goes to the caller, which can store it, calculate with it or hand it on.

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

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

A Python function may do both — print a message and return a value. They are simply two different jobs: printing talks to the person at the screen, returning talks to the program.

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

Same sum, two very different functionsهەمان کۆ، دوو کرداری زۆر جیاوازprint_or_return.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def add_and_print(a, b):
    print(a + b)          # shows the sum on the screen


def add_and_return(a, b):
    return a + b          # gives the sum back to the caller


x = add_and_return(2, 3) * 10
print("x is", x)

y = add_and_print(2, 3)
print("y is", y)
z = y * 10
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 9

add_and_return(2, 3) is the value 5, so x becomes 50.

add_and_return(2, 3) نرخی 5ـە، بۆیە x دەبێتە ⁦50⁩.

Lineدێڕی 12

add_and_print shows 5 on the screen but gives back None.

add_and_print ژمارە 5 لەسەر شاشە پیشان دەدات بەڵام None دەگەڕێنێتەوە.

Lineدێڕی 14

None * 10 is impossible: TypeError.

None * 10 ناشێت: TypeError.

Quick checkپشکنینی خێراIn print_or_return.py, what does y hold after y = add_and_print(2, 3)?لە print_or_return.pyـدا، دوای y = add_and_print(2, 3) چی لە yـدا هەیە؟

print() vs. return in Python FunctionsCoding with Estefania · Englishئینگلیزی · 176K viewsبینین · 3.7K likesلایک

The difference between print() inside a function and return: print only shows text, so the caller gets None.

جیاوازیی print() لەناو لەگەڵ return: print تەنها دەق پیشان دەدات، بۆیە None وەردەگرێت.

Whole video (4:47). Chapters: 0:20 return, 1:58 print() in a function, 4:27 summary.

هەموو ڤیدیۆکە ⁦(4:47)⁩. بەشەکان: ⁦0:20⁩ return، ⁦1:58⁩ print() لەناو ، ⁦4:27⁩ کورتە.

Returning versus printingگەڕاندنەوە بەرامبەر چاپکردن

Lab 2, Task 2: the pyramid, two waysتاقیگەی 2، ئەرکی 2: هەرەمەکە بە دوو شێوە

ExerciseڕاهێنانLab 2, Task 2: pyramid volumeتاقیگەی 2، ئەرکی 2: قەبارەی هەرەم

Define a function that calculates the volume of a pyramid with a square base: base_area = base_length * base_length and volume = height * base_area / 3. Show its result for the pyramids (9, 10), (0, 10) and (3, 12), where each pair is (height, base length).

بناسێنە کە قەبارەی هەرەمێک بە بنکەیەکی چوارگۆشە بژمێرێت: base_area = base_length * base_length و volume = height * base_area / 3. ئەنجامەکەی بۆ هەرەمەکانی ⁦(9, 10)⁩، ⁦(0, 10)⁩ و ⁦(3, 12)⁩ پیشان بدە، کە هەر جووتێک (بەرزی، درێژیی لای بنکە)یە.

V=h⋅a23V = \frac{h \cdot a^2}{3}

hh is the height and aa the length of a side of the square base, so a2a^2 is the base area.

hh بەرزییەکەیە و aa درێژیی لایەکی بنکە چوارگۆشەکەیە، بۆیە a2a^2 ڕووبەری بنکەکەیە.

Expected outputدەرخستەکەی چاوەڕوانکراو
the first pyramid Volume: 300.0
the second pyramid Volume: 0.0
the third pyramid Volume: 144.0
Show answerوەڵامەکە پیشان بدە
pyramid.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def pyramid_volume(height, base_length):
    base_area = base_length * base_length
    volume = height * base_area / 3
    return volume


print("the first pyramid Volume:", pyramid_volume(9, 10))
print("the second pyramid Volume:", pyramid_volume(0, 10))
print("the third pyramid Volume:", pyramid_volume(3, 12))

total = pyramid_volume(9, 10) + pyramid_volume(3, 12)
print("Both pyramids together:", total)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-4

The function returns the volume.

قەبارەکە دەگەڕێنێتەوە.

Lineدێڕی 11-12

Because the values come back, they can be added: 300.0+144.0=444.0300.0 + 144.0 = 444.0.

چونکە نرخەکان دەگەڕێنەوە، دەتوانرێت کۆ بکرێنەوە: 300.0+144.0=444.0300.0 + 144.0 = 444.0.

One student's solution printed the volume inside the function instead of returning it:

چارەسەری قوتابییەک قەبارەکەی لەناو چاپ کرد لەبری ئەوەی بیگەڕێنێتەوە:

A student's solution: it printsچارەسەری قوتابییەک: چاپ دەکاتpyramid_print.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
#Task 2
def pyramidVol(level, height, baseLength):
    baseArea = baseLength * baseLength
    volume = height * baseArea / 3
    print(f"The {level} pyramid volume is: {volume}")
pyramidVol("first", 9, 10)
pyramidVol("second", 0, 10)
pyramidVol("third", 3, 12)

The numbers are right, and the label is neatly built with an f-string. But nothing comes back: the caller cannot add the two volumes, round them or use them in a later calculation. A returning function can do everything the printing one does — the caller simply prints the value — and more. (In the student's file this code came straight after Task 1, whose loop never ended its line, so the first pyramid line appeared glued to Task 1's output; see Positional, Keyword and Default Arguments.)

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

Quick checkپشکنینی خێراWhich call works only with the returning version?کام بانگکردن تەنها لەگەڵ وەشانی گەڕێنەرەوە کار دەکات؟

Lab: the average of three numbersتاقیگە: ناوەندی سێ ژمارە

ExerciseڕاهێنانLab 2, Task 3-1تاقیگەی 2، ئەرکی ⁦3-1⁩

Write the function def average(x, y, z) that returns the average of its three arguments. Test it with 12, 46 and 38; the program should print Average = 32.0.

def average(x, y, z) بنووسە کە سێ بگەڕێنێتەوە. بە ⁦12⁩، ⁦46⁩ و ⁦38⁩ تاقیی بکەرەوە؛ دەبێت Average = 32.0 چاپ بکات.

xˉ=x+y+z3=12+46+383=963=32\bar{x} = \frac{x + y + z}{3} = \frac{12 + 46 + 38}{3} = \frac{96}{3} = 32
Show answerوەڵامەکە پیشان بدە
average.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def average(x, y, z):
    return (x + y + z) / 3


print("Average =   ", average(12, 46, 38))

The parentheses matter. Without them Python divides first, because / comes before +:

کەوانەکان گرنگن. بەبێ ئەوان Python سەرەتا دابەش دەکات، چونکە / پێش + دێت:

parentheses.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
print((12 + 46 + 38) / 3)
print(12 + 46 + 38 / 3)
ExerciseڕاهێنانLab 2, Task 3-2تاقیگەی 2، ئەرکی ⁦3-2⁩

Change the program so that the user types the three numbers. Keep the same function average(x, y, z).

بگۆڕە بۆ ئەوەی بەکارهێنەر سێ ژمارەکە بنووسێت. هەمان average(x, y, z) بهێڵەوە.

Hintئاماژە

Read each number with float(input(...)) — never with eval().

هەر ژمارەیەک بە float(input(...)) بخوێنەوە — هەرگیز بە eval().

Show answerوەڵامەکە پیشان بدە
average_input.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def average(x, y, z):
    return (x + y + z) / 3


a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
c = float(input("Enter the third number: "))
print("Average =   ", average(a, b, c))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5-7

input() returns text; float() turns it into a number. See Input and Output.

input() دەق دەگەڕێنێتەوە؛ float() دەیکاتە ژمارە. بڕوانە نێوخستە و دەرخستە.

Lineدێڕی 8

The function did not change at all: only the arguments now come from the keyboard.

هیچ نەگۆڕا: تەنها ئێستا لە تەختەکلیلەوە دێن.

Quick checkپشکنینی خێراWhat does average(10, 20, 60) return?average(10, 20, 60) چی دەگەڕێنێتەوە؟

Lab: grades, with and without returnتاقیگە: نمرە، بە return و بەبێ ئەو

ExerciseڕاهێنانLab 2, Task 5-1: a value-returning grade functionتاقیگەی 2، ئەرکی ⁦5-1⁩: کردارێکی نرخگەڕێنەر بۆ نمرە

Define a value-returning function gGrade(score) and call it to get the grade letter for 5 scores typed by the user: A from 90, B from 80, C from 70, D from 60, and F below 60.

بە ناوی gGrade(score) بناسێنە و بانگی بکە بۆ وەرگرتنی پیتی پلە بۆ 5 نمرە کە بەکارهێنەر دەینووسێت: A لە ⁦90⁩ـەوە، B لە ⁦80⁩ـەوە، C لە ⁦70⁩ـەوە، D لە ⁦60⁩ـەوە و F لە خوار ⁦60⁩.

A sample runنموونەیەکی جێبەجێکردن
enter a score: 78
The grade is  C
enter a score: 34
The grade is  F
enter a score: 98
The grade is  A
enter a score: 64
The grade is  D
enter a score: 80
The grade is  B
Show answerوەڵامەکە پیشان بدە
grades_return.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def gGrade(score):           # a value-returning function
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"


for i in range(5):
    score = int(input("enter a score: "))
    print("The grade is ", gGrade(score))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-11

The elif chain is checked from the top. The first true condition returns its letter and ends the function.

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

Lineدێڕی 10-11

else makes sure every score gets a letter — no branch without return.

else دڵنیا دەبێتەوە کە هەموو نمرەیەک پیتێک وەردەگرێت — هیچ لقێک بەبێ return نییە.

Lineدێڕی 16

The returned letter is used inside print.

پیتە گەڕێنراوەکە لەناو printـدا بەکار دێت.

Quick checkپشکنینی خێراWith the corrected gGrade, which letter does a score of 70 get?بە gGradeـی چاککراو، نمرەی ⁦70⁩ چ پیتێک وەردەگرێت؟

Lab: grades, with and without returnتاقیگە: نمرە، بە return و بەبێ ئەو

Lab: the grade function without returnتاقیگە: کردارەکەی نمرە بەبێ return

ExerciseڕاهێنانLab 2, Task 5-2: a grade function without a return valueتاقیگەی 2، ئەرکی ⁦5-2⁩: کردارێکی نمرە بەبێ نرخی گەڕاوە

Repeat Task 5-1, but this time define a function without a return value, pGrade(score), that shows the grade letter itself. Test it with 50, 90, 36, 85 and 63.

ئەرکی ⁦5-1⁩ دووبارە بکەرەوە، بەڵام ئەم جارە بەبێ بە ناوی pGrade(score) بناسێنە کە خۆی پیتی پلەکە پیشان بدات. بە ⁦50⁩، ⁦90⁩، ⁦36⁩، ⁦85⁩ و ⁦63⁩ تاقیی بکەرەوە.

Show answerوەڵامەکە پیشان بدە
grades_print.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def pGrade(score):           # no return value: it prints
    if score >= 90:
        print("The grade is  A")
    elif score >= 80:
        print("The grade is  B")
    elif score >= 70:
        print("The grade is  C")
    elif score >= 60:
        print("The grade is  D")
    else:
        print("The grade is  F")


for i in range(5):
    score = int(input("enter a score: "))
    pGrade(score)            # called as a statement
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-11

Each branch prints instead of returning; the function returns None.

هەر لقێک چاپ دەکات لەبری گەڕاندنەوە؛ None دەگەڕێنێتەوە.

Lineدێڕی 16

So the call is a statement on its own line.

بۆیە بانگکردنەکە لەسەر دێڕی خۆی.

A shorter pGrade can reuse gGrade: let the value-returning function decide, and only print its answer. This is the usual way to combine the two kinds:

pGradeـێکی کورتتر دەتوانێت gGrade دووبارە بەکار بهێنێتەوە: با بڕیار بدات و تەنها وەڵامەکەی چاپ بکە. ئەمە ڕێگە ئاساییەکەیە بۆ پێکەوە بەکارهێنانی ئەم دوو جۆرە:

grades_reuse.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def gGrade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"


def pGrade(score):           # no return value ...
    print("The grade is ", gGrade(score))   # ... but it reuses gGrade


for i in range(5):
    pGrade(int(input("enter a score: ")))
Quick checkپشکنینی خێراx = pGrade(85) prints The grade is B. What is stored in x?x = pGrade(85) دەقی The grade is B چاپ دەکات. چی لە xـدا هەڵدەگیرێت؟

Quiz program: a triangle's perimeterبەرنامەیەکی تاقیکردنەوە: چێوەی سێگۆشە

ExerciseڕاهێنانThe perimeter of three trianglesچێوەی سێ سێگۆشە

Write a function perimeter(a, b, c) that returns the perimeter of a triangle with sides a, b and c. Use it to print the perimeters of the triangles with sides (4, 8, 11), (13, 11, 17) and (18, 22, 19).

بە ناوی perimeter(a, b, c) بنووسە کە چێوەی سێگۆشەیەک بە لاکانی a، b و c بگەڕێنێتەوە. بەکاری بهێنە بۆ چاپکردنی چێوەی ئەو سێگۆشانەی لاکانیان ⁦(4, 8, 11)⁩، ⁦(13, 11, 17)⁩ و ⁦(18, 22, 19)⁩ـە.

P=a+b+c4+8+11=23P = a + b + c \qquad 4 + 8 + 11 = 23
Show answerوەڵامەکە پیشان بدە
perimeter.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def perimeter(a, b, c):
    p = a + b + c
    return p
print(f"Perimeter of the first triangle is: {perimeter(4, 8, 11)}")
print(f"Perimeter of the second triangle is: {perimeter(13, 11, 17)}")
print(f"Perimeter of the third triangle is: {perimeter(18, 22, 19)}")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-3

The function returns the sum of the three sides.

کۆی سێ لاکە دەگەڕێنێتەوە.

Lineدێڕی 4-6

Each call sits inside an f-string: its return value is put straight into the text.

هەر بانگکردنێک لەناو : ڕاستەوخۆ دەخرێتە ناو دەقەکە.

This solution from the course's quiz works perfectly. The variable p could even be skipped: return a + b + c. PEP 8 would also put two blank lines after the function.

ئەم چارەسەرەی تاقیکردنەوەی کۆرسەکە بە تەواوی کار دەکات. تەنانەت دەکرێت p لابرێت: return a + b + c. ⁦PEP 8⁩ هەروەها دوو دێڕی بەتاڵ دوای دادەنێت.

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

What does it print? Two mystery functionsچی چاپ دەکات؟ دوو کرداری نهێنی

These two exercises were shown in class. Read each program the way Python runs it: start at the call of main(), jump into mystery when it is called, and come back with the return value.

ئەم دوو ڕاهێنانە لە پۆلدا پیشان دران. هەر بەو شێوەیە بخوێنەوە کە Python جێبەجێی دەکات: لە بانگکردنی main()ـەوە دەست پێبکە، کاتێک mystery بانگ دەکرێت باز بدە ناوی و لەگەڵ بگەڕێوە.

ExerciseڕاهێنانMystery 1نهێنیی 1

What does this program print?

ئەم چی چاپ دەکات؟

mystery1.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def main():
    a = 5
    b = 7
    print(mystery(a, b))


def mystery(x, y):
    z = x + y
    z = z / 2.0
    return z


main()
Show answerوەڵامەکە پیشان بدە
Outputدەرئەنجام
6.0
  • mystery(5, 7) is called: x = 5, y = 7.
  • z = x + y gives 12; z = z / 2.0 gives 6.0 — / always produces a float.
  • return z sends 6.0 back, and main prints it. The function computes the average of its two arguments.
  • mystery(5, 7) بانگ دەکرێت: x = 5، y = 7.
  • z = x + y ژمارە ⁦12⁩ دەدات؛ z = z / 2.0 ژمارە ⁦6.0⁩ دەدات — / هەمیشە بەرهەم دێنێت.
  • return z ژمارە ⁦6.0⁩ دەگەڕێنێتەوە و main چاپی دەکات. دوو دەژمێرێت.
ExerciseڕاهێنانMystery 2نهێنیی 2

The second exercise on the same slide was cut off in the class photo. Here is a complete version of the same idea. What does it print?

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

mystery2.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def main():
    a = 4
    print(mystery(a + 1))


def mystery(x):
    y = x * x
    return y


main()
Show answerوەڵامەکە پیشان بدە
Outputدەرئەنجام
25

The argument a + 1 is an expression: Python evaluates it before the call, so x receives 5. Then y = 5 * 5 = 25 is returned and printed. Had the call been mystery(a), x would be 4 and the program would print 16.

a + 1 : Python پێش بانگکردنەکە نرخەکەی دەژمێرێت، بۆیە x ژمارە 5 وەردەگرێت. پاشان y = 5 * 5 = 25 دەگەڕێنرێتەوە و چاپ دەکرێت. ئەگەر بانگکردنەکە mystery(a) بووایە، x دەبووە 4 و ⁦16⁩ـی چاپ دەکرد.

Quick checkپشکنینی خێراIn Mystery 2, when is a + 1 calculated?لە نهێنیی 2ـدا، a + 1 کەی دەژمێردرێت؟

Extra: returning several valuesزیادە: گەڕاندنەوەی چەند نرخێک

A return statement gives back one value — but that value can be a that holds several items. Write the values after return separated by commas, and unpack them at the call:

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

Two results from one callدوو ئەنجام لە یەک بانگکردنlow_high.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def smallest_and_largest(a, b, c):
    return min(a, b, c), max(a, b, c)


low, high = smallest_and_largest(7, 2, 9)
print("smallest:", low)
print("largest:", high)
print(smallest_and_largest(7, 2, 9))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

return min(...), max(...) returns the tuple (2, 9).

return min(...), max(...) (2, 9) دەگەڕێنێتەوە.

Lineدێڕی 5

Unpacking: the first item goes into low, the second into high.

جیاکردنەوە: یەکەم دانە دەچێتە low و دووەم دانە دەچێتە high.

Lineدێڕی 8

Printed without unpacking, you see the tuple itself.

بەبێ جیاکردنەوە چاپ بکرێت، خودی دەبینیت.

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

ExerciseڕاهێنانA shop discount: two resultsداشکاندنی دوکان: دوو ئەنجام

A shop gives 5 % off from 500,000 dinars, 8 % from 1,000,000 and 10 % from 2,000,000; members get 5 % more. Write discount(amount, member) that returns two values: the discount and the amount to pay. Test it with 1,200,000 dinars for a member.

دوکانێک لە ⁦500⁩٬⁦000⁩ دینارەوە 5٪، لە 1٬⁦000⁩٬⁦000⁩ـەوە 8٪ و لە 2٬⁦000⁩٬⁦000⁩ـەوە ⁦10⁩٪ دادەشکێنێت؛ ئەندامەکان 5٪ی زیاتر وەردەگرن. discount(amount, member) بنووسە کە دوو نرخ بگەڕێنێتەوە: بڕی داشکاندن و ئەو بڕەی دەدرێت. بە 1٬⁦200⁩٬⁦000⁩ دینار بۆ ئەندامێک تاقیی بکەرەوە.

Hintئاماژە

Choose the percentage with if … elif from the largest limit down, add 5 for a member, then return off, amount - off.

بە if … elif لە گەورەترین سنوورەوە بەرەو خوار هەڵبژێرە، بۆ ئەندام 5 زیاد بکە، پاشان return off, amount - off.

Show answerوەڵامەکە پیشان بدە
discount.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def discount(amount, member):
    """Return the discount and the amount to pay, in dinars."""
    if amount >= 2000000:
        percent = 10
    elif amount >= 1000000:
        percent = 8
    elif amount >= 500000:
        percent = 5
    else:
        percent = 0
    if member:
        percent += 5            # members get 5 % more
    off = amount * percent // 100
    return off, amount - off


off, pay = discount(1200000, True)
print("Discount:", off, "dinars - to pay:", pay, "dinars")
print(discount(300000, False))
print(discount(2500000, False))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3-10

From the largest limit down, so each elif needs only its lower limit.

لە گەورەترین سنوورەوە بەرەو خوار، بۆیە هەر elifـێک تەنها سنووری خوارەوەی خۆی پێویستە.

Lineدێڕی 13

// keeps the dinars whole: 1200000×13/100=1560001200000 \times 13 / 100 = 156000.

// دینارەکان تەواو دەهێڵێتەوە: 1200000×13/100=1560001200000 \times 13 / 100 = 156000.

Lineدێڕی 14

Two values after return: Python packs them into one tuple.

دوو نرخ دوای return: Python دەیانپێچێتەوە لە یەک .

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

MistakeهەڵەWhat happensچی ڕوو دەداتFixچارەسەر
Forgetting return (the result stays in a local variable)لەبیرکردنی return (ئەنجامەکە لە دەمێنێتەوە)The caller gets None None وەردەگرێتEnd with return result.بە return result کۆتایی پێبهێنە.
A branch without returnلقێک بەبێ returnNone only for some inputsNone تەنها بۆ هەندێک Add else: return …, or one return at the end.else: return … زیاد بکە، یان یەک return لە کۆتاییدا.
Printing inside the function when the caller needs the valueچاپکردن لەناو کاتێک پێویستی بە نرخەکەیەThe value cannot be used in calculationsنرخەکە لە ژمێرکاریدا بەکار نایەتreturn it; let the caller print.بیگەڕێنەوە؛ با چاپی بکات.
Code after return in the same blockکۆد دوای return لە هەمان بلۆکداIt never runsهەرگیز جێبەجێ نابێتMove it before the return.بیبە پێش return.
Calling a value-returning function as a statementبانگکردنی وەک The returned value is thrown away فڕێ دەدرێتStore it or print it: v = cube_volume(3).هەڵیبگرە یان چاپی بکە: v = cube_volume(3).
> instead of >= at a boundary> لەبری >= لە سنوورێکدا80 gets C instead of B⁦80 C⁩ وەردەگرێت لەبری BTest the boundary values themselves.خودی نرخەکانی سنوور تاقی بکەرەوە.
No colon after def … or if …نەبوونی دوو خاڵ دوای def … یان if …SyntaxError: expected ':'SyntaxError: expected ':'End headers with :.سەردێڕەکان بە : کۆتایی پێبهێنە.
A returned value nobody usesنرخێکی گەڕاوە کە کەس بەکاری ناهێنێتignored.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def cube_volume(side_length):
    return side_length ** 3


cube_volume(3)          # the value 27 is thrown away
print("done")

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

ExerciseڕاهێنانEven or not?جووتە یان نا؟

Write a function is_even(n) that returns True if n is even and False otherwise. Use it in an if.

بە ناوی is_even(n) بنووسە کە ئەگەر n جووت بوو True بگەڕێنێتەوە و ئەگەر نا False. لەناو ifـێکدا بەکاری بهێنە.

Hintئاماژە

n % 2 == 0 is already True or False — return it directly.

n % 2 == 0 خۆی True یان Falseـە — ڕاستەوخۆ بیگەڕێنەوە.

Show answerوەڵامەکە پیشان بدە
is_even.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def is_even(n):
    return n % 2 == 0


print(is_even(10))
print(is_even(7))
if is_even(4):
    print("4 is even")

The same pattern tests any divisor: n % 7 == 0 is True exactly when 7 divides n, so is_divisible_by_7(n) is one line too.

هەمان شێوە هەر دابەشکەرێک تاقی دەکاتەوە: n % 7 == 0 تەنها کاتێک Trueـە کە 7 بە تەواوی n دابەش بکات، بۆیە is_divisible_by_7(n)ـیش یەک دێڕە.

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

This program should print 12. It prints None. Why? Fix it.

ئەم دەبێت ⁦12⁩ چاپ بکات. None چاپ دەکات. بۆچی؟ چاکی بکەرەوە.

area_bug.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def rectangle_area(width, height):
    area = width * height


print(rectangle_area(3, 4))
Show answerوەڵامەکە پیشان بدە
Outputدەرئەنجام
None

The function computes area but never returns it, so it falls off the end and returns None. Add return area:

area دەژمێرێت بەڵام هەرگیز نایگەڕێنێتەوە، بۆیە دەگاتە کۆتایی و None دەگەڕێنێتەوە. return area زیاد بکە:

area_fixed.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def rectangle_area(width, height):
    area = width * height
    return area


print(rectangle_area(3, 4))
ExerciseڕاهێنانAbsolute value with an early returnنرخی ڕووت بە returnـێکی زوو

Write absolute(n) that returns -n when n is negative, and n otherwise. Use an early return for the negative case.

absolute(n) بنووسە کە کاتێک n سالب بوو -n بگەڕێنێتەوە و ئەگەر نا n. بۆ حاڵەتی سالب returnـێکی زوو بەکار بهێنە.

Show answerوەڵامەکە پیشان بدە
absolute.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def absolute(n):
    if n < 0:
        return -n
    return n


print(absolute(-7), absolute(5), absolute(0))

Python already has this as the built-in abs() (see the built-in toolbox); writing it yourself is good practice for early returns.

Python ئەمەی وەک بە ناوی abs() هەیە (بڕوانە سندوقی ئامرازی کردارە ئامادەکان)؛ نووسینی بە خۆت ڕاهێنانێکی باشە بۆ returnـی زوو.

ExerciseڕاهێنانA traffic light in two functionsگڵۆپی هاتووچۆ بە دوو کردار

Write light_code(colour), which returns a number for a traffic-light colour (0 red, 1 yellow, 2 green, −1-1 anything else), and advice(code), which returns the message for the driver. Call them together: advice(light_code("red")).

light_code(colour) بنووسە کە ژمارەیەک بۆ ڕەنگی گڵۆپی هاتووچۆ بگەڕێنێتەوە (⁦0⁩ سوور، 1 زەرد، 2 سەوز، −1-1 بۆ هەر شتێکی تر) و advice(code) کە پەیامەکە بۆ شۆفێر بگەڕێنێتەوە. پێکەوە بانگیان بکە: advice(light_code("red")).

Hintئاماژە

colour.upper() makes "Red", "red" and "RED" the same. Every branch of both functions needs a return, including the last one.

colour.upper() وا دەکات "Red"، "red" و "RED" وەک یەک بن. هەموو لقێکی هەردوو پێویستی بە return هەیە، دوایین لقیش.

Show answerوەڵامەکە پیشان بدە
traffic.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def light_code(colour):
    """Return 0 for red, 1 for yellow, 2 for green and -1 for anything else."""
    colour = colour.upper()
    if colour == "RED":
        return 0
    elif colour == "YELLOW":
        return 1
    elif colour == "GREEN":
        return 2
    return -1


def advice(code):
    """Turn a light code into a message for the driver."""
    if code == 0:
        return "Stop and wait."
    elif code == 1:
        return "Slow down and get ready to stop."
    elif code == 2:
        return "Go, but watch for people crossing."
    return "Unknown light: drive carefully."


print("red ->", advice(light_code("red")))
print("Green ->", advice(light_code("Green")))
print("yellow ->", advice(light_code("yellow")))
print("blue ->", advice(light_code("blue")))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 10

The last return covers every other colour, so the function never falls off its end.

دوایین return هەموو ڕەنگەکانی تر دەگرێتەوە، بۆیە هەرگیز بەبێ نرخ ناگاتە کۆتایی.

Lineدێڕی 24

The return value of light_code becomes the argument of advice.

light_code دەبێتە advice.

Splitting the work this way keeps each function small: one decides, the other explains. A traffic-control program could use light_code without ever showing a message.

دابەشکردنی کارەکە بەم شێوەیە هەر بچووک دەهێڵێتەوە: یەکێکیان بڕیار دەدات و ئەوی تر ڕوون دەکاتەوە. کۆنترۆڵی هاتووچۆ دەتوانێت light_code بەکار بهێنێت بەبێ ئەوەی هەرگیز پەیامێک پیشان بدات.

Quick checkپشکنینی خێراA function has if n > 0: return "positive" and elif n < 0: return "negative", and nothing else. What does it return for 0? if n > 0: return "positive" و elif n < 0: return "negative"ـی تێدایە و هیچی تر. بۆ 0 چی دەگەڕێنێتەوە؟

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

Exercises: formulas as functionsڕاهێنان: فۆرمولەکان وەک کردار

A formula with inputs and one result is a perfect value-returning function: the inputs become parameters, the formula goes after return.

کە چەند و یەک ئەنجامی هەیە بە تەواوی دەبێتە : دەبنە و دوای return دێت.

ExerciseڕاهێنانWhat kind of roots?چ جۆرە چارەسەرێک؟

For the quadratic equation ax2+bx+c=0ax^2 + bx + c = 0, the number D=b2−4acD = b^2 - 4ac (the discriminant) tells how many real roots there are: two if D>0D > 0, one if D=0D = 0, none if D<0D < 0. Write discriminant(a, b, c) and kind_of_roots(a, b, c), which calls it.

بۆ ax2+bx+c=0ax^2 + bx + c = 0، ژمارەی D=b2−4acD = b^2 - 4ac (discriminant) دەڵێت چەند چارەسەری لەناو هەیە: دوو ئەگەر D>0D > 0، یەک ئەگەر D=0D = 0، هیچ ئەگەر D<0D < 0. discriminant(a, b, c) و kind_of_roots(a, b, c) بنووسە کە ئەوی یەکەم بانگ دەکات.

Show answerوەڵامەکە پیشان بدە
roots.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def discriminant(a, b, c):
    """Return b**2 - 4*a*c for the equation a*x**2 + b*x + c = 0."""
    return b ** 2 - 4 * a * c


def kind_of_roots(a, b, c):
    d = discriminant(a, b, c)
    if d > 0:
        return "two different real roots"
    elif d == 0:
        return "one repeated real root"
    else:
        return "no real roots"


print(discriminant(1, -3, 2), kind_of_roots(1, -3, 2))
print(discriminant(1, -4, 4), kind_of_roots(1, -4, 4))
print(discriminant(1, 2, 5), kind_of_roots(1, 2, 5))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-3

The formula goes straight after return.

ڕاستەوخۆ دوای return دێت.

Lineدێڕی 6-7

One function uses another's return value.

تر بەکار دەهێنێت.

x2−3x+2:  D=9−8=1>0x2−4x+4:  D=16−16=0x2+2x+5:  D=4−20=−16<0\begin{aligned} x^2 - 3x + 2 &: \; D = 9 - 8 = 1 > 0 \\ x^2 - 4x + 4 &: \; D = 16 - 16 = 0 \\ x^2 + 2x + 5 &: \; D = 4 - 20 = -16 < 0 \end{aligned}

The three test equations, checked by hand.

سێ تاقیکراوەکە، بە دەست پشکنراون.

ExerciseڕاهێنانSavings that grow every yearپاشەکەوتێک کە هەموو ساڵێک گەورە دەبێت

When a bank adds rr % to an amount PP nn times a year, after tt years the amount is A=P(1+r/100n)ntA = P\left(1 + \frac{r/100}{n}\right)^{nt} (compound interest). Write final_amount(principal, rate, years, times_per_year) and find the amount for 1,000,000 dinars at 5 % for 3 years, added once a year and twelve times a year.

کاتێک بانکێک rr٪ دەخاتە سەر بڕە پارەیەکی PP، nn جار لە ساڵێکدا، دوای tt ساڵ بڕەکە دەبێتە A=P(1+r/100n)ntA = P\left(1 + \frac{r/100}{n}\right)^{nt} (بە ئینگلیزی: compound interest). final_amount(principal, rate, years, times_per_year) بنووسە و بڕەکە بۆ 1٬⁦000⁩٬⁦000⁩ دینار بە 5٪ بۆ 3 ساڵ بدۆزەوە، جارێک لە ساڵێکدا و دوازدە جار لە ساڵێکدا.

Hintئاماژە

Turn the percentage into a fraction first: r = rate / 100. ** raises to a power.

سەرەتا بکە بە : r = rate / 100. ** بەرز دەکاتەوە بۆ .

Show answerوەڵامەکە پیشان بدە
savings.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def final_amount(principal, rate, years, times_per_year):
    """Money after `years` years when `rate` % is added times_per_year times a year."""
    r = rate / 100
    n = times_per_year
    return principal * (1 + r / n) ** (n * years)


print(round(final_amount(1000000, 5, 3, 1)))
print(round(final_amount(1000000, 5, 3, 12)))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5

The whole formula in one return.

هەموو لە یەک returnـدا.

Lineدێڕی 8-9

round() with no second argument gives whole dinars.

round() بەبێ دووەم دیناری تەواو دەدات.

1000000×1.053=11576251000000 \times 1.05^{3} = 1157625

Added once a year: 5 % on top of the previous year's amount, three times.

جارێک لە ساڵێکدا: 5٪ لەسەر بڕی ساڵی پێشوو، سێ جار.

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

Summaryپوختە

  • return states a function's result. It can return any expression, and the call is replaced by that value.
  • return ends the function at once; this is handy for special cases at the start. Code after it in the same block never runs.
  • Every branch should return a value. A function that falls off its end returns None — Python does not warn you.
  • A function without a return value performs actions (such as printing) and is called as a statement; it returns None.
  • Return values to the program; print messages for people. A returning function can be reused in calculations.
  • Test for None with is None. To return several values, return a tuple and unpack it.
  • return ئەنجامی دیاری دەکات. دەتوانێت هەر بگەڕێنێتەوە و بانگکردنەکە بەو نرخە دەگۆڕدرێت.
  • return یەکسەر کۆتایی پێدێنێت؛ ئەمە بۆ حاڵەتە تایبەتەکانی سەرەتا بەسوودە. کۆدی دوای ئەو لە هەمان بلۆکدا هەرگیز جێبەجێ نابێت.
  • دەبێت هەموو لقێک نرخێک بگەڕێنێتەوە. کە دەگاتە کۆتایی جەستەکەی None دەگەڕێنێتەوە — Python ئاگادارت ناکاتەوە.
  • کارێک ئەنجام دەدات (وەک چاپکردن) و وەک بانگ دەکرێت؛ None دەگەڕێنێتەوە.
  • نرخ بۆ بگەڕێنەوە؛ پەیام بۆ مرۆڤ چاپ بکە. دەتوانرێت لە ژمێرکاریدا دووبارە بەکار بهێنرێتەوە.
  • بە is None بۆ None بپشکنە. بۆ گەڕاندنەوەی چەند نرخێک، بگەڕێنەوە و جیای بکەرەوە.
Review questionsپرسیارەکانی پێداچوونەوە
What does a function return if no return statement runs?ئەگەر هیچ ڕستەیەکی return جێبەجێ نەبێت، کردارێک چی دەگەڕێنێتەوە؟

None.

None.

Why is return better than print inside pyramid_volume?بۆچی return لەناو pyramid_volumeـدا لە print باشترە؟

The caller gets the number and can add, round or reuse it; with print it gets None.

ژمارەکە وەردەگرێت و دەتوانێت کۆی بکاتەوە، بۆ بکات یان دووبارە بەکاری بهێنێتەوە؛ بە print None وەردەگرێت.

Which two ways of fixing "not every branch returns" did the slides show?سلایدەکان کام دوو ڕێگەیان بۆ چاککردنی «هەموو لقێک ناگەڕێنێتەوە» پیشان دا؟

A return in every branch (if … return … / else: return …), or a variable set in each branch and one return at the end.

returnـێک لە هەموو لقێکدا (if … return … / else: return …)، یان کە لە هەر لقێکدا نرخ وەردەگرێت و یەک return لە کۆتاییدا.

Next: Positional, Keyword and Default Arguments — more ways to pass values into a function.

دواتر: ئارگیومێنتە شوێنییەکان، ئارگیومێنتە ناودارەکان و نرخە بنەڕەتییەکان — ڕێگەی زیاتر بۆ ناردنی نرخ بۆ ناو .

Videoڤیدیۆ

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

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

Return Statement | Python | Tutorial 15Giraffe Academy · Englishئینگلیزی · 273K viewsبینین · 7.8K likesلایک

How return sends a value back to the caller, storing that value in a variable, and why code after return never runs.

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

Whole video (6:15). Chapters: 1:04 creating a function, 3:05 using return, 4:07 storing the result, 4:56 return ends the function.

هەموو ڤیدیۆکە ⁦(6:15)⁩. بەشەکان: ⁦1:04⁩ دروستکردنی ، ⁦3:05⁩ بەکارهێنانی return، ⁦4:07⁩ هەڵگرتنی ئەنجامەکە، ⁦4:56⁩ return کۆتایی پێدەهێنێت.

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

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

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

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

Positional, Keyword and Default Argumentsئارگیومێنتە شوێنییەکان، ئارگیومێنتە ناودارەکان و نرخە بنەڕەتییەکان

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

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