חלקPart 2: פונקציות וקוד אמיתיFunctions & real code
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
Scope וערכי החזרהScope & return values
return מול print, משתנים מקומיים וגלובליים, ופונקציות טהורות.
return vs print, local and global variables, and pure functions.
הנקודות החשובותKey points
- print מציגה לבני אדםprint shows humans
- return מוסרת ערך לקודreturn hands a value to code
- כל קריאה יוצרת frame חדשEach call creates a new frame
- פרמטרים ומשתנים מקומיים חיים שםParameters and locals live there
- פונקציה יכולה לקרוא משתנה גלובליA function can read a global
- השמה בתוך פונקציה יוצרת משתנה מקומיAssigning inside a function makes a local
return a, bמחזיר טאפלreturn a, breturns a tuple- מפרקים:
x, y = f()Unpack:x, y = f() - טהורה: אותו קלט → אותו פלטPure: same input → same output
מונחיםTerms
- טווח הכרה (scope)scope: האזור בקוד שבו משתנה מוכר. משתנה שנוצר בתוך פונקציה מוכר רק בתוכה.The region of code where a variable is known. A variable created inside a function exists only inside it.
- משתנה מקומיlocal variable: משתנה שנוצר בתוך פונקציה ונעלם כשהיא נגמרת.A variable created inside a function that disappears when it ends.
- משתנה גלובליglobal variable: משתנה שנוצר מחוץ לכל פונקציה, ברמת הקובץ.A variable created outside any function, at file level.
- מסגרת (frame)frame: האזור בזיכרון שנוצר לכל קריאה לפונקציה ומחזיק את המשתנים המקומיים שלה.The memory area created for each function call, holding its local variables.
- פונקציה טהורהpure function: פונקציה שהתוצאה שלה תלויה רק בפרמטרים, ושלא משנה שום דבר מחוצה לה. קל לבדוק אותה.A function whose result depends only on its parameters and that changes nothing outside. Easy to test.
- תופעת לוואיside effect: כל דבר שפונקציה עושה מעבר להחזרת ערך: הדפסה, כתיבה לקובץ, שינוי רשימה שקיבלה.Anything a function does besides returning a value: printing, writing a file, changing a list it received.
Cheatsheet
return מול printreturn vs print
def show_total(a, b):
print(a + b)
def get_total(a, b):
return a + b
x = show_total(2, 3)scopeScope
rate = 40
def hours(pages):
return pages / rate
def hours_fast(pages):
rate = 60כמה ערכיםSeveral values
def stats(pages):
if not pages:
return 0, 0
return min(pages), max(pages)
low, high = stats([412, 96, 1036])
print(low, high)פונקציות טהורותPure functions
def add_pure(shelf, title):
return shelf + [title]
def add_inplace(shelf, title):
shelf.append(title)
mine = ["Dune"]שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
TypeError | מחשבים עם תוצאה של פונקציה שרק מדפיסה.Calculating with the result of a function that only prints. | 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). |
NameError | מנסים להשתמש במשתנה מקומי מחוץ לפונקציה.Trying to use a local variable outside the function. | 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). |
UnboundLocalError | מעדכנים משתנה גלובלי בתוך פונקציה בלי להעביר אותו.Updating a global inside a function without passing it in. | 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. |
ValueError | מפרקים למספר משתנים שלא מתאים למה שחוזר.Unpacking into the wrong number of variables. | 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. |
AssertionError | ברירת מחדל שהיא רשימה: אותה רשימה משותפת לכל הקריאות. בדיקה כאן חושפת את המלכודת.A list as a default value: one list shared by every call. A check here exposes the trap. | 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 = []. |
RecursionError | רקורסיה בלי תנאי עצירה.Recursion with no stopping condition. | 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. |