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

PythonPython
23
חלקPart 4: נתונים ורשתData & the web כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

SQLiteSQLite

טבלאות, SQL בסיסי, sqlite3 ושאילתות בטוחות.

Tables, basic SQL, sqlite3 and safe queries.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. מה ההבדל בין WHERE ל-ORDER BY?What's the difference between WHERE and ORDER BY?

2. איך מכניסים קלט של משתמש לשאילתה בבטחה?How do you put user input into a query safely?

3. מה קורה ל-UPDATE books SET pages = 0 בלי WHERE?What does UPDATE books SET pages = 0 do without WHERE?

תרגיליםExercises

תרגילExercise 1

טבלת סרטיםA movies table

צרו מסד בזיכרון עם טבלה movies (id, title, year), הכניסו שלושה סרטים עם executemany, והדפיסו את כמות הסרטים ואת הכותרות ממוינות לפי שנה.

Create an in-memory database with a movies (id, title, year) table, insert three movies with executemany, and print the count and the titles sorted by year.

איך הפלט אמור להיראות?What should the output look like?
3
['Cars', 'Up', 'Coco']
main.py
רמזHint 1: CREATE TABLE movies (id INTEGER PRIMARY KEY, title TEXT, year INTEGER)CREATE TABLE movies (id INTEGER PRIMARY KEY, title TEXT, year INTEGER)
רמזHint 2: [r[0] for r in con.execute("SELECT title FROM movies ORDER BY year")][r[0] for r in con.execute("SELECT title FROM movies ORDER BY year")]
לפתרוןSolution
תרגילExercise 2

חיפוש בטוחA safe search

בעזרת הטבלה הנתונה, כתבו by_author(con, name) שמחזירה רשימת כותרות של הסופר (חיפוש חלקי, LIKE עם %), ממוינת לפי שנה. השתמשו ב-? בלבד.

Using the given table, write by_author(con, name) returning the author's titles (partial match, LIKE with %), sorted by year. Use ? only.

איך הפלט אמור להיראות?What should the output look like?
['The BFG', 'Matilda']
[]
main.py
רמזHint 1: הערך עצמו מכיל את ה-%: ("%" + name + "%",)The value itself carries the %: ("%" + name + "%",)
רמזHint 2: [r[0] for r in ...][r[0] for r in ...]
לפתרוןSolution
תרגילExercise 3

עדכון ומחיקהUpdate and delete

כתבו set_pages(con, title, pages) שמעדכנת את מספר העמודים של ספר ומחזירה כמה שורות השתנו, ו-remove(con, title) שמוחקת ספר ומחזירה כמה נמחקו. השתמשו ב-with con:.

Write set_pages(con, title, pages) that updates a book's page count and returns how many rows changed, and remove(con, title) that deletes a book and returns how many were deleted. Use with con:.

איך הפלט אמור להיראות?What should the output look like?
1 1 0
[('Dune', 604), ('Matilda', 240), ('The BFG', 208)]
main.py
רמזHint 1: cur = con.execute("UPDATE books SET pages = ? WHERE title = ?", (pages, title))cur = con.execute("UPDATE books SET pages = ? WHERE title = ?", (pages, title))
רמזHint 2: return cur.rowcountreturn cur.rowcount
לפתרוןSolution
תרגילExercise 4

סטטיסטיקה ב-SQLStats in SQL

כתבו שאילתה אחת שמחזירה לכל סופר: שם, מספר ספרים וממוצע עמודים מעוגל (ROUND(AVG(pages))), ממוינת לפי מספר ספרים מהגבוה ואז לפי שם. החזירו אותה מ-author_stats(con) כרשימת טאפלים.

Write one query returning for each author: name, book count and rounded average pages (ROUND(AVG(pages))), sorted by count descending then by name. Return it from author_stats(con) as a list of tuples.

איך הפלט אמור להיראות?What should the output look like?
('Roald Dahl', 2, 224.0)
('Frank Herbert', 1, 412.0)
('Jane Austen', 1, 474.0)
main.py
רמזHint 1: GROUP BY authorGROUP BY author
רמזHint 2: ORDER BY COUNT(*) DESC, authorORDER BY COUNT(*) DESC, author
לפתרוןSolution
תרגילExercise 5

