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

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

דיבאג עם VS CodeDebugging with VS Code

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

Breakpoints, stepping, watching variables and a method for finding bugs.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

תקנו את הממוצעFix the average

תזכורת: מה ביקשוReminder: the task

הפונקציה מחזירה ממוצע שגוי. מצאו את הבאג (אפשר עם הדפסות) ותקנו. average([10, 20, 30]) צריך להיות 20.

The function returns a wrong average. Find the bug (prints help) and fix it. average([10, 20, 30]) should be 20.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def average(nums):
    total = 0
    for n in nums:
        total += n
    return total / len(nums)

print(average([10, 20, 30]))
פלטOutput
20.0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

הספר שלא נמצאThe book that isn't found

תזכורת: מה ביקשוReminder: the task

החיפוש לא מוצא את dune אף שהספר קיים. השתמשו ב-repr כדי לראות למה, ותקנו כך ש-find("dune") תחזיר True.

The search doesn't find dune although the book exists. Use repr to see why, and fix it so find("dune") returns True.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
shelf = [" Dune", "Emma ", "Matilda"]

def find(title):
    for b in shelf:
        if b.strip().lower() == title.strip().lower():
            return True
    return False

print(find("dune"))
פלטOutput
True

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

שלושה באגיםThree bugs

תזכורת: מה ביקשוReminder: the task

הפונקציה אמורה להחזיר רשימה של המספרים הזוגיים מ-1 עד n (כולל). יש בה שלושה באגים. תקנו את כולם.

The function should return a list of even numbers from 1 to n (inclusive). It has three bugs. Fix them all.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def evens(n):
    result = []
    for i in range(1, n + 1):
        if i % 2 == 0:
            result.append(i)
    return result

print(evens(10))
פלטOutput
[2, 4, 6, 8, 10]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

assert שמגןA guarding assert

תזכורת: מה ביקשוReminder: the task

הוסיפו ל-discount(price, percent) שני assert: המחיר חיובי, והאחוז בין 0 ל-100 (עם הודעות). הפונקציה מחזירה את המחיר אחרי הנחה, מעוגל ל-2.

Add two asserts to discount(price, percent): the price is positive, and percent is 0 to 100 (with messages). It returns the price after the discount, rounded to 2.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def discount(price, percent):
    assert price > 0, "price must be positive"
    assert 0 <= percent <= 100, f"percent must be 0-100, got {percent}"
    return round(price * (1 - percent / 100), 2)

print(discount(80, 25))
פלטOutput
60.0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מדף, צעד 14: באג במדףShelf, step 14: a shelf bug

תזכורת: מה ביקשוReminder: the task

בגרסה הזו של המדף, מחיקת ספר מוחקת לפעמים ספר אחר, והספירה שגויה. מצאו ותקנו את שני הבאגים כך ש-remove_book תמחק לפי כותרת ו-count תחזיר את המספר הנכון.

In this shelf version, removing a book sometimes removes a different one, and the count is wrong. Find and fix both bugs so remove_book removes by title and count returns the right number.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
shelf.py
shelf = [{"title": "Dune"}, {"title": "Emma"}, {"title": "Matilda"}]

def remove_book(shelf, title):
    for i, b in enumerate(shelf):
        if b["title"] == title:
            del shelf[i]
            return True
    return False

def count(shelf):
    return len(shelf)

remove_book(shelf, "Emma")
print([b["title"] for b in shelf], count(shelf))
פלטOutput
['Dune', 'Matilda'] 2

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

חיפוש בינארי שבורA broken binary search

תזכורת: מה ביקשוReminder: the task

החיפוש הבינארי (נלמד לעומק במפגש 34) נתקע או מפספס את הפריט האחרון. תקנו אותו כך שיחזיר את האינדקס של target ברשימה ממוינת, או -1.

This binary search (covered in session 34) hangs or misses the last item. Fix it to return target's index in a sorted list, or -1.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def search(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

print(search([3, 8, 12, 20, 31], 31))
פלטOutput
4

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

רישום ביומןLogging it

תזכורת: מה ביקשוReminder: the task

כתבו process(orders) שעוברת על מחירים: מחיר שלילי נרשם כ-WARNING ומדולג, מחיר 0 נרשם כ-INFO ומדולג, והשאר נסכמים. הגדירו logging לרמת INFO עם הפורמט %(levelname)s: %(message)s ל-stdout, והדפיסו את הסכום.

Write process(orders) over prices: a negative price logs a WARNING and is skipped, 0 logs INFO and is skipped, the rest are summed. Configure logging at INFO with format %(levelname)s: %(message)s to stdout, and print the total.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import logging
import sys

logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s", stream=sys.stdout, force=True)
log = logging.getLogger("orders")

def process(orders):
    total = 0
    for p in orders:
        if p < 0:
            log.warning(f"negative price: {p}")
            continue
        if p == 0:
            log.info("free item skipped")
            continue
        total += p
    return total

print(process([40, -5, 0, 60]))
פלטOutput
WARNING: negative price: -5
INFO: free item skipped
100

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

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