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

PythonPython
9
חלקPart 2: פונקציות וקוד אמיתיFunctions & real code כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

פונקציותFunctions

def, פרמטרים, ערכי ברירת מחדל ולמה מפרקים קוד.

def, parameters, default values and why we split code.

01פונקציה: קוד עם שםA function: code with a name

פונקציה היא בלוק קוד שנותנים לו שם, כדי להריץ אותו שוב ושוב. 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.

banner.py
def banner():
    print("=" * 24)
    print("📚 מדף: הספרייה שלי")
    print("=" * 24)

banner()
print("...תוכן...")
banner()
def banner():
    print("=" * 24)
    print("📚 Shelf: my library")
    print("=" * 24)

banner()
print("...content...")
banner()
פלטOutput
========================
📚 מדף: הספרייה שלי
========================
...תוכן...
========================
📚 מדף: הספרייה שלי
========================
========================
📚 Shelf: my library
========================
...content...
========================
📚 Shelf: my library
========================
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סימולציהSimulationPython קופצת לפונקציה וחוזרתPython jumps into the function and back

מה קורה עכשיוWhat happens now

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life 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".

טעות נפוצהCommon mistake

קוראים לפונקציה לפני שהוגדרה.

Calling a function before it's defined.

banner.py
banner()
def banner():
    print("===")
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/banner.py", line 1, in <module>
    banner()
    ^^^^^^
NameError: name 'banner' is not defined
בעברית פשוטה: In plain words: NameError: Python קוראת מלמעלה למטה, ובשורה 1 banner עוד לא קיימת. מגדירים למעלה, קוראים למטה.NameError: Python reads top down, and on line 1 banner doesn't exist yet. Define above, call below.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

מגדירים פעולה פעם אחת וקוראים לה כמה פעמים.

Define an action once and call it several times.

עוד דוגמה: פעולה שמברכתOne more: an action that greets
example.py
def greet(name):
    print("Hi", name)

greet("Noa")
greet("Dan")
פלטOutput
Hi Noa
Hi Dan
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

02פרמטרים: מידע שנכנסParameters: data going in

פרמטר הוא משתנה של הפונקציה שמקבל ערך בכל קריאה. ככה אותה פונקציה עובדת על נתונים שונים. הערך שמעבירים בקריאה נקרא ארגומנט.

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.

card.py
def book_card(title, author, pages):
    print(f"📚 {title}")
    print(f"   ✍️ {author} · {pages} עמודים")

book_card("Dune", "Frank Herbert", 412)
book_card("Matilda", "Roald Dahl", 240)
def book_card(title, author, pages):
    print(f"📚 {title}")
    print(f"   ✍️ {author} · {pages} pages")

book_card("Dune", "Frank Herbert", 412)
book_card("Matilda", "Roald Dahl", 240)
פלטOutput
📚 Dune
   ✍️ Frank Herbert · 412 עמודים
📚 Matilda
   ✍️ Roald Dahl · 240 עמודים
📚 Dune
   ✍️ Frank Herbert · 412 pages
📚 Matilda
   ✍️ Roald Dahl · 240 pages
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life 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.

טעות נפוצהCommon mistake

מעבירים פחות ארגומנטים ממה שהפונקציה צריכה.

Passing fewer arguments than the function needs.

card.py
def book_card(title, author):
    print(title, author)

book_card("Dune")
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/card.py", line 4, in <module>
    book_card("Dune")
    ~~~~~~~~~^^^^^^^^
TypeError: book_card() missing 1 required positional argument: 'author'
בעברית פשוטה: In plain words: 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.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03ברירת מחדל וארגומנטים לפי שםDefaults and keyword arguments

ערך ברירת מחדל הופך פרמטר לאופציונלי. בקריאה אפשר להעביר ארגומנט לפי שם, וכך הסדר לא משנה והקוד קריא יותר. 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.

defaults.py
def reading_time(pages, per_hour=40, rounded=True):
    hours = pages / per_hour
    return round(hours) if rounded else hours

print(reading_time(412))
print(reading_time(412, per_hour=60))
print(reading_time(pages=100, rounded=False))
פלטOutput
10
7
2.5
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

ברירת מחדל היא כמו הזמנת קפה "רגיל": אם לא אמרתם אחרת, תקבלו עם חלב. מי שרוצה שחור, אומר במפורש.

A default is like ordering a "regular" coffee: unless you say otherwise you get milk. Want it black? Say so explicitly.

טעות נפוצהCommon mistake

שמים פרמטר בלי ברירת מחדל אחרי פרמטר עם ברירת מחדל.

Putting a parameter without a default after one with a default.

defaults.py
def reading_time(per_hour=40, pages):
    return pages / per_hour