מדף, צעד 23: המדף עובר למסדShelf, step 23: the shelf moves to a database

פרויקט מלווהCompanion project

כתבו מחלקה ShelfDB(path) שמתחברת למסד ויוצרת (IF NOT EXISTS) טבלה books (id, title UNIQUE, author, pages, read DEFAULT 0). מתודות: add(title, author, pages) (מחזירה id), find(text) (חיפוש חלקי בכותרת או בסופר, מחזירה רשימת מילונים), mark_read(title, pages), ו-progress() שמחזירה אחוז כולל מעוגל של עמודים שנקראו. השתמשו ב-con.row_factory = sqlite3.Row כדי לקבל שורות שאפשר להפוך למילון.

Write a class ShelfDB(path) that connects and creates (IF NOT EXISTS) a table books (id, title UNIQUE, author, pages, read DEFAULT 0). Methods: add(title, author, pages) (returns the id), find(text) (partial match on title or author, returns a list of dicts), mark_read(title, pages), and progress() returning the overall rounded percent of pages read. Use con.row_factory = sqlite3.Row to get rows that convert to dicts.

איך הפלט אמור להיראות?What should the output look like?
[{'id': 2, 'title': 'Matilda', 'author': 'Roald Dahl', 'pages': 240, 'read': 0}]
63
shelf_db.py
רמזHint 1: cur.lastrowid הוא ה-id החדש.cur.lastrowid is the new id.
רמזHint 2: SELECT SUM(read), SUM(pages) FROM booksSELECT SUM(read), SUM(pages) FROM books
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

ביקורות ו-JOINReviews and JOIN

הוסיפו טבלה reviews (book_id, stars) עם ביקורות, וכתבו top_rated(con, min_reviews=2) שמחזירה טאפלים (title, avg_stars, count) לספרים עם לפחות min_reviews ביקורות, ממוינים לפי ממוצע מהגבוה (ממוצע מעוגל ל-2). השתמשו ב-JOIN, GROUP BY ו-HAVING.

Add a reviews (book_id, stars) table with reviews, and write top_rated(con, min_reviews=2) returning tuples (title, avg_stars, count) for books with at least min_reviews reviews, sorted by average descending (rounded to 2). Use JOIN, GROUP BY and HAVING.

איך הפלט אמור להיראות?What should the output look like?
[('Matilda', 4.67, 3), ('Dune', 4.5, 2)]
('The BFG', 2.0, 1)
main.py
רמזHint 1: HAVING COUNT(*) >= ? מסנן קבוצות (WHERE מסנן שורות).HAVING COUNT(*) >= ? filters groups (WHERE filters rows).
רמזHint 2: ROUND(AVG(r.stars), 2)ROUND(AVG(r.stars), 2)
לפתרוןSolution
אתגרChallenge 2

הגירה מ-JSONMigrating from JSON

כתבו migrate(json_text, con) שמקבלת את קובץ ה-JSON של המדף הישן (רשימת מילונים עם title, author, pages ואולי read), יוצרת טבלה אם צריך, ומכניסה הכול בטרנזקציה אחת. ספר בלי title מדולג; כותרת שכבר קיימת לא מוכנסת שוב (INSERT OR IGNORE). מחזירה כמה ספרים נוספו בפועל.

Write migrate(json_text, con) taking the old shelf's JSON (a list of dicts with title, author, pages and maybe read), creating the table if needed, and inserting everything in one transaction. A book without a title is skipped; a title that already exists isn't inserted again (INSERT OR IGNORE). Return how many books were actually added.

איך הפלט אמור להיראות?What should the output look like?
2 0
[('Dune', 'Frank Herbert', 103), ('Emma', '', 0)]
main.py
רמזHint 1: con.total_changes לפני ואחרי סופר שינויים.con.total_changes before and after counts changes.
רמזHint 2: b.get("read", 0) לשדה אופציונלי.b.get("read", 0) for an optional field.
לפתרוןSolution

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