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

PythonPython
27
חלקPart 5: בונים דבריםBuilding things כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

כלי שורת פקודה עם 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

1. מה יש ב-sys.argv[0]?What's in sys.argv[0]?

2. איך מגדירים דגל --verbose בלי ערך?How do you define a --verbose flag without a value?

3. מה אומר קוד יציאה 0?What does exit code 0 mean?

תרגילים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?
Haifa 5
main.py
רמזHint 1: p.add_argument("city")p.add_argument("city")
רמזHint 2: p.add_argument("--days", type=int, default=3)p.add_argument("--days", type=int, default=3)
לפתרוןSolution
תרגילExercise 2

דגליםFlags

הוסיפו לפרסר של מחשבון טיפ: 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?
22.5 28
main.py
רמזHint 1: p.add_argument("--round", action="store_true")p.add_argument("--round", action="store_true")
רמזHint 2: args.round הוא True או False.args.round is True or False.
לפתרוןSolution
תרגילExercise 3

choices ושגיאותchoices and errors

כתבו 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?
26.22 42.16
main.py
רמזHint 1: p.add_argument("--to", choices=["km", "mi"], required=True)p.add_argument("--to", choices=["km", "mi"], required=True)
רמזHint 2: --to mi אומר שהקלט בק"מ.--to mi means the input is in km.
לפתרוןSolution
תרגילExercise 4

פקודות-משנהSubcommands

כתבו 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?
added: read Dune
done: #3
main.py
רמזHint 1: sub = p.add_subparsers(dest="cmd", required=True)sub = p.add_subparsers(dest="cmd", required=True)
רמזHint 2: if a.cmd == "add": ...if a.cmd == "add": ...
לפתרוןSolution
תרגילExercise 5

מדף, צעד 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.
לפתרוןSolution

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

אתגרChallenge 1

פרסר משלכםYour own parser

בלי 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?
{'days': 5, 'loud': True, 'unit': 'C', '_': ['Haifa', 'extra']}
main.py
רמזHint 1: לולאת while עם אינדקס, כי אופציה "אוכלת" גם את המילה הבאה.A while loop with an index, since an option also "eats" the next word.
רמזHint 2: type(default)(value) ממיר לטיפוס הנכון.type(default)(value) converts to the right type.
לפתרוןSolution
אתגרChallenge 2

main עם קוד יציאהmain with an exit code

כתבו 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
main.py
רמזHint 1: digits = isbn.replace("-", "")digits = isbn.replace("-", "")
רמז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
לפתרוןSolution

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