מה Python עונהWhat Python says
  File "/Users/you/python-course/defaults.py", line 1
    def reading_time(per_hour=40, pages):
                                  ^^^^^
SyntaxError: parameter without a default follows parameter with a default
בעברית פשוטה: In plain words: SyntaxError: parameter without a default follows parameter with a default: פרמטרים חובה קודם, אופציונליים אחר כך.SyntaxError: parameter without a default follows parameter with a default: required first, optional after.

04return: מידע שיוצאreturn: data coming out

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.

return.py
def percent(read, total):
    return round(read / total * 100)

done = percent(103, 412)
print(f"{done}%")
if percent(400, 412) > 90:
    print("כמעט סיימת!")
def percent(read, total):
    return round(read / total * 100)

done = percent(103, 412)
print(f"{done}%")
if percent(400, 412) > 90:
    print("Almost done!")
פלטOutput
25%
כמעט סיימת!
25%
Almost done!
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life 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.

טעות נפוצהCommon mistake

משתמשים בתוצאה של פונקציה שלא מחזירה כלום.

Using the result of a function that returns nothing.

return.py
def double(x):
    print(x * 2)

result = double(5) + 1
מה Python עונהWhat Python says
10
Traceback (most recent call last):
  File "/Users/you/python-course/return.py", line 4, in <module>
    result = double(5) + 1
             ~~~~~~~~~~^~~
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
בעברית פשוטה: In plain words: 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.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

return מחזיר תשובה שאפשר לשמור בקופסה.

return gives back an answer we can keep in a box.

עוד דוגמה: שטח של מלבןOne more: a rectangle's area
example.py
def area(w, h):
    return w * h

room = area(4, 3)
yard = area(10, 2)
print(room + yard)
פלטOutput
32
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05docstring ושמות טוביםDocstrings and good names

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.

doc.py
def pages_left(total, read):
    """מחזירה כמה עמודים נשארו (לא פחות מ-0)."""
    return max(total - read, 0)

print(pages_left(412, 103))
print(pages_left.__doc__)
def pages_left(total, read):
    """Return how many pages are left (never below 0)."""
    return max(total - read, 0)

print(pages_left(412, 103))
print(pages_left.__doc__)
פלטOutput
309
מחזירה כמה עמודים נשארו (לא פחות מ-0).
309
Return how many pages are left (never below 0).
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

docstring היא כמו התווית על קופסת שימורים: לא צריך לפתוח את הקופסה כדי לדעת מה בפנים.

A docstring is like the label on a tin: you don't need to open it to know what's inside.

טעות נפוצהCommon mistake

שוכחים את הנקודתיים אחרי הגדרת הפונקציה.

Forgetting the colon after the def line.

doc.py
def pages_left(total, read)
    return total - read
מה Python עונהWhat Python says
  File "/Users/you/python-course/doc.py", line 1
    def pages_left(total, read)
                               ^
SyntaxError: expected ':'
בעברית פשוטה: In plain words: SyntaxError: expected ':': כמו if, גם def נגמר בנקודתיים.SyntaxError: expected ':': like if, def ends with a colon.

06לפרק תוכנית לפונקציותSplitting a program into functions

תוכנית טובה בנויה מפונקציות קטנות, שכל אחת עושה דבר אחד ויש לה שם ברור. כשמוצאים קוד שחוזר פעמיים, מוציאים אותו לפונקציה (עיקרון 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.

split.py
def read_book():
    title = input("title: ").strip().title()
    pages = int(input("pages: "))
    return {"title": title, "pages": pages}

def show(book):
    print(f"{book['title']:<12}{book['pages']:>5}")

def main():
    shelf = [read_book(), read_book()]
    for b in shelf:
        show(b)
    print("total:", sum(b["pages"] for b in shelf))

main()
פלטOutput
title: dune
pages: 412
title: emma
pages: 474
Dune          412
Emma          474
total: 886
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

פירוק לפונקציות הוא כמו מטבח של מסעדה: יש תחנת סלטים, תחנת גריל ותחנת קינוחים. השף הראשי (main) רק מתאם ביניהן.

Decomposition is like a restaurant kitchen: a salad station, a grill station, a dessert station. The head chef (main) just coordinates.

טעות נפוצהCommon mistake

שוכחים סוגריים בקריאה, ומקבלים את הפונקציה עצמה במקום התוצאה.

Forgetting the parentheses in a call, getting the function itself instead of its result.

split.py
def total():
    return 412

print(total + 1)
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/split.py", line 4, in <module>
    print(total + 1)
          ~~~~~~^~~
TypeError: unsupported operand type(s) for +: 'function' and 'int'
בעברית פשוטה: In plain words: 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.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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