כלי שורת פקודה עם argparseCommand-line tools with argparse
ארגומנטים, תתי-פקודות, עזרה אוטומטית.
Arguments, sub-commands, automatic help.
כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-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
תרגיליםExercises
תרגילExercise 1
פרסר ראשוןA first parser
כתבו build_parser() שמחזירה ArgumentParser עם ארגומנט חובה city ואופציה --days (int, ברירת מחדל 3). הדפיסו את התוצאה של parse_args(["Haifa", "--days", "5"]).
Write build_parser() returning an ArgumentParser with a required city and a --days option (int, default 3). Print the result of parse_args(["Haifa", "--days", "5"]).
איך הפלט אמור להיראות?What should the output look like?
הוסיפו לפרסר של מחשבון טיפ: amount (float), --percent (int, ברירת מחדל 12) ודגל --round. tip(argv) מחזירה את הטיפ (amount × percent / 100), ואם יש --round מעגלת למספר שלם, אחרת ל-2 ספרות.
Build a tip calculator parser: amount (float), --percent (int, default 12) and a --round flag. tip(argv) returns the tip (amount × percent / 100), rounded to a whole number with --round, otherwise to 2 places.
איך הפלט אמור להיראות?What should the output look like?
כתבו convert(argv) עם ארגומנטים value (float) ו---to עם choices=["km", "mi"] (חובה). היא מחזירה את הערך מומר (km→mi: ×0.621371, mi→km: ÷0.621371) מעוגל ל-2. בחירה לא חוקית צריכה לגרום ל-SystemExit.
Write convert(argv) with value (float) and --to with choices=["km", "mi"] (required). It returns the converted value (km→mi: ×0.621371, mi→km: ÷0.621371) rounded to 2. An invalid choice must cause SystemExit.
איך הפלט אמור להיראות?What should the output look like?
כתבו main(argv) לכלי רשימת מטלות עם פקודות add TEXT ו-done N (N מספר שלם). היא מחזירה מחרוזת: added: TEXT או done: #N. השתמשו ב-subparsers עם dest="cmd" ו-required=True.
Write main(argv) for a to-do tool with commands add TEXT and done N (N an integer). It returns a string: added: TEXT or done: #N. Use subparsers with dest="cmd" and required=True.
איך הפלט אמור להיראות?What should the output look like?
מדף, צעד 27: shelf add / list / searchShelf, step 27: shelf add / list / search
פרויקט מלווהCompanion project
השלימו את run(argv, books) (books היא רשימה שמתעדכנת במקום, במקום קובץ): add TITLE AUTHOR [--pages N] מוסיפה ומחזירה added: TITLE; list [--sort title|pages] מחזירה מחרוזת עם שורה לכל ספר TITLE (PAGES); search TEXT מחזירה את הכותרות שמכילות את הטקסט (בלי רגישות לאותיות) בשורות, או no matches.
Complete run(argv, books) (books is a list updated in place, instead of a file): add TITLE AUTHOR [--pages N] adds and returns added: TITLE; list [--sort title|pages] returns a string with a line per book TITLE (PAGES); search TEXT returns matching titles (case-insensitive) one per line, or no matches.
איך הפלט אמור להיראות?What should the output look like?
added: Emma
added: Dune
Dune (412)
Emma (474)
Emma
shelf.py
רמזHint 1:שלוש פקודות עם set_defaults, או if a.cmd == ....Three commands with set_defaults, or if a.cmd == ....
רמזHint 2:"\n".join(...) לחיבור שורות."\n".join(...) to join lines.
בלי argparse: כתבו parse(argv, spec) ש-spec שלה הוא מילון אופציות → ברירת מחדל (למשל {"--days": 3, "--loud": False}). ערך בוליאני בברירת המחדל = דגל; אחרת האופציה לוקחת את המילה הבאה ומומרת לטיפוס של ברירת המחדל. מילים שאינן אופציות נאספות ל-"_". אופציה לא מוכרת: ValueError.
Without argparse: write parse(argv, spec) whose spec is a dict option → default (e.g. {"--days": 3, "--loud": False}). A boolean default = a flag; otherwise the option takes the next word, converted to the default's type. Non-option words are collected into "_". An unknown option: ValueError.
איך הפלט אמור להיראות?What should the output look like?
כתבו main(argv, out, err) לכלי check-isbn שמקבל ISBN אחד או יותר ובודק ISBN-13: 13 ספרות (מותר -), וספרת ביקורת נכונה (סכום הספרות כשכל ספרה במקום אי-זוגי ×1 ובמקום זוגי ×3 מתחלק ב-10). לכל ISBN תקין כותבים ל-out OK <isbn>, ולשגוי ל-err BAD <isbn>. מחזירים 0 אם כולם תקינים, אחרת 1.
Write main(argv, out, err) for a check-isbn tool taking one or more ISBNs and checking ISBN-13: 13 digits (dashes allowed), and a correct check digit (the digit sum with odd positions ×1 and even positions ×3 divides by 10). For each valid ISBN write OK <isbn> to out, for invalid write BAD <isbn> to err. Return 0 if all are valid, else 1.
איך הפלט אמור להיראות?What should the output look like?
OK 978-0441172719
OK 9780141439587
exit: 0
BAD 9780441172710
exit: 1
רמזHint 2:sum(int(d) * (3 if i % 2 else 1) for i, d in enumerate(digits)) % 10 == 0sum(int(d) * (3 if i % 2 else 1) for i, d in enumerate(digits)) % 10 == 0