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

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

קבציםFiles

קריאה וכתיבה, with, נתיבים עם pathlib וקידוד UTF-8.

Reading and writing, with, paths with pathlib and UTF-8 encoding.

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

שמירת רשימהSave a list

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

כתבו את שלושת הספרים ברשימה books לקובץ books.txt, ספר בשורה. אחר כך קראו את הקובץ והדפיסו כמה שורות יש בו.

Write the three books in books to books.txt, one per line. Then read the file back and print how many lines it has.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
books = ["Dune", "Emma", "Matilda"]
with open("books.txt", "w", encoding="utf-8") as f:
    for b in books:
        f.write(b + "\n")
with open("books.txt", encoding="utf-8") as f:
    print(len(f.readlines()))
פלטOutput
3

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

תרגילExercise 2

יומן קריאהReading log

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

כתבו log(pages) שמוסיפה לקובץ log.txt שורה read N pages (בלי למחוק את הקודם). קראו לה עם 40, 55 ו-20, ואז קראו את הקובץ והדפיסו את סך העמודים.

Write log(pages) that appends a line read N pages to log.txt (without erasing). Call it with 40, 55 and 20, then read the file and print the total pages.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 log(pages):
    with open("log.txt", "a", encoding="utf-8") as f:
        f.write(f"read {pages} pages\n")

for p in [40, 55, 20]:
    log(p)
total = 0
with open("log.txt", encoding="utf-8") as f:
    for line in f:
        total += int(line.split()[1])
print(total)
פלטOutput
115

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

תרגילExercise 3

ספירת מילים בקובץWords in a file

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

הקוד יוצר קובץ story.txt. קראו אותו והדפיסו כמה שורות, כמה מילים וכמה תווים (בלי ירידות שורה) יש בו, בפורמט lines: L, words: W, chars: C.

The code creates story.txt. Read it and print its lines, words and characters (without newlines) as lines: L, words: W, chars: C.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
with open("story.txt", "w", encoding="utf-8") as f:
    f.write("A prince on a planet\nwith one rose\nand three volcanoes\n")
with open("story.txt", encoding="utf-8") as f:
    text = f.read()
rows = text.splitlines()
print(f"lines: {len(rows)}, words: {len(text.split())}, chars: {sum(len(r) for r in rows)}")
פלטOutput
lines: 3, words: 11, chars: 52

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

תרגילExercise 4

תיקייה מסודרתA tidy folder

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

בעזרת pathlib צרו תיקייה notes, וכתבו בה שלושה קבצים day1.txt עד day3.txt שכל אחד מכיל Day N. הדפיסו את שמות הקבצים בתיקייה ממוינים, ואת התוכן של day2.txt.

With pathlib create a folder notes and write three files day1.txt to day3.txt, each containing Day N. Print the sorted file names in the folder, then the content of day2.txt.

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

folder = Path("notes")
folder.mkdir(exist_ok=True)
for i in range(1, 4):
    (folder / f"day{i}.txt").write_text(f"Day {i}", encoding="utf-8")
print(sorted(p.name for p in folder.iterdir()))
print((folder / "day2.txt").read_text(encoding="utf-8"))
פלטOutput
['day1.txt', 'day2.txt', 'day3.txt']
Day 2

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

תרגילExercise 5

מדף, צעד 12: שמירה וטעינהShelf, step 12: save and load

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

כתבו save(shelf, path) ששומרת כל ספר כשורה title|author, ו-load(path) שמחזירה רשימת מילונים (ורשימה ריקה אם הקובץ לא קיים). שמרו שני ספרים, טענו, והדפיסו את הכותרות.

Write save(shelf, path) storing each book as a line title|author, and load(path) returning a list of dicts (or an empty list if the file doesn't exist). Save two books, load them, and print the titles.

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

def save(shelf, path):
    with open(path, "w", encoding="utf-8") as f:
        for b in shelf:
            f.write(f"{b['title']}|{b['author']}\n")

def load(path):
    if not Path(path).exists():
        return []
    shelf = []
    with open(path, encoding="utf-8") as f:
        for line in f:
            title, author = line.strip().split("|")
            shelf.append({"title": title, "author": author})
    return shelf

save([{"title": "Dune", "author": "Frank Herbert"}, {"title": "Matilda", "author": "Roald Dahl"}], "shelf.txt")
for b in load("shelf.txt"):
    print(b["title"])
print(load("nothing.txt"))
פלטOutput
Dune
Matilda
[]

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

אתגרChallenge 1

המילים הנפוצותMost common words

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

הקוד יוצר קובץ טקסט. הדפיסו את 3 המילים הנפוצות בו (באותיות קטנות, בלי פיסוק), בפורמט word: n, מהנפוצה ביותר.

The code creates a text file. Print its 3 most common words (lowercase, no punctuation) as word: n, most common first.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
with open("text.txt", "w", encoding="utf-8") as f:
    f.write("The rose, the fox and the prince. The fox waited. A rose is a rose!")
counts = {}
with open("text.txt", encoding="utf-8") as f:
    for w in f.read().lower().split():
        w = w.strip(".,!?")
        counts[w] = counts.get(w, 0) + 1
for w, n in sorted(counts.items(), key=lambda kv: -kv[1])[:3]:
    print(f"{w}: {n}")
פלטOutput
the: 4
rose: 3
fox: 2

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

אתגרChallenge 2

גיבוי עם חותמתNumbered backups

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

כתבו backup(path) שמעתיקה קובץ ל-<שם>.bak1, ואם קיים כבר אז ל-.bak2 וכן הלאה, ומחזירה את שם הגיבוי. צרו shelf.txt, גבו שלוש פעמים, והדפיסו את שמות הגיבויים.

Write backup(path) that copies a file to <name>.bak1, or .bak2 if that exists, and so on, returning the backup name. Create shelf.txt, back it up three times, and print the backup names.

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

def backup(path):
    src = Path(path)
    n = 1
    while Path(f"{src}.bak{n}").exists():
        n += 1
    dst = Path(f"{src}.bak{n}")
    dst.write_text(src.read_text(encoding="utf-8"), encoding="utf-8")
    return dst.name

Path("shelf.txt").write_text("Dune\n", encoding="utf-8")
for _ in range(3):
    print(backup("shelf.txt"))
פלטOutput
shelf.txt.bak1
shelf.txt.bak2
shelf.txt.bak3

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

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