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

PythonPython
15
חלקPart 3: קוד נקי ו-OOPClean code & OOP כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

מחלקות ואובייקטיםClasses & objects

class, __init__, self, תכונות ומתודות.

class, __init__, self, attributes and methods.

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

מחלקת כלבA Dog class

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

כתבו מחלקה Dog עם name ו-sound (ברירת מחדל "Woof"), ומתודה speak() שמחזירה "<name> says <sound>". צרו את Rex והדפיסו את מה שהוא אומר.

Write a Dog class with name and sound (default "Woof"), and a speak() method returning "<name> says <sound>". Create Rex and print what he says.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
class Dog:
    def __init__(self, name, sound="Woof"):
        self.name = name
        self.sound = sound

    def speak(self):
        return f"{self.name} says {self.sound}"

print(Dog("Rex").speak())
פלטOutput
Rex says Woof

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

תרגילExercise 2

חשבון בנקA bank account

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

כתבו Account עם owner ו-balance שמתחיל ב-0. deposit(x) מוסיפה, withdraw(x) מורידה רק אם יש מספיק ומחזירה True, אחרת מחזירה False ולא משנה דבר.

Write Account with owner and balance starting at 0. deposit(x) adds, withdraw(x) subtracts only if there's enough and returns True, otherwise returns False and changes nothing.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
class Account:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0

    def deposit(self, x):
        self.balance += x

    def withdraw(self, x):
        if x > self.balance:
            return False
        self.balance -= x
        return True

acc = Account("Noa")
acc.deposit(100)
print(acc.withdraw(30), acc.withdraw(500), acc.balance)
פלטOutput
True False 70

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

תרגילExercise 3

מלבןA rectangle

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

כתבו Rect(w, h) עם מתודות area(), perimeter() ו-is_square(). הדפיסו את שלושתן עבור Rect(3, 4).

Write Rect(w, h) with methods area(), perimeter() and is_square(). Print all three for Rect(3, 4).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
class Rect:
    def __init__(self, w, h):
        self.w = w
        self.h = h

    def area(self):
        return self.w * self.h

    def perimeter(self):
        return 2 * (self.w + self.h)

    def is_square(self):
        return self.w == self.h

r = Rect(3, 4)
print(r.area(), r.perimeter(), r.is_square())
פלטOutput
12 14 False

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

תרגילExercise 4

רשימת קניותA shopping list

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

כתבו ShoppingList עם add(item, qty=1) (אם הפריט קיים, מגדילים כמות), remove(item), ו-total_items() שמחזירה את סך הכמויות. שמרו את הפריטים במילון self.items.

Write ShoppingList with add(item, qty=1) (if it exists, increase the quantity), remove(item), and total_items() returning the sum of quantities. Keep items in a dict self.items.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
class ShoppingList:
    def __init__(self):
        self.items = {}

    def add(self, item, qty=1):
        self.items[item] = self.items.get(item, 0) + qty

    def remove(self, item):
        self.items.pop(item, None)

    def total_items(self):
        return sum(self.items.values())

s = ShoppingList()
s.add("milk")
s.add("eggs", 12)
s.add("milk", 2)
s.remove("bread")
print(s.items, s.total_items())
פלטOutput
{'milk': 3, 'eggs': 12} 15

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

תרגילExercise 5

מדף, צעד 15: Book ו-LibraryShelf, step 15: Book and Library

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

הפכו את המדף למחלקות. Book(title, author, pages) עם read שמתחיל ב-0 ומתודה read_pages(n) (לא עוברים את pages). Library עם add(book), find(title) (בלי רגישות לאותיות גדולות, או None), ו-unread() שמחזירה רשימת כותרות של ספרים שלא התחילו.

Turn the shelf into classes. Book(title, author, pages) with read starting at 0 and a read_pages(n) method (never past pages). Library with add(book), find(title) (case-insensitive, or None), and unread() returning titles of books not started.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
shelf.py
class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages
        self.read = 0

    def read_pages(self, n):
        self.read = min(self.read + n, self.pages)

class Library:
    def __init__(self):
        self.books = []

    def add(self, book):
        self.books.append(book)

    def find(self, title):
        for b in self.books:
            if b.title.lower() == title.lower():
                return b
        return None

    def unread(self):
        return [b.title for b in self.books if b.read == 0]

lib = Library()
lib.add(Book("Dune", "Frank Herbert", 412))
lib.add(Book("Emma", "Jane Austen", 474))
lib.find("dune").read_pages(50)
print(lib.unread())
פלטOutput
['Emma']

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

אתגרChallenge 1

מחסניתA stack

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

כתבו Stack עם push(x), pop() (מחזירה את האחרון ומוציאה; על מחסנית ריקה מחזירה None), peek() (מחזירה בלי להוציא), is_empty() ו-size(). השתמשו בה כדי לבדוק אם הסוגריים במחרוזת מאוזנים: balanced("(a[b]{c})") → True.

Write Stack with push(x), pop() (returns and removes the last; on an empty stack returns None), peek() (returns without removing), is_empty() and size(). Use it to check whether brackets in a string are balanced: balanced("(a[b]{c})") → 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
class Stack:
    def __init__(self):
        self.items = []

    def push(self, x):
        self.items.append(x)

    def pop(self):
        return self.items.pop() if self.items else None

    def peek(self):
        return self.items[-1] if self.items else None

    def is_empty(self):
        return not self.items

    def size(self):
        return len(self.items)

def balanced(text):
    pairs = {")": "(", "]": "[", "}": "{"}
    s = Stack()
    for ch in text:
        if ch in "([{":
            s.push(ch)
        elif ch in pairs:
            if s.pop() != pairs[ch]:
                return False
    return s.is_empty()

print(balanced("(a[b]{c})"), balanced("(]"), balanced("(("))
פלטOutput
True False False

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

אתגרChallenge 2

טיימר משימותA task timer

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

כתבו Task(name) עם log(minutes) שמוסיפה זמן, ו-Tracker שמחזיקה משימות: start(name) יוצרת משימה אם אין (ומחזירה אותה), total() מחזירה את כל הדקות, ו-top() מחזירה את שם המשימה עם הכי הרבה דקות.

Write Task(name) with log(minutes) adding time, and Tracker holding tasks: start(name) creates the task if missing (and returns it), total() returns all minutes, top() returns the name of the task with the most minutes.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
class Task:
    def __init__(self, name):
        self.name = name
        self.minutes = 0

    def log(self, minutes):
        self.minutes += minutes

class Tracker:
    def __init__(self):
        self.tasks = {}

    def start(self, name):
        if name not in self.tasks:
            self.tasks[name] = Task(name)
        return self.tasks[name]

    def total(self):
        return sum(t.minutes for t in self.tasks.values())

    def top(self):
        return max(self.tasks.values(), key=lambda t: t.minutes).name

tr = Tracker()
tr.start("read").log(30)
tr.start("code").log(45)
tr.start("read").log(25)
print(tr.total(), tr.top())
פלטOutput
100 read

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

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