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

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

Git ו-GitHubGit & GitHub

commit, branch, merge, push ו-README טוב.

commit, branch, merge, push and a good README.

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

המאגר הראשון שלכםYour first repo

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

על המחשב שלכם: התקינו Git, הגדירו שם ומייל, צרו תיקייה hello-git עם קובץ hello.py, ובצעו שני commits: אחד שיוצר את הקובץ ואחד שמשנה אותו. בסוף git log --oneline צריך להראות שתי שורות.

On your computer: install Git, set name and email, create a folder hello-git with hello.py, and make two commits: one creating the file and one changing it. At the end git log --oneline should show two lines.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
Terminal
git init
git add hello.py
git commit -m "Add hello script"
git commit -am "Greet by name"
git log --oneline

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

תרגילExercise 2

מה ייכנס ל-Git?What goes into Git?

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

כתבו ignored(path, patterns) שמחזירה True אם הנתיב תואם לאחת התבניות. תבנית שמסתיימת ב-/ היא תיקייה (מתאימה אם הנתיב מתחיל בה או מכיל אותה), ושאר התבניות נבדקות מול שם הקובץ עם fnmatch. ואז to_commit(paths, patterns) מחזירה את מה שלא מתעלמים ממנו.

Write ignored(path, patterns) returning True if the path matches a pattern. A pattern ending in / is a folder (matches if the path starts with it or contains it); others are checked against the file name with fnmatch. Then to_commit(paths, patterns) returns the paths not ignored.

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

def ignored(path, patterns):
    name = path.split("/")[-1]
    for p in patterns:
        if p.endswith("/"):
            if path.startswith(p) or "/" + p in "/" + path:
                return True
        elif fnmatch(name, p):
            return True
    return False

def to_commit(paths, patterns):
    return [p for p in paths if not ignored(p, patterns)]

patterns = [".venv/", "__pycache__/", "*.pyc", ".env"]
files = ["shelf.py", ".env", ".venv/bin/python", "src/__pycache__/a.pyc", "README.md", "old.pyc"]
print(to_commit(files, patterns))
פלטOutput
['shelf.py', 'README.md']

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

תרגילExercise 3

לקרוא git logReading git log

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

פלט של git log --oneline נתון כמחרוזת. כתבו parse_log(text) שמחזירה רשימת זוגות (hash, message), ו-bad_messages(commits) שמחזירה hashes של הודעות קצרות מ-10 תווים או שהן אחת המילים fix, wip, stuff (בלי רגישות לאותיות).

git log --oneline output is given as a string. Write parse_log(text) returning a list of (hash, message) pairs, and bad_messages(commits) returning hashes of messages shorter than 10 characters or equal to fix, wip, stuff (case-insensitive).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
LOG = """a1b2c3d Add search by author
9f8e7d6 fix
5c4b3a2 Sort books by title
0d1e2f3 WIP
77aa88b typo"""

def parse_log(text):
    return [tuple(line.split(" ", 1)) for line in text.splitlines() if line.strip()]

def bad_messages(commits):
    return [h for h, m in commits if len(m) < 10 or m.lower() in ("fix", "wip", "stuff")]

commits = parse_log(LOG)
print(len(commits), bad_messages(commits))
פלטOutput
5 ['9f8e7d6', '0d1e2f3', '77aa88b']

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

תרגילExercise 4

בודק הודעות commitA commit message checker

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

כתבו check_message(msg) שמחזירה רשימת בעיות (רשימה ריקה = הודעה טובה): "empty" אם ריקה, "too long" אם השורה הראשונה מעל 50 תווים, "capital" אם לא מתחילה באות גדולה, "period" אם השורה הראשונה מסתיימת בנקודה.

