PythonPython · Chapterبەش 8 · Lectureوانە 8.3
Positional, Keyword and Default Argumentsئارگیومێنتە شوێنییەکان، ئارگیومێنتە ناودارەکان و نرخە بنەڕەتییەکان
How Python matches arguments to parameters by position or by name, how to mix the two safely, what default values are and where they may stand, why a default is made only once (and the None idiom), with Lab 2's repeat-a-message task and a pyramid whose arguments must not be swapped.
Python چۆن بەپێی شوێن یان بەپێی ناو لەگەڵ دەگونجێنێت، چۆن هەردووکیان بە سەلامەتی تێکەڵ بکەیت، چین و لە کوێ دادەنرێن، بۆچی تەنها یەک جار دروست دەکرێت (و ڕێگای None)، لەگەڵ ئەرکی دووبارەکردنەوەی پەیامی تاقیگەی 2 و هەرەمێک کە نابێت شوێنی بگۆڕدرێت.
What you will learnچی فێر دەبیت
- Call a function with positional arguments and explain why order, number and type must fit.
- Use keyword arguments to pass values by name, in any order, and to make calls clear.
- Mix positional and keyword arguments correctly and read the errors when the rules are broken.
- Give parameters default values, put them in the right place, and avoid the shared-list trap with
None.
- بە بانگ بکەیت و ڕوونی بکەیتەوە بۆچی ڕیزبەندی، ژمارە و جۆر دەبێت بگونجێن.
- بەکار بهێنیت بۆ ناردنی نرخ بەپێی ناو، بە هەر ڕیزبەندییەک بێت، هەروەها بۆ ڕوونکردنەوەی بانگکردنەکان.
- و بە دروستی تێکەڵ بکەیت و بخوێنیتەوە کاتێک یاساکان دەشکێنرێن.
- بدەیتە ، لە شوێنی دروستدا دایانبنێیت و بە
Noneخۆت لە تەڵەی هاوبەش بپارێزیت.
How arguments reach parametersئارگیومێنتەکان چۆن دەگەنە پارامیتەرەکان
The power of a function is that it works with parameters. You write the function once, and each call gives it new values to work on. When you call a function, Python passes your arguments to its parameters. (Parameter = the name in the header; argument = the value in the call. See Parameters and arguments.)
هێزی لەوەدایە کە لەگەڵ کار دەکات. یەک جار دەنووسیت و هەر بانگکردنێک نوێی پێ دەدات بۆ ئەوەی کاریان لەسەر بکات. کاتێک بانگ دەکەیت، Python دەداتە . ( = ئەو ناوەی لە سەردێڕەکەدایە؛ = ئەو نرخەی لە بانگکردنەکەدایە. بڕوانە پارامیتەرەکان و ئارگیومێنتەکان.)
Python can match arguments to parameters in two ways. A is matched by its place in the call: the first argument goes to the first parameter. A is matched by name: you write the parameter's name, an equals sign and the value. This lesson teaches both, how to mix them, and how a parameter can get a when you leave its argument out.
Python بە دوو ڕێگە لەگەڵ دەگونجێنێت. بەپێی شوێنەکەی لە بانگکردنەکەدا دەگونجێنرێت: یەکەم دەچێتە یەکەم . بەپێی ناو دەگونجێنرێت: ناوی ، نیشانەی یەکسان و نرخەکە دەنووسیت. ئەم وانەیە هەردووکیان فێر دەکات، چۆن تێکەڵیان بکەیت و چۆن وەردەگرێت کاتێک نانێریت.
How arguments reach parametersئارگیومێنتەکان چۆن دەگەنە پارامیتەرەکان
An everyday picture: handing back exam papersوێنەیەکی ڕۆژانە: گەڕاندنەوەی پەڕەی تاقیکردنەوە
After an exam the teacher hands back the marked papers. In one class she walks along the seats and gives the first paper to the first seat, the second paper to the second seat, and so on. That is how positional arguments work: only the order counts. If the papers are in the wrong order, Aram gets Shilan's paper, and nobody notices anything. In another class every paper has the student's name on top, so the teacher can hand them out in any order and each paper still reaches its owner. That is how keyword arguments work.
دوای تاقیکردنەوەیەک مامۆستا پەڕە ڕاستکراوەکان دەگەڕێنێتەوە. لە پۆلێکدا بەلای کورسییەکاندا دەڕوات: یەکەم پەڕە دەداتە یەکەم کورسی، دووەم پەڕە دەداتە دووەم کورسی و هەتا کۆتایی. بەم جۆرە کار دەکەن: تەنها ڕیزبەندی گرنگە. ئەگەر پەڕەکان تێکچووبن، پەڕەی شیلان دەکەوێتە دەستی ئارام و هیچ کەسێکیش هەست بە هیچ ناکات. لە پۆلێکی تردا ناوی قوتابی لەسەر هەر پەڕەیەک نووسراوە، بۆیە مامۆستا دەتوانێت بە هەر ڕیزبەندییەک بیانبەخشێتەوە و هەر پەڕەیەک دەگاتە خاوەنی خۆی. بەم جۆرە کار دەکەن.
Where the analogy stops workingسنووری ئەم نموونەیە
In Python a name that matches no parameter is an error at once (TypeError), not a paper left on the desk. Python also has a rule the classroom does not have: positional arguments must come before keyword arguments.
لە Pythonـدا ناوێک کە لەگەڵ هیچ نەگونجێت یەکسەر (TypeError)، نەک پەڕەیەک کە لەسەر مێزەکە بمێنێتەوە. هەروەها Python یاسایەکی هەیە کە پۆل نییەتی: دەبێت پێش بێن.
Positional arguments: by orderئارگیومێنتە شوێنییەکان: بەپێی ڕیزبەندی
Positional arguments must be passed in the same order as their parameters in the function header. They must also match the parameters in number (one argument for each parameter) and in type (a value the function can work with).
دەبێت بە هەمان ڕیزبەندیی لە بنێردرێن. هەروەها دەبێت لە ژمارەدا لەگەڵ بگونجێن (بۆ هەر یەک ) و لە جۆرداش (نرخێک کە بتوانێت کاری لەسەر بکات).
def n_println(message, n):
for i in range(n):
print(message)
n_println("a", 3) # positional: "a" -> message, 3 -> na a a
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Two parameters:
messagefirst,nsecond.دوو : یەکەم
message، دووەمn.- Lineدێڕی 6
"a"is first, so it goes tomessage; 3 is second, so it goes ton."a"یەکەمە، بۆیە دەچێتەmessage؛ 3 دووەمە، بۆیە دەچێتەn.
Positional arguments: by orderئارگیومێنتە شوێنییەکان: بەپێی ڕیزبەندی
When the order or the number is wrongکاتێک ڕیزبەندی یان ژمارەی ئارگیومێنتەکان هەڵە بێت
Swap the two arguments and message receives the number 3 while n receives the text "a". range() needs a whole number, so the program stops with a TypeError:
ئەگەر شوێنی دوو بگۆڕیتەوە، message ژمارە 3 وەردەگرێت و n دەقی "a". range() پێویستی بە ، بۆیە بە TypeError دەوەستێت:
def n_println(message, n):
for i in range(n):
print(message)
n_println(3, "a") # the order is swappedTraceback (most recent call last):
File "wrong_order.py", line 6, in <module>
n_println(3, "a") # the order is swapped
^^^^^^^^^^^^^^^^^
File "wrong_order.py", line 2, in n_println
for i in range(n):
^^^^^^^^
TypeError: 'str' object cannot be interpreted as an integerWith too few arguments, Python does not even start the body. It names the parameter that got nothing:
ئەگەر کەم بن، Python تەنانەت دەست بە جەستەی ناکات. ناوی ئەو دەڵێت کە هیچی وەرنەگرتووە:
def n_println(message, n):
for i in range(n):
print(message)
n_println("a") # one argument is missingTraceback (most recent call last):
File "too_few.py", line 6, in <module>
n_println("a") # one argument is missing
^^^^^^^^^^^^^^
TypeError: n_println() missing 1 required positional argument: 'n'Positional arguments: by orderئارگیومێنتە شوێنییەکان: بەپێی ڕیزبەندی
A silent mistake: the pyramidهەڵەیەکی بێدەنگ: هەرەمەکە
A wrong order is worse when both values are numbers: Python finds nothing wrong, and you get a wrong answer. Lab 2 asks for the volume of a pyramid with a square base for the pairs (9, 10), (0, 10) and (3, 12), but the sheet never says which number is the height. Look what the order does:
ڕیزبەندیی هەڵە خراپتر دەبێت کاتێک هەردوو نرخەکە ژمارە بن: Python هیچ کێشەیەک نابینێت و وەڵامێکی هەڵە وەردەگریت. تاقیگەی 2 قەبارەی هەرەمێکی بنکە چوارگۆشە بۆ جووتەکانی (9, 10)، (0, 10) و (3, 12) دەخوازێت، بەڵام پەڕەکە هەرگیز ناڵێت کام ژمارە بەرزییەکەیە. سەیر بکە ڕیزبەندی چی دەکات:
def pyramid_volume(height, base_length):
base_area = base_length * base_length
return height * base_area / 3
print(pyramid_volume(9, 10)) # height 9, base length 10
print(pyramid_volume(10, 9)) # swapped: a different pyramid!
print(pyramid_volume(height=9, base_length=10))
print(pyramid_volume(base_length=10, height=9))300.0 270.0 300.0 300.0
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 7
Swapped: Python calculates a pyramid of height 10 and base 9. No error message, just a different number — a .
پێچەوانە: Python هەرەمێک بە بەرزیی 10 و بنکەی 9 دەژمێرێت. هیچ پەیامێکی هەڵە نییە، تەنها ژمارەیەکی جیاواز — .
- Lineدێڕی 8-9
Keyword arguments say which number is which, in any order. The call explains itself.
دەڵێن کام ژمارە کامەیە، بە هەر ڕیزبەندییەک بێت. بانگکردنەکە خۆی ڕوون دەکاتەوە.
So when a function has several parameters of the same kind, keyword arguments make a call much easier to read: pyramid_volume(height=9, base_length=10) cannot be misunderstood. The full Lab 2 pyramid task is solved in Return Values: the pyramid, two ways.
بۆیە کاتێک چەند هاوجۆری هەیە، خوێندنەوەی بانگکردنەکە زۆر ئاسانتر دەکەن: pyramid_volume(height=9, base_length=10) بە هەڵە تێناگەیەنرێت. ئەرکی تەواوی هەرەمی تاقیگەی 2 لە نرخە گەڕاوەکان: هەرەمەکە بە دوو ڕێگە چارەسەر کراوە.
Keyword arguments: by nameئارگیومێنتە ناودارەکان: بەپێی ناو
A keyword argument is written in the form name=value: the parameter's name, an equals sign, then the value. Because each value carries its parameter's name, the arguments can appear in any order.
بە شێوەی name=value دەنووسرێت: ناوی ، نیشانەی یەکسان، پاشان نرخەکە. لەبەر ئەوەی هەر نرخێک ناوی لەگەڵدایە، دەتوانن بە هەر ڕیزبەندییەک بێن.
def n_println(message, n):
for i in range(n):
print(message)
n_println(n=5, message="good") # keyword arguments, any ordergood good good good good
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 6
n=5is written first, but it still goes to the parameter calledn.message="good"goes tomessage.n=5یەکەم نووسراوە، بەڵام هەر دەچێتە ئەو ناویnـە.message="good"دەچێتەmessage.
Keyword arguments name the parameter, so their order does not matter; print's end= and sep= are keyword arguments too.
ناوی دەهێنن، بۆیە ڕیزبەندییان گرنگ نییە؛ end= و sep= لە printـدا هەروەها .
Whole video (6:44). Chapters: 0:00 example 1, 3:20 example 2, 4:36 exercise.
هەموو ڤیدیۆکە (6:44). بەشەکان: 0:00 نموونەی 1، 3:20 نموونەی 2، 4:36 ڕاهێنان.
Mixing positional and keyword argumentsتێکەڵکردنی ئارگیومێنتە شوێنییەکان و ئارگیومێنتە ناودارەکان
You can mix the two kinds in one call, but the positional arguments cannot appear after any keyword argument. Take a function def f(p1, p2, p3):. These calls are fine:
دەتوانیت لە یەک بانگکردندا هەردوو جۆرەکە تێکەڵ بکەیت، بەڵام ناتوانن دوای هیچ بێن. وەک def f(p1, p2, p3): بهێنە بەرچاو. ئەم بانگکردنانە دروستن:
def f(p1, p2, p3):
print(p1, p2, p3)
f(30, p2=4, p3=10) # one positional, then two keyword arguments
f(30, p3=10, p2=4) # keyword arguments in any order
f(30, 4, p3=10) # two positional, then one keyword30 4 10 30 4 10 30 4 10
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
30 is positional, so it goes to
p1;p2andp3are filled by name.30 شوێنییە، بۆیە دەچێتە
p1؛p2وp3بەپێی ناو پڕ دەکرێنەوە.- Lineدێڕی 7
Two positional arguments (
p1,p2), then one keyword argument.دوو (
p1،p2)، پاشان یەک .
But this call is refused before the program even starts:
بەڵام ئەم بانگکردنە پێش ئەوەی دەست پێبکات ڕەت دەکرێتەوە:
def f(p1, p2, p3):
print(p1, p2, p3)
f(30, p2=4, 10) # a positional argument after a keyword argument File "mix_bad.py", line 5
f(30, p2=4, 10) # a positional argument after a keyword argument
^
SyntaxError: positional argument follows keyword argumentWhy? After p2=4, Python no longer knows which parameter the bare 10 belongs to: positions only make sense while they are counted from the start. So Python treats it as a and refuses the whole file.
بۆچی؟ دوای p2=4، Python چیتر نازانێت ئەو 10ـە بێناوە هی کام : شوێنەکان تەنها کاتێک واتایان هەیە کە لە سەرەتاوە بژمێردرێن. بۆیە Python بە دەیزانێت و هەموو فایلەکە ڕەت دەکاتەوە.
Mixing positional and keyword argumentsتێکەڵکردنی ئارگیومێنتە شوێنییەکان و ئارگیومێنتە ناودارەکان
Two more rules for keyword argumentsدوو یاسای تر بۆ ئارگیومێنتە ناودارەکان
Each parameter gets exactly one value. If a value has already reached a parameter by position, you cannot give it a second value by name:
هەر ڕێک یەک نرخ وەردەگرێت. ئەگەر نرخێک پێشتر بەپێی شوێن گەیشتبێتە ، ناتوانیت بەپێی ناو نرخێکی دووەمی پێ بدەیت:
def f(p1, p2, p3):
print(p1, p2, p3)
f(30, p1=5, p3=10) # p1 gets 30 by position AND 5 by nameTraceback (most recent call last):
File "twice.py", line 5, in <module>
f(30, p1=5, p3=10) # p1 gets 30 by position AND 5 by name
^^^^^^^^^^^^^^^^^^
TypeError: f() got multiple values for argument 'p1'Every name must match a parameter. A misspelt or unknown name is not ignored:
هەموو ناوێک دەبێت لەگەڵ بگونجێت. ناوێکی هەڵە نووسراو یان نەناسراو پشتگوێ ناخرێت:
def f(p1, p2, p3):
print(p1, p2, p3)
f(30, p2=4, p4=10) # there is no parameter called p4Traceback (most recent call last):
File "unknown_name.py", line 5, in <module>
f(30, p2=4, p4=10) # there is no parameter called p4
^^^^^^^^^^^^^^^^^^
TypeError: f() got an unexpected keyword argument 'p4'From Python 3.13 the message also suggests a name, here Did you mean 'p1'?. Check which name you really meant.
لە Python 3.13ـەوە پەیامەکە ناوێکیش پێشنیار دەکات، لێرەدا Did you mean 'p1'?. بپشکنە کە بەڕاستی مەبەستت کام ناو بوو.
| Ruleیاسا | Wrong callبانگکردنی هەڵە | What Python saysPython چی دەڵێت |
|---|---|---|
| Positional arguments first, keyword arguments afterسەرەتا ، پاشان | f(30, p2=4, 10) | SyntaxError: positional argument follows keyword argument |
| One value per parameterبۆ هەر یەک نرخ | f(30, p1=5, p3=10) | TypeError: f() got multiple values for argument 'p1' |
| Names must match parametersناوەکان دەبێت لەگەڵ بگونجێن | f(30, p2=4, p4=10) | TypeError: f() got an unexpected keyword argument 'p4' |
| Every parameter without a default needs a valueهەر کە نییە پێویستی بە نرخە | f(30, p3=10) | TypeError: f() missing 1 required positional argument: 'p2' |
Default argument valuesنرخە بنەڕەتییەکانی ئارگیومێنتەکان
Python allows you to define functions with default argument values. In the header you write parameter=value. When the function is invoked without that argument, the default value is passed to the parameter.
Python ڕێگە دەدات بە بناسێنیت. لە سەردێڕەکەدا parameter=value دەنووسیت. کاتێک بەبێ ئەو بانگ دەکرێت، دەدرێتە .
A value that is used automatically when none is given. A function can have one, used when the caller leaves that out: def greet(name="guest"): in Python, function greet($name = "guest") in PHP. A database can have one too, stored in every new record that leaves the field empty.
کە خۆکارانە بەکار دێت کاتێک هیچ نرخێک نەدرابێت. دەتوانێت هەیبێت، کە بەکار دێت کاتێک بانگکەر ئەو نانێرێت: لە Pythonـدا def greet(name="guest"): و لە PHPـدا function greet($name = "guest"). دەتوانێت هەیبێت، کە لە هەموو تۆمارێکی نوێدا هەڵدەگیرێت ئەگەر ئەو ستوونە بەتاڵ بهێڵرێتەوە.
def print_area(width=1, height=2):
area = width * height
print("width:", width, "\theight:", height, "\tarea:", area)
print_area() # default arguments width = 1 and height = 2
print_area(4, 2.5) # positional arguments width = 4 and height = 2.5
print_area(height=5, width=3) # keyword arguments width = 3 and height = 5
print_area(width=1.2) # default height = 2
print_area(height=6.2) # default width = 1width: 1 height: 2 area: 2 width: 4 height: 2.5 area: 10.0 width: 3 height: 5 area: 15 width: 1.2 height: 2 area: 2.4 width: 1 height: 6.2 area: 6.2
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Both parameters have defaults:
widthis 1 andheightis 2 unless the call says otherwise.هەردوو هەیە:
width1ـە وheight2ـە، مەگەر بانگکردنەکە شتێکی تر بڵێت.- Lineدێڕی 3
"\t"is the tab : it jumps to the next column, so the output lines up."\t"tabـە: بۆ ستوونی داهاتوو باز دەدات، بۆیە ڕێک دەکەوێت.- Lineدێڕی 7
4 * 2.5gives10.0, not10: a calculation with a gives a float.4 * 2.5دەکاتە10.0نەک10: ئەنجامی ژماردن لەگەڵ .
| Callبانگکردن | width | height | Howچۆن |
|---|---|---|---|
print_area() | 1 | 2 | both defaultsهەردووکیان |
print_area(4, 2.5) | 4 | 2.5 | both by positionهەردووکیان بەپێی شوێن |
print_area(height=5, width=3) | 3 | 5 | both by name, in any orderهەردووکیان بەپێی ناو، بە هەر ڕیزبەندییەک |
print_area(width=1.2) | 1.2 | 2 | width by name, height defaultwidth بەپێی ناو، height |
print_area(height=6.2) | 1 | 6.2 | height by name, width defaultheight بەپێی ناو، width |
Giving parameters default values, like discount=0 and tax=0.05, so a call may leave those arguments out or replace them.
دانانی بۆ ، وەک discount=0 و tax=0.05، بۆ ئەوەی لە بتوانیت ئەو نەنێریت یان بیانگۆڕیت.
Whole video (6:06): a net_price function with discount=0 and tax=0.05, then a counting exercise.
هەموو ڤیدیۆکە (6:06): net_price بە discount=0 و tax=0.05، پاشان ڕاهێنانێکی ژماردن.
Default argument valuesنرخە بنەڕەتییەکانی ئارگیومێنتەکان
Watch the parameters fill upسەیری پڕبوونەوەی پارامیتەرەکان بکە
The animation runs five calls of print_area. Watch where each parameter gets its value from: a value in the call (by position or by name) or the default in the header.
ئەنیمەیشنەکە پێنج بانگکردنی print_area پیشان دەدات. سەیر بکە هەر نرخەکەی لە کوێوە وەردەگرێت: لە نرخێکی ناو بانگکردنەکە (بەپێی شوێن یان بەپێی ناو) یان لە ناو سەردێڕەکە.


