נבנה על ידיBuilt by Ariel Yohimovich

חזרה למפגשBack
PythonPython

Scope וערכי החזרהScope & return values

מפגש 10: return מול print, משתנים מקומיים וגלובליים, ופונקציות טהורות.Session 10: return vs print, local and global variables, and pure functions.

מה נעשה היוםToday's plan

  • return מול printreturn vs print
  • מסגרותFrames
  • scopeScope
  • כמה ערכיםSeveral values
  • פונקציות טהורותPure functions
  • הרכבהComposition
נושא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
שאלה לכיתה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)

    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

    אנלוגיה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.

    טעות נפוצהCommon mistake

    rvp.py
    def average(nums):
        print(sum(nums) / len(nums))
    
    score = average([80, 90])
    print(score > 85)
    מה Python עונהWhat Python says
    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).
    נושא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

    אנלוגיה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.

    טעות נפוצה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).
    נושא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
    שאלה לכיתהQuestion for the class

    מה ידפיס הקוד?What will this print?

    python
    rate = 40
    
    def hours(pages):
        return pages / rate
    
    def hours_fast(pages):
        rate = 60
        return pages / rate
    
    print(hours(120), hours_fast(120), rate)

      scopeScope

      scope.py
      rate = 40
      
      def hours(pages):
          return pages / rate
      
      def hours_fast(pages):
          rate = 60
          return pages / rate
      
      print(hours(120), hours_fast(120), rate)
      פלטOutput
      3.0 2.0 40

      אנלוגיה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.

      טעות נפוצהCommon mistake

      scope.py
      count = 0
      
      def 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.
      נושא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
      שאלה לכיתהQuestion for the class

      מה ידפיס הקוד?What will this print?

      python
      def stats(pages):
          if not pages:
              return 0, 0
          return min(pages), max(pages)
      
      low, high = stats([412, 96, 1036])
      print(low, high)
      print(stats([]))

        כמה ערכיםSeveral values

        multi.py
        def stats(pages):
            if not pages:
                return 0, 0
            return min(pages), max(pages)
        
        low, high = stats([412, 96, 1036])
        print(low, high)
        print(stats([]))
        פלטOutput
        96 1036
        (0, 0)

        אנלוגיהAnalogy

        החזרת כמה ערכים היא כמו לקבל מהקופאית גם קבלה וגם עודף באותה מסירה.Returning several values is like getting both the receipt and the change from the cashier in one hand-off.

        טעות נפוצהCommon mistake

        multi.py
        def stats(pages):
            return min(pages), max(pages)
        
        low, high, avg = stats([1, 2])
        מה Python עונהWhat Python says
        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.
        נושאTopic 5

        פונקציות טהורותPure functions

        פונקציות טהורות ותופעות לוואיPure functions and side effects

        • טהורה: אותו קלט → אותו פלטPure: same input → same output
        • תופעת לוואי: הדפסה, קובץ, שינוי רשימהA side effect: printing, files, changing a list
        • טהורות קל לבדוק (מפגש 19)Pure ones are easy to test (session 19)

        אנלוגיה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.

        טעות נפוצה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 = [].
        נושאTopic 6

        הרכבהComposition

        פונקציות שקוראות לפונקציותFunctions calling functions

        • פלט של אחת = קלט של אחרתOne's output = another's input
        • מחסנית קריאות: מסגרת על מסגרתCall stack: frame on frame
        • רקורסיה: פונקציה שקוראת לעצמהRecursion: a function calling itself

        אנלוגיה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.

        טעות נפוצהCommon mistake

        compose.py
        def countdown(n):
            print(n)
            countdown(n - 1)
        
        countdown(3)
        מה Python עונהWhat Python says
        RecursionError: maximum recursion depth exceeded
        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.

        print מציגה לבני אדםprint shows humans

        return מוסרת ערך לקודreturn hands a value to code

        פונקציה שמדפיסה מחזירה NoneA printing function returns None

        כל קריאה יוצרת frame חדשEach call creates a new frame

        פרמטרים ומשתנים מקומיים חיים שםParameters and locals live there

        כשהפונקציה חוזרת, ה-frame נעלםWhen the function returns, the frame is gone

        מה למדנו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

        עכשיו לתרגולNow, practice

        5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
        הערות מרצהSpeaker notes

        נבנה על ידיBuilt by Ariel Yohimovich