Write check_message(msg) returning a list of problems (empty list = a good message): "empty" if empty, "too long" if the first line exceeds 50 characters, "capital" if it doesn't start with a capital letter, "period" if the first line ends with a period.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 check_message(msg):
    if not msg.strip():
        return ["empty"]
    first = msg.strip().splitlines()[0]
    problems = []
    if len(first) > 50:
        problems.append("too long")
    if not first[0].isupper():
        problems.append("capital")
    if first.endswith("."):
        problems.append("period")
    return problems

for m in ["Add search by author", "fixed stuff.", ""]:
    print(repr(m), check_message(m))
פלטOutput
'Add search by author' []
'fixed stuff.' ['capital', 'period']
'' ['empty']

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

תרגילExercise 5

מדף, צעד 20: הפרויקט ב-GitHubShelf, step 20: the project on GitHub

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

על המחשב שלכם: בתיקיית פרויקט המדף צרו .gitignore (עם .venv/, __pycache__/, .env), git init, commit ראשון של כל הקבצים, צרו repo ב-GitHub, חברו עם git remote add origin ו-git push -u origin main. בדקו בדפדפן שהקבצים שם ושאין שם .venv.

On your computer: in the shelf project folder create .gitignore (with .venv/, __pycache__/, .env), git init, a first commit of all files, create a repo on GitHub, connect with git remote add origin and git push -u origin main. Check in the browser that the files are there and .venv isn't.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
Terminal
git init -b main
git add .
git commit -m "Shelf: first version"
git remote add origin https://github.com/<you>/shelf.git
git push -u origin main

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

אתגרChallenge 1

מפענח git statusA git status decoder

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

git status --porcelain מחזיר שורות כמו M shelf.py, M app.py, ?? notes.txt, A new.py, D old.py. שני התווים הראשונים: מצב ב-staging ומצב בתיקייה. כתבו summarize(text) שמחזירה מילון עם הרשימות staged, modified, untracked (קובץ יכול להופיע גם ב-staged וגם ב-modified, למשל MM).

git status --porcelain returns lines like M shelf.py, M app.py, ?? notes.txt, A new.py, D old.py. The first two characters: staging state and folder state. Write summarize(text) returning a dict with lists staged, modified, untracked (a file can be both staged and modified, e.g. MM).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 summarize(text):
    out = {"staged": [], "modified": [], "untracked": []}
    for line in text.splitlines():
        if not line.strip():
            continue
        x, y, path = line[0], line[1], line[3:]
        if x == "?":
            out["untracked"].append(path)
            continue
        if x != " ":
            out["staged"].append(path)
        if y != " ":
            out["modified"].append(path)
    return out

print(summarize("M  shelf.py\n M app.py\n?? notes.txt\nMM both.py"))
פלטOutput
{'staged': ['shelf.py', 'both.py'], 'modified': ['app.py', 'both.py'], 'untracked': ['notes.txt']}

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

אתגרChallenge 2

diff משלכםYour own diff

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

כתבו mini_diff(old, new) שמקבלת שתי מחרוזות רב-שורתיות ומחזירה רק את שורות השינוי בפורמט של git: -שורה לשורה שהוסרה ו-+שורה לשורה שנוספה. השתמשו ב-difflib.ndiff ושמרו רק שורות שמתחילות ב-- או + .

Write mini_diff(old, new) taking two multi-line strings and returning only the change lines in git style: -line for removed and +line for added. Use difflib.ndiff and keep only lines starting with - or + .

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

def mini_diff(old, new):
    return [d[0] + d[2:] for d in difflib.ndiff(old.splitlines(), new.splitlines()) if d[:2] in ("- ", "+ ")]

old = 'shelf = ["Dune", "Emma"]\nfor b in shelf:\n    print(b)'
new = 'shelf = ["Dune", "Emma", "Matilda"]\nfor b in sorted(shelf):\n    print(b)'
for line in mini_diff(old, new):
    print(line)
פלטOutput
-shelf = ["Dune", "Emma"]
+shelf = ["Dune", "Emma", "Matilda"]
-for b in shelf:
+for b in sorted(shelf):

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

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