Default argument valuesنرخە بنەڕەتییەکانی ئارگیومێنتەکان
Where defaults may standنرخە بنەڕەتییەکان لە کوێ دادەنرێن
A function may have some parameters with defaults and some without. The parameters without a default must come first, because they always need an argument and are filled by position from the left:
دەتوانێت هەندێک بە و هەندێکی بەبێ ئەو هەبێت. ئەو نییە دەبێت یەکەم بن، چونکە هەمیشە پێویستیان بە هەیە و بەپێی شوێن لە چەپەوە پڕ دەکرێنەوە:
def greet(greeting="Hello", name):
print(f"{greeting}, {name}!") File "default_first.py", line 1
def greet(greeting="Hello", name):
^^^^
SyntaxError: parameter without a default follows parameter with a defaultdef greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Shilan") # greeting uses its default
greet("Karwan", "Good morning") # both positional
greet(greeting="Welcome", name="Dilan") # both by nameHello, Shilan! Good morning, Karwan! Welcome, Dilan!
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
nameis required;greetingis optional because it has a default.nameپێویستە؛greetingئارەزوومەندانەیە چونکە هەیە.- Lineدێڕی 7
Keyword arguments can still be given in any order.
هێشتا دەتوانن بە هەر ڕیزبەندییەک بدرێن.
You have used defaults all along: print() has sep=" " and end="\n", and round() has an optional second parameter ndigits. You change only the ones you need, usually by name (more in print() options):
تۆ هەمیشە بەکار هێناوە: print() خاوەنی sep=" " و end="\n"ـە و round() دووەمی ئارەزوومەندانەی هەیە بە ناوی ndigits. تەنها ئەوانە دەگۆڕیت کە پێویستن، زۆرجار بەپێی ناو (زیاتر لە هەڵبژاردنەکانی print()):
print("tea", "sugar") # sep=" " and end="\n" by default
print("tea", "sugar", sep=", ") # change only sep
print(round(3.14159)) # ndigits left out
print(round(3.14159, 2)) # ndigits given by position
print(round(3.14159, ndigits=3)) # ndigits given by nametea sugar tea, sugar 3 3.14 3.142
Lab 2, Task 1: repeat a messageتاقیگەی 2، ئەرکی 1: دووبارەکردنەوەی پەیامێک
Write a function that prints any message you give it, as many times as you want. Give it 2 parameters with default values: the default message is TEST and the default number of repetitions is 10. Then call it three times: for the first line of output use the default arguments, for the second line positional arguments, and for the third line keyword arguments. The output must be:
بنووسە کە هەر پەیامێک کە پێی دەدەیت چەند جار بتەوێت چاپی بکات. 2 بە پێ بدە: پەیامی بنەڕەتی TESTـە و ژمارەی بنەڕەتیی دووبارەکردنەوە 10ـە. پاشان سێ جار بانگی بکە: بۆ یەکەم دێڕی بەکار بهێنە، بۆ دووەم دێڕ و بۆ سێیەم دێڕ . دەبێت ئەمە بێت:
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST lab 2 exercises lab 2 exercises lab 2 exercises Programming Programming Programming Programming Programming
Hintئاماژە
Inside the function, loop times times and print with end=" ". What must happen after the loop?
لەناو ، بنووسە کە times جار بخولێتەوە و بە end=" " چاپ بکات. دوای دەبێت چی ڕوو بدات؟
Show answerوەڵامەکە پیشان بدە
def repeat(message="TEST", times=10):
for i in range(times):
print(message, end=" ")
print() # end the line after the loop
repeat() # line 1: default arguments
repeat("lab 2 exercises", 3) # line 2: positional arguments
repeat(times=5, message="Programming") # line 3: keyword argumentsTEST TEST TEST TEST TEST TEST TEST TEST TEST TEST lab 2 exercises lab 2 exercises lab 2 exercises Programming Programming Programming Programming Programming
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Two parameters, both with defaults.
دوو ، هەردووکیان بە .
- Lineدێڕی 3
end=" "puts four spaces after each message instead of a new line.end=" "لەبری دێڕی نوێ چوار دوای هەر پەیامێک دادەنێت.- Lineدێڕی 4
After the loop, an empty
print()ends the line.دوای ،
print()ـێکی بەتاڵ دێڕەکە کۆتایی پێدێنێت.- Lineدێڕی 9
Keyword arguments, deliberately in the "wrong" order — it still works.
، بە ئەنقەست بە ڕیزبەندیی «هەڵە» — هێشتا کار دەکات.
Lab 2, Task 1: repeat a messageتاقیگەی 2، ئەرکی 1: دووبارەکردنەوەی پەیامێک
One student's solutionچارەسەری قوتابییەک
Here is a solution one student typed in class. It uses all three kinds of call correctly, but look at its output:
ئەمە چارەسەرێکە کە قوتابییەک لە پۆلدا نووسیویەتی. هەر سێ جۆری بانگکردن بە دروستی بەکار دەهێنێت، بەڵام سەیری بکە:
#Task 1 (A): Default Arguments
def a(message = "Test", repition = 10):
for i in range(repition):
print(message, end=" ")
a()
#Task 1 (B): Positional Arguments
a("lab 2 exercises", 3)
#Task 1 (C): Keyword Arguments
a(repition=5, message="Programming")Test Test Test Test Test Test Test Test Test Test lab 2 exercises lab 2 exercises lab 2 exercises Programming Programming Programming Programming Programming
Everything is on ONE line, and the next program's output would continue on the same line.
هەمووی لەسەر یەک دێڕە و دواتر لەسەر هەمان دێڕ بەردەوام دەبێت.
- No
print()after the loop.end=" "keeps every message on the same line, and nothing ever starts a new one. The lab wants three lines, so the function must end with an emptyprint(). "Test"instead of"TEST". Python strings are case-sensitive, so the default message does not match the task.- Names.
asays nothing about the job, andrepitionis misspelt (repetition). Descriptive names such asrepeatandtimesmake the calls readable — especially keyword calls, where the reader sees the parameter names.
- دوای هیچ
print()ـێک نییە.end=" "هەموو پەیامێک لەسەر هەمان دێڕ دەهێڵێتەوە و هیچ شتێک دێڕێکی نوێ دەست پێناکات. تاقیگەکە سێ دێڕ دەخوازێت، بۆیە دەبێت بەprint()ـێکی بەتاڵ کۆتایی بێت. "Test"لەبری"TEST". Python ، بۆیە پەیامە بنەڕەتییەکە لەگەڵ ئەرکەکە ناگونجێت.- ناوەکان.
aهیچ شتێک لەبارەی کارەکەوە ناڵێت وrepitionبە هەڵە نووسراوە (repetition). ناوی ڕوونکەرەوەی وەکrepeatوtimesبانگکردنەکان خوێندراو دەکەن — بە تایبەتی بانگکردنی ناودار، کە تێیدا خوێنەر ناوی دەبینێت.
A default value is made only onceنرخی بنەڕەتی تەنها یەک جار دروست دەکرێت
Python works out a default value once, when the def line runs — not again at every call. With a number this is easy to see: changing the variable later does not change the default.
Python یەک جار دەژمێرێت، کاتێک دێڕی def جێبەجێ دەبێت — نەک لە هەموو بانگکردنێکدا. لەگەڵ ژمارەدا ئەمە بە ئاسانی دەبینرێت: گۆڕینی دواتر ناگۆڕێت.
sugar = 2
def make_tea(sugars=sugar): # the default is worked out HERE, once
print("Tea with", sugars, "sugar cubes")
sugar = 4
make_tea() # still 2: the default was fixed when def ran
make_tea(sugar) # pass the new value if you want itTea with 2 sugar cubes Tea with 4 sugar cubes
With numbers and strings this never causes trouble, because they cannot be changed. With a list it becomes a trap: a list is , so the one default list made at def time is shared by every call that leaves the argument out, and items from earlier calls come back. The Lists chapter shows this trap and its fix in The shared default list.
لەگەڵ ژمارە و ئەمە هەرگیز کێشە دروست ناکات، چونکە ناگۆڕدرێن. لەگەڵ دەبێتە تەڵە: ، بۆیە ئەو یەک بنەڕەتییەی لە کاتی def دروست کراوە لە نێوان هەموو ئەو بانگکردنانەدا هاوبەشە کە نانێرن و دانەکانی بانگکردنە پێشووەکان دەگەڕێنەوە. بەشی ئەم تەڵەیە و چارەسەرەکەی لە لیستە بنەڕەتییە هاوبەشەکە پیشان دەدات.
Extra: making names compulsoryزیادە: ناچارکردنی ناو
A bare * in the header means: every parameter after it must be given by name. This protects calls where a bare value would be unclear. (A / does the opposite: parameters before it can only be given by position. You will mostly meet it in Python's own documentation, for example len(obj, /).)
*ـێکی ڕووت لە سەردێڕەکەدا واتە: هەموو کە دوای ئەو دێت دەبێت بەپێی ناو بدرێت. ئەمە ئەو بانگکردنانە دەپارێزێت کە نرخێکی بێناو تێیاندا ڕوون نییە. (/ پێچەوانەکەی دەکات: ئەو پێش ئەو دێن تەنها بەپێی شوێن دەدرێن. زۆرتر لە بەڵگەنامەکانی خودی Pythonـدا دەیبینیت، بۆ نموونە len(obj, /).)
size must be given by namesize دەبێت بەپێی ناو بدرێتkeyword_only.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەdef make_tea(sugars, *, size="small"): # after *, only by name
print(f"A {size} tea with {sugars} sugar cubes")
make_tea(2)
make_tea(2, size="large")
make_tea(2, "large")A small tea with 2 sugar cubes
A large tea with 2 sugar cubes
Traceback (most recent call last):
File "keyword_only.py", line 7, in <module>
make_tea(2, "large")
TypeError: make_tea() takes 1 positional argument but 2 were givenCommon mistakesهەڵە باوەکان
| Mistakeهەڵە | What happensچی ڕوو دەدات | Fixچارەسەر |
|---|---|---|
| Arguments in the wrong order بە ڕیزبەندیی هەڵە | A TypeError, or worse, a wrong answer with no messageTypeError، یان خراپتر، وەڵامێکی هەڵە بەبێ هیچ پەیامێک | Check the header, or use keyword argumentsسەیری سەردێڕەکە بکە، یان بەکار بهێنە |
| A positional argument after a keyword argument دوای | SyntaxError: positional argument follows keyword argument | Put all positional arguments firstهەموو بخە پێشەوە |
Quotes around the name: f("n"=5) لە دەوری ناوەکە: f("n"=5) | SyntaxErrorSyntaxError | f(n=5) |
| A name that is not a parameter (a typo)ناوێک کە نییە (هەڵەی نووسین) | TypeError: … got an unexpected keyword argument | Copy the name from the headerناوەکە لە سەردێڕەکەوە کۆپی بکە |
| A default before a parameter without one پێش کە نییەتی | SyntaxError: parameter without a default follows parameter with a default | Put the parameters with defaults last بە بخە کۆتایی |
| A list as a default value وەک | Old items come back in later callsدانە کۆنەکان لە بانگکردنەکانی دواتردا دەگەڕێنەوە | Use None and make the list insideNone بەکار بهێنە و لە ناوەوە دروست بکە |
Spaces around = in a keyword argument: n = 5 لە دەوری = لە : n = 5 | It works, but PEP 8 says noکار دەکات، بەڵام PEP 8 ڕێگە نادات | n=5 |
Exercisesڕاهێنانەکان
Without running it, write down what each call prints. Then explain where price gets its value in each line.
بەبێ جێبەجێکردن، بنووسە هەر بانگکردنێک چی چاپ دەکات. پاشان ڕوونی بکەرەوە لە هەر دێڕێکدا price نرخەکەی لە کوێوە وەردەگرێت.
def ticket(name, seat, price=5000):
print(f"{name}: seat {seat}, {price} dinars")
ticket("Aram", 12)
ticket(seat=3, name="Lana")
ticket("Soran", 7, 4000)
ticket("Hana", price=3000, seat=9)Show answerوەڵامەکە پیشان بدە
Aram: seat 12, 5000 dinars Lana: seat 3, 5000 dinars Soran: seat 7, 4000 dinars Hana: seat 9, 3000 dinars
Lines 1 and 2: price uses its default 5000 (line 2 fills seat and name by name). Line 3: 4000 by position. Line 4: 3000 by name; seat=9 comes after it, which is fine for keyword arguments.
دێڕی 1 و 2: price بەکار دەهێنێت کە 5000ـە (دێڕی 2 seat و name بەپێی ناو پڕ دەکاتەوە). دێڕی 3: 4000 بەپێی شوێن. دێڕی 4: 3000 بەپێی ناو؛ seat=9 دوای ئەو دێت، کە بۆ ئاساییە.
For the same ticket(name, seat, price=5000), which of these calls fail, and with which error? (a) ticket("Hana") (b) ticket("Hana", 9, seat=4) (c) ticket(price=3000, "Hana", 9)
بۆ هەمان ticket(name, seat, price=5000)، کام لەم بانگکردنانە شکست دەهێنن و بە چ ؟ (أ) ticket("Hana") (ب) ticket("Hana", 9, seat=4) (ج) ticket(price=3000, "Hana", 9)
Show answerوەڵامەکە پیشان بدە
All three fail:
هەر سێکیان شکست دەهێنن:
TypeError: ticket() missing 1 required positional argument: 'seat' TypeError: ticket() got multiple values for argument 'seat' SyntaxError: positional argument follows keyword argument
(a) seat has no default, so it needs a value. (b) 9 already reached seat by position, then seat=4 gives it a second value. (c) Positional arguments come after a keyword argument, so Python refuses the whole file.
(أ) seat نییە، بۆیە پێویستی بە نرخە. (ب) 9 پێشتر بەپێی شوێن گەیشتە seat، پاشان seat=4 نرخێکی دووەمی پێ دەدات. (ج) دوای هاتوون، بۆیە Python هەموو فایلەکە ڕەت دەکاتەوە.
Write power(base, exponent=2) that returns base ** exponent. Print power(5), power(2, 10) and power(exponent=3, base=4).
power(base, exponent=2) بنووسە کە base ** exponent بگەڕێنێتەوە. power(5)، power(2, 10) و power(exponent=3, base=4) چاپ بکە.
Hintئاماژە
Without a second argument the function squares the number.
بەبێ دووەم ژمارەکە دووجا دەکات.
Show answerوەڵامەکە پیشان بدە
def power(base, exponent=2):
return base ** exponent
print(power(5))
print(power(2, 10))
print(power(exponent=3, base=4))25 1024 64
Write line(char="-", length=20) that prints char repeated length times. Call it so that it prints: a line of 20 dashes; 10 stars; 5 dashes (give only the length, by name); 8 equals signs.
line(char="-", length=20) بنووسە کە char بە ژمارەی length جار چاپ بکات. بە جۆرێک بانگی بکە کە ئەمانە چاپ بکات: هێڵێکی 20 داش؛ 10 ئەستێرە؛ 5 داش (تەنها درێژییەکە بدە، بەپێی ناو)؛ 8 نیشانەی یەکسان.
Show answerوەڵامەکە پیشان بدە
def line(char="-", length=20):
print(char * length)
line()
line("*", 10)
line(length=5)
line("=", length=8)-------------------- ********** ----- ========
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 7
Only
lengthis given, by name;charkeeps its default.تەنها
lengthدراوە، بەپێی ناو؛charدەپارێزێت.
Exercisesڕاهێنانەکان
Find the errorsهەڵەکان بدۆزەرەوە
Each program below has mistakes. For each one, say what Python reports, then fix it. Remember that Python checks the whole file for syntax errors before it runs anything; after that it stops at the first error it meets. So fix one error, run again, and look for the next.
لە هەر یەکێک لەم سێ خوارەوەدا هەڵە هەیە. بۆ هەر یەکێکیان بڵێ Python چی دەڵێت، پاشان چاکی بکەرەوە. لەبیرت بێت Python پێش ئەوەی هیچ شتێک جێبەجێ بکات هەموو فایلەکە بۆ دەپشکنێت؛ دواتر لە یەکەم کە پێی دەگات دەوەستێت. بۆیە یەک چاک بکەرەوە، دیسان جێبەجێی بکە و بەدوای دواتردا بگەڕێ.
def show_menu(item, times):
for i in range(times):
print item
show_menu("tea")def order(sugars=2, item, size):
print(size, item, "with", sugars, "sugar cubes")
Order("tea", "small")def welcome():
return "Welcome to the tea house"
welcome() = message
print(message)Hintئاماژە
(a) and (b) each have two mistakes; Python shows the second one only after you fix the first.
(أ) و (ب) هەر یەکەیان دوو هەڵەیان تێدایە؛ Python هەڵەی دووەم تەنها دوای چاککردنی یەکەم پیشان دەدات.
Show answerوەڵامەکە پیشان بدە
| Program | Python reports firstPython سەرەتا دەڵێت | After that fixدوای ئەو چاککردنە |
|---|---|---|
| (a) | SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)? | TypeError: show_menu() missing 1 required positional argument: 'times' |
| (b) | SyntaxError: parameter without a default follows parameter with a default | NameError: name 'Order' is not defined. Did you mean: 'order'? |
| (c) | SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='? | — |
- (a)
print itemis Python 2. In Python 3printis a function: writeprint(item). Thenshow_menu("tea")gives one argument for two parameters: say how many times, for exampleshow_menu("tea", 3). - (b) A parameter with a default (
sugars=2) stands before parameters without one: move it to the end,def order(item, size, sugars=2):. ThenOrderis notorder: Python names are case-sensitive. - (c) The left side of
=must be a name that receives a value. A call gives a value; it cannot receive one. Writemessage = welcome().
- (أ)
print itemشێوازی Python 2ـە. لە Python 3ـداprint: بنووسەprint(item). پاشانshow_menu("tea")تەنها یەک بۆ دوو دەنێرێت: ژمارەی جارەکانیش بنێرە، بۆ نموونەshow_menu("tea", 3). - (ب) کە هەیە (
sugars=2) پێش ئەو کەوتووە کە نییانە: بیخە کۆتایی،def order(item, size, sugars=2):. پاشانOrderهەمانorderنییە: ناوەکانی Python . - (ج) لای چەپی
=دەبێت ناوێک بێت کە نرخ وەربگرێت. بانگکردنی نرخ دەدات؛ ناتوانێت نرخ وەربگرێت. بنووسەmessage = welcome().
def show_menu(item, times):
for i in range(times):
print(item)
def order(item, size, sugars=2):
print(size, item, "with", sugars, "sugar cubes")
def welcome():
return "Welcome to the tea house"
show_menu("tea", 3)
order("tea", "small")
message = welcome()
print(message)tea tea tea small tea with 2 sugar cubes Welcome to the tea house
Summaryپوختە
- A positional argument is matched by its place: first to first. Order, number and type must fit the header.
- A keyword argument is written
name=valueand goes to the parameter with that name, in any order. - In one call: positional arguments first, then keyword arguments; one value per parameter; names must exist.
- A default value (
parameter=valuein the header) is used when the call leaves that argument out. Parameters with defaults go last. - A default is made once, when
defruns. So never use a list as a default value: useNone. - Keyword arguments make calls with several similar values (height, base length) clear and safe.
- بەپێی شوێنەکەی دەگونجێنرێت: یەکەم بۆ یەکەم. ڕیزبەندی، ژمارە و جۆر دەبێت لەگەڵ سەردێڕەکە بگونجێن.
- بە شێوەی
name=valueدەنووسرێت و بە هەر ڕیزبەندییەک بێت دەچێتە ئەو هەمان ناوی هەیە. - لە یەک بانگکردندا: سەرەتا ، پاشان ؛ بۆ هەر یەک نرخ؛ ناوەکان دەبێت هەبن.
- (
parameter=valueلە سەردێڕەکەدا) بەکار دێت کاتێک بانگکردنەکە ئەو نانێرێت. بە لە کۆتاییدا دێن. - یەک جار دروست دەکرێت، کاتێک
defجێبەجێ دەبێت. بۆیە هەرگیز وەک بەکار مەهێنە:Noneبەکار بهێنە. - ئەو بانگکردنانەی چەند نرخێکی هاوشێوەیان هەیە (بەرزی، درێژیی بنکە) ڕوون و بێمەترسی دەکەن.
What is the difference between f(1, 2) and f(b=2, a=1) for def f(a, b):?بۆ def f(a, b):، جیاوازیی نێوان f(1, 2) و f(b=2, a=1) چییە؟
Nothing in the result: a is 1 and b is 2 in both. The first matches by order, the second by name.
لە ئەنجامدا هیچ: لە هەردووکیاندا a 1ـە و b 2ـە. یەکەمیان بەپێی ڕیزبەندی دەگونجێنێت، دووەمیان بەپێی ناو.
Why is f(a=1, 2) a syntax error?بۆچی f(a=1, 2) هەڵەی داڕستنە؟
A positional argument may not follow a keyword argument: Python could not tell which parameter 2 is for.
نابێت دوای بێت: Python نازانێت 2 بۆ کام .
When is a default value used?نرخی بنەڕەتی کەی بەکار دێت؟
When the call gives no argument for that parameter, neither by position nor by name.
کاتێک بانگکردنەکە هیچ بۆ ئەو نانێرێت، نە بەپێی شوێن و نە بەپێی ناو.
Next: Variable Scope: Local and Global — where a parameter, and every other variable, can be used.
دواتر: مەودای گۆڕاوەکان: ناوخۆیی و گشتی — و هەموو تر لە کوێ بەکار دێن.
Videoڤیدیۆ
Watch a videoسەیری ڤیدیۆیەک بکە
A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
The three ways to pass arguments: positional (by order), default values in the header, and keyword arguments (name=value).
سێ ڕێگەی ناردنی : (بەپێی ڕیزبەندی)، لە و (name=value).
Whole video (6:14). Chapters: 0:28 positional, 1:42 default, 3:37 keyword, 4:46 recap.
هەموو ڤیدیۆکە (6:14). بەشەکان: 0:28 ، 1:42 ، 3:37 ، 4:46 پێداچوونەوە.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Variable Scope: Local and Globalمەودای گۆڕاوەکان: ناوخۆیی و گشتی
Related lecturesوانە پەیوەندیدارەکان
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- Python tutorial 4.9.1–4.9.3: Default argument values, keyword arguments, special parameters
- Python glossary: argument (keyword and positional), parameter (five kinds)
- Python programming FAQ: Why are default values shared between objects?
- PEP 8 — Style Guide for Python Code (no spaces around = in keyword arguments; snake_case)
- What's New in Python 3.13: suggestions for misspelt keyword arguments
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.