מפגש 10: return מול print, משתנים מקומיים וגלובליים, ופונקציות טהורות.Session 10: return vs print, local and global variables, and pure functions.
return מול print, משתנים מקומיים וגלובליים, ופונקציות טהורות. בסוף המפגש מוסיפים צעד לפרויקט המלווה.return vs print, local and global variables, and pure functions. At the end we add a step to the companion project.
מה נעשה היוםToday's plan
return מול printreturn vs print
מסגרותFrames
scopeScope
כמה ערכיםSeveral values
פונקציות טהורותPure functions
הרכבהComposition
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.
נושאTopic 1
return מול printreturn vs print
return מול printreturn vs print
print מציגה לבני אדםprint shows humans
return מוסרת ערך לקודreturn hands a value to code
פונקציה שמדפיסה מחזירה NoneA printing function returns None
זה הבלבול הכי נפוץ אצל מתחילים. print רק מציגה טקסט על המסך, והתוכנית לא יכולה להשתמש בו. return מוסרת ערך בחזרה לקוד שקרא, ואפשר לחשב איתו, לשמור או להשוות.This is beginners' most common mix-up. print only shows text on screen, and the program can't use it. return hands a value back to the calling code, which can calculate with it, store or compare it.
שאלה לכיתהQuestion for the class
מה ידפיס הקוד?What will this print?
python
def show_total(a, b):print(a + b)
def get_total(a, b):return a + b
x = show_total(2, 3)
y = get_total(2, 3)
print("x =", x)
print("y =", y, "| y * 10 =", y *10)
נותנים לכיתה חצי דקה לנחש, ואז עוברים לשקופית הבאה.Give the class half a minute to guess, then move on.
return מול printreturn vs print
rvp.py
def show_total(a, b):print(a + b)
def get_total(a, b):return a + b
x = show_total(2, 3)
y = get_total(2, 3)
print("x =", x)
print("y =", y, "| y * 10 =", y *10)
פלטOutput
5
x = None
y = 5 | y * 10 = 50
מריצים ומשווים לניחושים.Run it and compare with the guesses.
אנלוגיהAnalogy
print היא לצעוק את התשובה בחדר: כולם שומעים, אבל אף אחד לא רשם. return היא לכתוב את התשובה על פתק ולמסור אותו ביד: אפשר לשמור, להעתיק ולהשתמש.print is shouting the answer across the room: everyone hears, nobody wrote it down. return is writing it on a note and handing it over: it can be kept, copied and used.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
TypeError: '>' not supported between instances of 'NoneType' and 'int'
TypeError: '>' not supported between instances of 'NoneType' and 'int': average מחזירה None. משנים ל-return sum(nums) / len(nums).TypeError: '>' not supported between instances of 'NoneType' and 'int': average returns None. Change it to return sum(nums) / len(nums).
מחשבים עם תוצאה של פונקציה שרק מדפיסה.Calculating with the result of a function that only prints.
נושאTopic 2
מסגרותFrames
מסגרות: כל קריאה מקבלת משתנים משלהFrames: each call gets its own variables
כל קריאה יוצרת frame חדשEach call creates a new frame
פרמטרים ומשתנים מקומיים חיים שםParameters and locals live there
כשהפונקציה חוזרת, ה-frame נעלםWhen the function returns, the frame is gone
בכל קריאה לפונקציה Python יוצרת מסגרת חדשה בזיכרון, ובה הפרמטרים והמשתנים המקומיים. כשהפונקציה מחזירה ערך, המסגרת נמחקת. בוויזואלייזר רואים את זה קורה:On every function call Python creates a new frame in memory holding the parameters and local variable variables. When the function returns, the frame is deleted. Watch it happen in the visualizer:
אנלוגיהAnalogy
מסגרת היא כמו דף טיוטה שמקבלים לכל תרגיל במבחן: כותבים עליו חישובים, מעבירים רק את התשובה הסופית לדף התשובות, והטיוטה נזרקת.A frame is like the scrap paper you get for each exam question: you do the working on it, copy only the final answer onto the answer sheet, and the scrap is thrown away.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
frames.py
def pages_left(total, read):
left = total - read
return left
pages_left(412, 100)
print(left)
מה Python עונהWhat Python says
NameError: name 'left' is not defined
NameError: name 'left' is not defined: left חי רק בתוך המסגרת. שומרים את מה שחוזר: left = pages_left(412, 100).NameError: name 'left' is not defined: left lives only in the frame. Keep what comes back: left = pages_left(412, 100).
מנסים להשתמש במשתנה מקומי מחוץ לפונקציה.Trying to use a local variable outside the function.
נושאTopic 3
scopeScope
scope: מקומי מול גלובליScope: local vs global
פונקציה יכולה לקרוא משתנה גלובליA function can read a global
השמה בתוך פונקציה יוצרת משתנה מקומיAssigning inside a function makes a local
עדיף להעביר כפרמטר ולהחזירPrefer passing in and returning
טווח הכרה (scope) קובע איפה משתנה מוכר. משתנה גלובלי (ברמת הקובץ) אפשר לקרוא מתוך פונקציה. אבל ברגע שעושים לו השמה בתוך הפונקציה, Python מחליטה שזה משתנה מקומי חדש, וזה מקור לבאגים.scope decides where a variable is known. A global variable (file-level) variable can be read inside a function. But the moment you assign to it inside the function, Python decides it's a new local, which causes bugs.
מריצים ומשווים לניחושים.Run it and compare with the guesses.
אנלוגיהAnalogy
משתנה גלובלי הוא כמו שעון על קיר המשרד: כל אחד רואה אותו. אבל אם מישהו תולה שעון משלו בתא שלו, זה שעון אחר, ושעון הקיר לא זז.A global is like the clock on the office wall: everyone can see it. But if someone hangs their own clock in their cubicle, that's a different clock, and the wall clock doesn't move.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
scope.py
count =0def add_book():
count +=1
add_book()
מה Python עונהWhat Python says
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
UnboundLocalError: ה-+= הופך את count למקומי, אבל אין לו ערך עדיין. פותרים עם def add_book(count): return count + 1.UnboundLocalError: the += makes count local, but it has no value yet. Fix: def add_book(count): return count + 1.
מעדכנים משתנה גלובלי בתוך פונקציה בלי להעביר אותו.Updating a global inside a function without passing it in.
נושאTopic 4
כמה ערכיםSeveral values
להחזיר כמה ערכיםReturning several values
return a, b מחזיר טאפלreturn a, b returns a tuple
מפרקים: x, y = f()Unpack: x, y = f()
return מוקדם יוצא מידAn early return exits at once
return a, b מחזיר טאפל, ובקריאה מפרקים אותו לשני משתנים. return באמצע הפונקציה ("return מוקדם") עוצר אותה מיד, וזה נוח לטיפול במקרים מיוחדים בהתחלה.return a, b returns a tuple, which the caller unpacks into two variables. A return in the middle ("early return") stops the function at once, handy for handling special cases first.
מריצים ומשווים לניחושים.Run it and compare with the guesses.
אנלוגיהAnalogy
החזרת כמה ערכים היא כמו לקבל מהקופאית גם קבלה וגם עודף באותה מסירה.Returning several values is like getting both the receipt and the change from the cashier in one hand-off.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
ValueError: not enough values to unpack (expected 3, got 2)
ValueError: not enough values to unpack (expected 3, got 2): מספר המשתנים בצד שמאל חייב להתאים.ValueError: not enough values to unpack (expected 3, got 2): the number of names on the left must match.
מפרקים למספר משתנים שלא מתאים למה שחוזר.Unpacking into the wrong number of variables.
נושאTopic 5
פונקציות טהורותPure functions
פונקציות טהורות ותופעות לוואיPure functions and side effects
טהורה: אותו קלט → אותו פלטPure: same input → same output
טהורות קל לבדוק (מפגש 19)Pure ones are easy to test (session 19)
פונקציה טהורה מחזירה תוצאה שתלויה רק בפרמטרים, ולא משנה כלום בחוץ. תופעת לוואי היא כל דבר נוסף: הדפסה, כתיבה לקובץ, שינוי רשימה שקיבלה. תוכנית טובה מחזיקה את רוב הלוגיקה בפונקציות טהורות.A pure function returns a result that depends only on its parameters and changes nothing outside. A side effect is anything else: printing, writing a file, changing a list it received. A good program keeps most logic in pure functions.
אנלוגיהAnalogy
פונקציה טהורה היא כמו מחשבון: אותו תרגיל תמיד נותן אותה תשובה, והמחשבון לא כותב לכם במחברת. פונקציה עם תופעות לוואי היא כמו עוזר שגם מסדר לכם את השולחן בלי לשאול.A pure function is like a calculator: the same sum always gives the same answer, and it never writes in your notebook. A function with side effects is like a helper who also tidies your desk without asking.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
pure.py
def add(title, shelf=[]):
shelf.append(title)
return shelf
add("Dune")
second = add("Emma")
assert second == ["Emma"], f"got {second}"
מה Python עונהWhat Python says
AssertionError: got ['Dune', 'Emma']
AssertionError: הרשימה נוצרת פעם אחת כשמגדירים את הפונקציה. כותבים shelf=None ובתוך הפונקציה if shelf is None: shelf = [].AssertionError: the list is created once, when the function is defined. Write shelf=None and inside if shelf is None: shelf = [].
ברירת מחדל שהיא רשימה: אותה רשימה משותפת לכל הקריאות. בדיקה כאן חושפת את המלכודת.A list as a default value: one list shared by every call. A check here exposes the trap.
פלט של אחת = קלט של אחרתOne's output = another's input
מחסנית קריאות: מסגרת על מסגרתCall stack: frame on frame
רקורסיה: פונקציה שקוראת לעצמהRecursion: a function calling itself
פונקציות קוראות זו לזו, ובכל קריאה נוספת מסגרת מעל הקודמת. זו "מחסנית הקריאות", וזה מה שמופיע ב-Traceback (מפגש 11). מקרה מיוחד: פונקציה שקוראת לעצמה, רקורסיה, חייבת תנאי עצירה.Functions call each other, each call adding a frame on top of the last. That's the "call stack", and it's what a traceback shows (session 11). A special case: a function calling itself, recursion, which needs a stopping condition.
אנלוגיהAnalogy
מחסנית קריאות היא כמו ערימת צלחות: מניחים צלחת חדשה למעלה בכל קריאה, ומורידים אותה כשהפונקציה חוזרת.The call stack is like a pile of plates: a new plate goes on top with each call, and comes off when the function returns.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
RecursionError: maximum recursion depth exceeded: מוסיפים if n == 0: return בתחילת הפונקציה.RecursionError: maximum recursion depth exceeded: add if n == 0: return at the top of the function.
רקורסיה בלי תנאי עצירה.Recursion with no stopping condition.
print מציגה לבני אדםprint shows humans
return מול printreturn vs print
return מוסרת ערך לקודreturn hands a value to code
return מול printreturn vs print
פונקציה שמדפיסה מחזירה NoneA printing function returns None
return מול printreturn vs print
כל קריאה יוצרת frame חדשEach call creates a new frame
מסגרות: כל קריאה מקבלת משתנים משלהFrames: each call gets its own variables
פרמטרים ומשתנים מקומיים חיים שםParameters and locals live there
מסגרות: כל קריאה מקבלת משתנים משלהFrames: each call gets its own variables
כשהפונקציה חוזרת, ה-frame נעלםWhen the function returns, the frame is gone
מסגרות: כל קריאה מקבלת משתנים משלהFrames: each call gets its own variables
מה למדנוWhat we learned
print מציגה לבני אדםprint shows humans
כל קריאה יוצרת frame חדשEach call creates a new frame
פונקציה יכולה לקרוא משתנה גלובליA function can read a global
return a, b מחזיר טאפלreturn a, b returns a tuple
טהורה: אותו קלט → אותו פלטPure: same input → same output
פלט של אחת = קלט של אחרתOne's output = another's input
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.
עכשיו לתרגולNow, practice
5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked