מפגש 9: def, פרמטרים, ערכי ברירת מחדל ולמה מפרקים קוד.Session 9: def, parameters, default values and why we split code.
def, פרמטרים, ערכי ברירת מחדל ולמה מפרקים קוד. בסוף המפגש מוסיפים צעד לפרויקט המלווה.def, parameters, default values and why we split code. At the end we add a step to the companion project.
מה נעשה היוםToday's plan
defdef
פרמטריםParameters
ברירות מחדלDefaults
returnreturn
docstringDocstrings
פירוק לפונקציותDecomposition
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.
נושאTopic 1
defdef
פונקציה: קוד עם שםA function: code with a name
def name(): + בלוק מוזחdef name(): + an indented block
ההגדרה לא מריצה כלוםDefining runs nothing
הקריאה name() מריצהThe call name() runs it
פונקציה היא בלוק קוד שנותנים לו שם, כדי להריץ אותו שוב ושוב. def רק מגדיר את הפונקציה; הקוד בתוכה רץ רק כשקוראים לה עם סוגריים.A function is a block of code with a name, so you can run it again and again. def only defines it; the code inside runs only when you function call it with parentheses.
========================
📚 Shelf: my library
========================
...content...
========================
📚 Shelf: my library
========================
מריצים ומשווים לניחושים.Run it and compare with the guesses.
אנלוגיהAnalogy
פונקציה היא כמו מתכון שכתבתם פעם אחת בפנקס. כל פעם שרוצים עוגה, לא כותבים את המתכון מחדש: רק אומרים "תכין את העוגה".A function is like a recipe written once in a notebook. Each time you want the cake you don't rewrite the recipe: you just say "make the cake".
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
banner.py
banner()
def banner():print("===")
מה Python עונהWhat Python says
NameError: name 'banner' is not defined
NameError: Python קוראת מלמעלה למטה, ובשורה 1 banner עוד לא קיימת. מגדירים למעלה, קוראים למטה.NameError: Python reads top down, and on line 1 banner doesn't exist yet. Define above, call below.
קוראים לפונקציה לפני שהוגדרה.Calling a function before it's defined.
נושאTopic 2
פרמטריםParameters
פרמטרים: מידע שנכנסParameters: data going in
def greet(name):def greet(name):
הערך בקריאה מגיע לפרמטרThe call's value lands in the parameter
כמה פרמטרים מופרדים בפסיקSeveral parameters, comma separated
פרמטר הוא משתנה של הפונקציה שמקבל ערך בכל קריאה. ככה אותה פונקציה עובדת על נתונים שונים. הערך שמעבירים בקריאה נקרא ארגומנט.A parameter is the function's own variable that receives a value on each call. That's how one function works on different data. The value you pass in the call is the argument.
אנלוגיהAnalogy
פרמטר הוא כמו חור בטופס: "שם: ____". כל פעם שממלאים את הטופס (קוראים לפונקציה), כותבים בחור ערך אחר.A parameter is like a blank on a form: "Name: ____". Each time you fill in the form (call the function), you write a different value in the blank.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
TypeError: book_card() missing 1 required positional argument: 'author': מעבירים ערך לכל פרמטר, או נותנים לו ברירת מחדל.TypeError: book_card() missing 1 required positional argument: 'author': pass a value for every parameter, or give it a default.
מעבירים פחות ארגומנטים ממה שהפונקציה צריכה.Passing fewer arguments than the function needs.
נושאTopic 3
ברירות מחדלDefaults
ברירת מחדל וארגומנטים לפי שםDefaults and keyword arguments
def f(x, unit="cm"):def f(x, unit="cm"):
קריאה לפי שם: f(5, unit="m")Keyword call: f(5, unit="m")
פרמטרים עם ברירת מחדל באים בסוףDefaulted parameters go last
ערך ברירת מחדל הופך פרמטר לאופציונלי. בקריאה אפשר להעביר ארגומנט לפי שם, וכך הסדר לא משנה והקוד קריא יותר. print(..., sep="/") מהמפגש השני הוא בדיוק זה.A default value makes a parameter optional. In a call you can pass an argument by name, so order doesn't matter and the code reads better. print(..., sep="/") from session 2 is exactly this.
אנלוגיהAnalogy
ברירת מחדל היא כמו הזמנת קפה "רגיל": אם לא אמרתם אחרת, תקבלו עם חלב. מי שרוצה שחור, אומר במפורש.A default is like ordering a "regular" coffee: unless you say otherwise you get milk. Want it black? Say so explicitly.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
SyntaxError: parameter without a default follows parameter with a default
SyntaxError: parameter without a default follows parameter with a default: פרמטרים חובה קודם, אופציונליים אחר כך.SyntaxError: parameter without a default follows parameter with a default: required first, optional after.
שמים פרמטר בלי ברירת מחדל אחרי פרמטר עם ברירת מחדל.Putting a parameter without a default after one with a default.
נושאTopic 4
returnreturn
return: מידע שיוצאreturn: data coming out
return x מחזיר ערך לקוראreturn x hands a value back
אחרי return הפונקציה נגמרתAfter return the function ends
בלי return מקבלים NoneWithout return you get None
return מחזיר ערך מהפונקציה למי שקרא לה, ואז הפונקציה נגמרת. את הערך אפשר לשמור במשתנה, להדפיס או להעביר לפונקציה אחרת. במפגש 10 נעמיק בהבדל בין return ל-print.return hands a value back to whoever called the function, and the function ends. You can store the value, print it, or pass it to another function. Session 10 goes deep into return versus print.
שאלה לכיתהQuestion for the class
מה ידפיס הקוד?What will this print?
python
def percent(read, total):returnround(read / total *100)
done = percent(103, 412)
print(f"{done}%")
if percent(400, 412) >90:print("כמעט סיימת!")
def percent(read, total):returnround(read / total *100)
done = percent(103, 412)
print(f"{done}%")
if percent(400, 412) >90:print("Almost done!")
נותנים לכיתה חצי דקה לנחש, ואז עוברים לשקופית הבאה.Give the class half a minute to guess, then move on.
returnreturn
return.py
def percent(read, total):returnround(read / total *100)
done = percent(103, 412)
print(f"{done}%")
if percent(400, 412) >90:print("כמעט סיימת!")
def percent(read, total):returnround(read / total *100)
done = percent(103, 412)
print(f"{done}%")
if percent(400, 412) >90:print("Almost done!")
פלטOutput
25%
כמעט סיימת!
25%
Almost done!
מריצים ומשווים לניחושים.Run it and compare with the guesses.
אנלוגיהAnalogy
פונקציה עם return היא כמו מכונת מיץ: מכניסים תפוזים (ארגומנטים), ומקבלים כוס מיץ (ערך) שאפשר לשתות, לשמור או לתת למישהו.A function with return is like a juicer: oranges go in (arguments) and a glass of juice comes out (a value) that you can drink, keep or hand to someone.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
return.py
def double(x):print(x *2)
result = double(5) +1
מה Python עונהWhat Python says
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int': הפונקציה מדפיסה אבל לא מחזירה, ולכן התוצאה None. מחליפים ל-return x * 2.TypeError: unsupported operand type(s) for +: 'NoneType' and 'int': the function prints but doesn't return, so the result is None. Change it to return x * 2.
משתמשים בתוצאה של פונקציה שלא מחזירה כלום.Using the result of a function that returns nothing.
נושאTopic 5
docstringDocstrings
docstring ושמות טוביםDocstrings and good names
שם פונקציה = פועל: add_bookFunction name = a verb: add_book
docstring בשורה הראשונהA docstring on the first line
help(f) מציג אותוhelp(f) shows it
docstring היא מחרוזת מיד אחרי שורת ה-def, שמסבירה מה הפונקציה עושה, מה היא מקבלת ומה מחזירה. עורכים כמו VS Code מציגים אותה כשמרחפים מעל הקריאה. שמות פונקציות כותבים כפועל ב-snake_case.A docstring is a string right after the def line explaining what the function does, takes and returns. Editors like VS Code show it when you hover over a call. Function names are verbs in snake_case.
אנלוגיהAnalogy
docstring היא כמו התווית על קופסת שימורים: לא צריך לפתוח את הקופסה כדי לדעת מה בפנים.A docstring is like the label on a tin: you don't need to open it to know what's inside.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
doc.py
def pages_left(total, read)
return total - read
מה Python עונהWhat Python says
SyntaxError: expected ':'
SyntaxError: expected ':': כמו if, גם def נגמר בנקודתיים.SyntaxError: expected ':': like if, def ends with a colon.
שוכחים את הנקודתיים אחרי הגדרת הפונקציה.Forgetting the colon after the def line.
נושאTopic 6
פירוק לפונקציותDecomposition
לפרק תוכנית לפונקציותSplitting a program into functions
כל פונקציה עושה דבר אחדEach function does one thing
פונקציה ראשית main() מחברת הכולA main() function ties it together
תוכנית טובה בנויה מפונקציות קטנות, שכל אחת עושה דבר אחד ויש לה שם ברור. כשמוצאים קוד שחוזר פעמיים, מוציאים אותו לפונקציה (עיקרון DRY). פונקציית main מחברת את החלקים.A good program is made of small functions, each doing one thing with a clear name. When code repeats, pull it into a function (the DRY principle). A main function ties the pieces together.
אנלוגיהAnalogy
פירוק לפונקציות הוא כמו מטבח של מסעדה: יש תחנת סלטים, תחנת גריל ותחנת קינוחים. השף הראשי (main) רק מתאם ביניהן.Decomposition is like a restaurant kitchen: a salad station, a grill station, a dessert station. The head chef (main) just coordinates.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
split.py
def total():return412print(total +1)
מה Python עונהWhat Python says
TypeError: unsupported operand type(s) for +: 'function' and 'int'
TypeError: unsupported operand type(s) for +: 'function' and 'int': בלי () הפונקציה לא רצה. כותבים total() + 1.TypeError: unsupported operand type(s) for +: 'function' and 'int': without () the function doesn't run. Write total() + 1.
שוכחים סוגריים בקריאה, ומקבלים את הפונקציה עצמה במקום התוצאה.Forgetting the parentheses in a call, getting the function itself instead of its result.
def name(): + בלוק מוזחdef name(): + an indented block
פונקציה: קוד עם שםA function: code with a name
ההגדרה לא מריצה כלוםDefining runs nothing
פונקציה: קוד עם שםA function: code with a name
הקריאה name() מריצהThe call name() runs it
פונקציה: קוד עם שםA function: code with a name
def greet(name):def greet(name):
פרמטרים: מידע שנכנסParameters: data going in
הערך בקריאה מגיע לפרמטרThe call's value lands in the parameter
פרמטרים: מידע שנכנסParameters: data going in
כמה פרמטרים מופרדים בפסיקSeveral parameters, comma separated
פרמטרים: מידע שנכנסParameters: data going in
def f(x, unit="cm"):def f(x, unit="cm"):
ברירת מחדל וארגומנטים לפי שםDefaults and keyword arguments
קריאה לפי שם: f(5, unit="m")Keyword call: f(5, unit="m")
ברירת מחדל וארגומנטים לפי שםDefaults and keyword arguments
מה למדנוWhat we learned
def name(): + בלוק מוזחdef name(): + an indented block
def greet(name):def greet(name):
def f(x, unit="cm"):def f(x, unit="cm"):
return x מחזיר ערך לקוראreturn x hands a value back
שם פונקציה = פועל: add_bookFunction name = a verb: add_book
כל פונקציה עושה דבר אחדEach function does one thing
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.
עכשיו לתרגולNow, practice
5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked