חלקPart 2: פונקציות וקוד אמיתיFunctions & real code
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
פונקציותFunctions
def, פרמטרים, ערכי ברירת מחדל ולמה מפרקים קוד.
def, parameters, default values and why we split code.
הנקודות החשובותKey points
def name():+ בלוק מוזחdef name():+ an indented block- ההגדרה לא מריצה כלוםDefining runs nothing
def greet(name):def greet(name):- הערך בקריאה מגיע לפרמטרThe call's value lands in the parameter
def f(x, unit="cm"):def f(x, unit="cm"):- קריאה לפי שם:
f(5, unit="m")Keyword call:f(5, unit="m") return xמחזיר ערך לקוראreturn xhands a value back- אחרי return הפונקציה נגמרתAfter return the function ends
- שם פונקציה = פועל:
add_bookFunction name = a verb:add_book
מונחיםTerms
- def (הגדרת פונקציה)def (function definition): המילה שמגדירה פונקציה חדשה:
def greet(name):ואחריה בלוק מוזח.The keyword that defines a new function:def greet(name):followed by an indented block. - פרמטרparameter: שם בסוגריים של הגדרת הפונקציה, שמקבל את הערך שמעבירים בקריאה.A name in a function definition's parentheses that receives the value passed in a call.
- קריאה לפונקציהfunction call: הפעלת פונקציה עם סוגריים:
greet("Noa").Running a function with parentheses:greet("Noa"). - ערך ברירת מחדלdefault value: ערך שהפרמטר מקבל אם לא העבירו לו כלום:
def greet(name="guest").The value a parameter gets if nothing is passed:def greet(name="guest"). - docstringdocstring: מחרוזת בשורה הראשונה של פונקציה שמסבירה מה היא עושה.
help()מציגה אותה.A string on a function's first line explaining what it does.help()shows it. - DRYDRY: "Don't Repeat Yourself": אם כתבתם קוד דומה פעמיים, כנראה שצריך פונקציה."Don't Repeat Yourself": if you wrote similar code twice, you probably need a function.
Cheatsheet
defdef
def banner():
print("=" * 24)
print("📚 מדף: הספרייה שלי")
print("=" * 24)
banner()
print("...תוכן...")def banner():
print("=" * 24)
print("📚 Shelf: my library")
print("=" * 24)
banner()
print("...content...")פרמטריםParameters
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)ברירות מחדלDefaults
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))returnreturn
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!")docstringDocstrings
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__)פירוק לפונקציותDecomposition
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}")שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
NameError | קוראים לפונקציה לפני שהוגדרה.Calling a function before it's defined. | NameError: Python קוראת מלמעלה למטה, ובשורה 1 banner עוד לא קיימת. מגדירים למעלה, קוראים למטה.NameError: Python reads top down, and on line 1 banner doesn't exist yet. Define above, call below. |
TypeError | מעבירים פחות ארגומנטים ממה שהפונקציה צריכה.Passing fewer arguments than the function needs. | 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. |
SyntaxError | שמים פרמטר בלי ברירת מחדל אחרי פרמטר עם ברירת מחדל.Putting a parameter without a default after one 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. |
TypeError | משתמשים בתוצאה של פונקציה שלא מחזירה כלום.Using the result of a function that returns nothing. | 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. |
SyntaxError | שוכחים את הנקודתיים אחרי הגדרת הפונקציה.Forgetting the colon after the def line. | SyntaxError: expected ':': כמו if, גם def נגמר בנקודתיים.SyntaxError: expected ':': like if, def ends with a colon. |
TypeError | שוכחים סוגריים בקריאה, ומקבלים את הפונקציה עצמה במקום התוצאה.Forgetting the parentheses in a call, getting the function itself instead of its result. | 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. |