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

PythonPython

כל הסיכומיםAll summaries

הנקודות החשובות של כל מפגש. לכל מפגש יש גם עמוד סיכום מלא עם דף עזר וטבלת שגיאות.

The key points of every session. Each session also has a full summary page with a cheatsheet and an error table.

חלקPart 1: יסודותFoundations

מפגשSession 1: מה זה תכנות? התקנה וטרמינלWhat is programming? Setup & terminal

  • תוכנית היא רשימת הוראות שמתבצעות לפי הסדר, מלמעלה למטה.A program is a list of instructions that run in order, top to bottom.
  • המפרש של Python קורא את הקוד ומבצע אותו שורה אחרי שורה.Python's interpreter reads the code and runs it line by line.
  • Windows: מסמנים Add to PATH ומריצים python. Mac: מריצים python3.Windows: tick Add to PATH and run python. Mac: run python3.
  • טרמינל: pwd, ls/dir, cd, cd .., mkdir.Terminal: pwd, ls/dir, cd, cd .., mkdir.
  • print מציגה ערכים. טקסט במירכאות, חישובים בלי. פסיק מפריד בין ערכים.print shows values. Text in quotes, calculations without. A comma separates values.
  • אופרטורים: + - * / וגם // (חילוק שלם), % (שארית), ** (חזקה).Operators: + - * / plus // (whole division), % (remainder), ** (power).
  • # מתחיל הערה. רווח בתחילת שורה הוא שגיאה (בינתיים).# starts a comment. A leading space is an error (for now).
  • קוראים שגיאה מלמטה: סוג → שורה → מה שונה ממה שהתכוונתי.Read an error from the bottom: type → line → what differs from what I meant.

מפגשSession 2: משתנים, print ו-inputVariables, print & input

  • משתנה = שם שמצביע על ערךVariable = a name pointing to a value
  • = הוא השמה, לא שוויון= means assign, not equals
  • אותיות, ספרות וקו תחתון; לא מתחילים בספרהLetters, digits, underscore; never start with a digit
  • snake_case: book_titlesnake_case: book_title
  • x = x + 1 מחשב ואז מעדכןx = x + 1 computes, then updates
  • x += 1 הוא קיצורx += 1 is the shortcut
  • input() מחכה להקלדהinput() waits for typing
  • תמיד מחזיר מחרוזתAlways returns a string
  • f"...{x}..." מכניס ערכים לטקסטf"...{x}..." puts values in text

מפגשSession 3: טיפוסים ומספריםTypes & numbers

  • int שלם, float עשרוניint whole, float decimal
  • str טקסט, bool אמת/שקרstr text, bool true/false
  • int("7") → 7int("7") → 7
  • float("2.5") → 2.5float("2.5") → 2.5
  • השוואות מחזירות True/FalseComparisons return True/False
  • == שווה, != שונה== equal, != not equal
  • round(x, 2) לשתי ספרותround(x, 2) to two places
  • 0.1 + 0.2 הוא 0.300000000000000040.1 + 0.2 is 0.30000000000000004
  • import math טוען מודולimport math loads a module

מפגשSession 4: מחרוזותStrings

  • הספירה מתחילה ב-0Counting starts at 0
  • s[-1] הוא התו האחרוןs[-1] is the last character
  • s[a:b] מ-a עד לפני bs[a:b] from a up to (not incl.) b
  • s[:3] ההתחלה, s[3:] ההמשךs[:3] the start, s[3:] the rest
  • .strip() מנקה רווחים בקצוות.strip() trims spaces at the ends
  • .upper() .lower() .title().upper() .lower() .title()
  • "a" in s → True/False"a" in s → True/False
  • .find() מחזיר מיקום או -1.find() returns a position or -1
  • {x:<10} יישור לשמאל ברוחב 10{x:<10} left-align, width 10

מפגשSession 5: תנאיםConditions

  • if תנאי: ואז בלוק מוזחif condition: then an indented block
  • הבלוק רץ רק אם התנאי TrueThe block runs only if the condition is True
  • else כשאף תנאי לא התקייםelse when no condition held
  • elif בודק תנאי נוסףelif checks another condition
  • == != < > <= >=== != < > <= >=
  • = משייך, == משווה= assigns, == compares
  • and: שניהם נכוניםand: both true
  • or: לפחות אחדor: at least one
  • 0, "", None הם falsy0, "", None are falsy

מפגשSession 6: לולאותLoops

  • חוזר כל עוד התנאי TrueRepeats while the condition is True
  • משהו בתוך הלולאה חייב לשנות את התנאיSomething inside must change the condition
  • for x in רצף:for x in sequence:
  • עובד על מחרוזות, רשימות ו-rangeWorks on strings, lists and range
  • range(5) → 0..4range(5) → 0..4
  • range(1, 6) → 1..5range(1, 6) → 1..5
  • מתחילים ב-0 לפני הלולאהStart at 0 before the loop
  • מוסיפים בכל סיבובAdd on every pass
  • break יוצא מהלולאה מידbreak leaves the loop at once

מפגשSession 7: רשימותLists

  • [a, b, c] בסוגריים מרובעים[a, b, c] in square brackets
  • אינדקסים וחיתוך כמו במחרוזתIndexing and slicing like strings
  • .append(x) מוסיף לסוף.append(x) adds to the end
  • .remove(x), .pop(), del.remove(x), .pop(), del
  • b = a לא מעתיק רשימהb = a doesn't copy a list
  • שינוי דרך b נראה גם דרך aA change through b shows through a
  • for book in books:for book in books:
  • enumerate נותן גם מספרenumerate also gives a number
  • .sort() משנה את הרשימה.sort() changes the list

מפגשSession 8: מילונים, טאפלים וסטיםDicts, tuples & sets

  • {מפתח: ערך}{key: value}
  • d[key] קורא, d[key] = x כותבd[key] reads, d[key] = x writes
  • for k in d: נותן מפתחותfor k in d: gives keys
  • .items() נותן זוגות.items() gives pairs
  • רשימה = הרבה רשומותA list = many records
  • כל רשומה = מילוןEach record = a dict
  • (a, b) בסוגריים עגולים(a, b) in round brackets
  • immutable: אי אפשר לשנותImmutable: can't be changed
  • set(lst) מסיר כפילויותset(lst) removes duplicates

חלקPart 2: פונקציות וקוד אמיתיFunctions & real code

מפגשSession 9: פונקציותFunctions

  • def name(): + בלוק מוזחdef name(): + an indented block
  • ההגדרה לא מריצה כלוםDefining runs nothing
  • def greet(name):def greet(name):
  • הערך בקריאה מגיע לפרמטרThe call's value lands in the parameter
  • def f(x, unit="cm"):def f(x, unit="cm"):
  • קריאה לפי שם: f(5, unit="m")Keyword call: f(5, unit="m")
  • return x מחזיר ערך לקוראreturn x hands a value back
  • אחרי return הפונקציה נגמרתAfter return the function ends
  • שם פונקציה = פועל: add_bookFunction name = a verb: add_book

מפגשSession 10: Scope וערכי החזרהScope & return values

  • print מציגה לבני אדםprint shows humans
  • return מוסרת ערך לקודreturn hands a value to code
  • כל קריאה יוצרת frame חדשEach call creates a new frame
  • פרמטרים ומשתנים מקומיים חיים שםParameters and locals live there
  • פונקציה יכולה לקרוא משתנה גלובליA function can read a global
  • השמה בתוך פונקציה יוצרת משתנה מקומיAssigning inside a function makes a local
  • return a, b מחזיר טאפלreturn a, b returns a tuple
  • מפרקים: x, y = f()Unpack: x, y = f()
  • טהורה: אותו קלט → אותו פלטPure: same input → same output

מפגשSession 11: שגיאות ו-try/exceptErrors & try/except

  • מלמטה למעלהBottom to top
  • השורה האחרונה: סוג והסברLast line: type and message
  • try: קוד שעלול להיכשלtry: code that might fail
  • except ValueError: מה עושים אם נכשלexcept ValueError: what to do if it fails
  • while True + try + breakwhile True + try + break
  • ההודעה אומרת מה לתקןThe message says what to fix
  • else: רץ אם לא הייתה שגיאהelse: runs if there was no error
  • finally: רץ תמידfinally: always runs
  • raise ValueError("הסבר")raise ValueError("message")

מפגשSession 12: קבציםFiles

  • open(שם, "w", encoding="utf-8")open(name, "w", encoding="utf-8")
  • f.write(טקסט) לא מוסיף ירידת שורהf.write(text) adds no newline
  • f.read() הכול כמחרוזת אחתf.read() all as one string
  • for line in f: שורה אחרי שורהfor line in f: line by line
  • "r" קריאה (ברירת מחדל)"r" read (default)
  • "w" כתיבה מאפס"w" write from scratch
  • with סוגר את הקובץ לבדwith closes the file for you
  • גם אם הייתה שגיאה באמצעEven if an error happened midway
  • Path("data") / "books.txt"Path("data") / "books.txt"

מפגשSession 13: מודולים, pip ו-venvModules, pip & venv

  • import random ואז random.choiceimport random then random.choice
  • from math import sqrtfrom math import sqrt
  • datetime: תאריכים וזמניםdatetime: dates and times
  • collections: Counter ועודcollections: Counter and more
  • כל קובץ ‎.py הוא מודולEvery .py file is a module
  • import books טוען את books.pyimport books loads books.py
  • __name__ הוא "__main__" כשמריצים ישירות__name__ is "__main__" when run directly
  • וכשמייבאים: שם המודולAnd when imported: the module's name
  • python -m pip install requestspython -m pip install requests

מפגשSession 14: דיבאג עם VS CodeDebugging with VS Code

  • לשחזר: מה בדיוק קרה?Reproduce: what exactly happened?
  • לצמצם: איפה בדיוק?Narrow down: where exactly?
  • נקודת עצירה: לחיצה ליד מספר השורהBreakpoint: click by the line number
  • F5 מתחיל, F10 צעד, F11 נכנס לפונקציהF5 starts, F10 steps, F11 steps in
  • print(f"{x=}") מדפיס שם וערךprint(f"{x=}") prints name and value
  • repr מראה רווחים ומירכאותrepr shows spaces and quotes
  • assert תנאי, "הודעה"assert condition, "message"
  • נכשל מוקדם ובקולFails early and loudly
  • רמות: DEBUG, INFO, WARNING, ERRORLevels: DEBUG, INFO, WARNING, ERROR

חלקPart 3: קוד נקי ו-OOPClean code & OOP

מפגשSession 15: מחלקות ואובייקטיםClasses & objects

  • נתונים + פעולות במקום אחדData + actions in one place
  • מילון עם פונקציות מפוזרות → מחלקהA dict with scattered functions → a class
  • __init__ רץ ביצירה__init__ runs on creation
  • self.title = title שומר תכונהself.title = title stores an attribute
  • def read(self, n): בתוך המחלקהdef read(self, n): inside the class
  • קוראים: book.read(50)Call: book.read(50)
  • כל אובייקט שומר מצב משלוEach object keeps its own state
  • שינוי אחד לא משפיע על השניChanging one doesn't affect another
  • Library מחזיקה רשימת BookLibrary holds a list of Book

מפגשSession 16: ירושהInheritance

  • class EBook(Book):class EBook(Book):
  • הבן מקבל הכול מהאבThe child gets everything from the parent
  • הבן מוסיף תכונה משלוThe child adds its own attribute
  • super().__init__(...) מפעיל את האבsuper().__init__(...) runs the parent's
  • אותו שם מתודה בבן = גרסה חדשהSame method name in the child = a new version
  • super().label() משתמש בגרסה של האבsuper().label() reuses the parent's version
  • רשימה של סוגים שוניםA list of different kinds
  • אותה קריאה לכולםThe same call for all
  • אפשר לרשת מבן של בןYou can inherit from a child of a child

מפגשSession 17: Dunder methodsDunder methods

  • שני קווים תחתונים מכל צדTwo underscores on each side
  • פייתון קוראת להן בעצמהPython calls them itself
  • __str__: למשתמש, print__str__: for users, print
  • __repr__: למתכנת, רשימות ודיבאג__repr__: for programmers, lists and debugging
  • ברירת מחדל: == משווה זהותDefault: == compares identity
  • __eq__ קובע מה נחשב שווה__eq__ decides what counts as equal
  • __lt__ = less than, <__lt__ = less than, <
  • מספיק כדי ש-sorted יעבודEnough for sorted to work
  • __len__ → len(shelf)__len__ → len(shelf)

מפגשSession 18: Dataclasses ו-type hintsDataclasses & type hints

  • def f(title: str, pages: int) -> str:def f(title: str, pages: int) -> str:
  • פייתון לא אוכפת אותםPython doesn't enforce them
  • list[str], dict[str, int]list[str], dict[str, int]
  • `str | None`: אולי כלום`str | None`: maybe nothing
  • שדות עם רמזים במקום __init__Fields with hints instead of __init__
  • __repr__ ו-__eq__ בחינם__repr__ and __eq__ for free
  • read: int = 0read: int = 0
  • רשימה כברירת מחדל: field(default_factory=list)A list default: field(default_factory=list)
  • @dataclass(frozen=True): אי אפשר לשנות@dataclass(frozen=True): can't be changed

מפגשSession 19: בדיקות עם pytestTesting with pytest

  • בדיקה ידנית = לשכוח משהוManual checking = forgetting something
  • בדיקה אוטומטית רצה בשנייהAn automated test runs in a second
  • קובץ בשם test_*.pyA file named test_*.py
  • פונקציות בשם test_*Functions named test_*
  • F במקום נקודהF instead of a dot
  • pytest מראה את הערכים בפועלpytest shows the actual values
  • with pytest.raises(ValueError):with pytest.raises(ValueError):
  • מקרי קצה: ריק, אפס, גבולEdge cases: empty, zero, limit
  • fixture: נתונים מוכנים לכל בדיקהfixture: ready data for each test

מפגשSession 20: Git ו-GitHubGit & GitHub

  • final_v2_REAL.py זה לא שיטהfinal_v2_REAL.py is not a system
  • היסטוריה מלאה, חזרה לכל נקודהFull history, return to any point
  • git init יוצר מאגרgit init creates a repo
  • git add → אזור ההכנה (staging)git add → staging area
  • git diff: מה השתנה ועדיין לא נשמרgit diff: what changed and isn't saved yet
  • git log --oneline: רשימת ה-commitsgit log --oneline: the list of commits
  • לא שומרים .venv/ ו-__pycache__/Don't save .venv/ and __pycache__/
  • לעולם לא סיסמאות ומפתחותNever passwords and keys
  • git switch -c feature יוצר ענף ועובר אליוgit switch -c feature creates a branch and moves to it

חלקPart 4: נתונים ורשתData & the web

מפגשSession 21: JSON ו-CSVJSON & CSV

  • נראה כמעט כמו מילון של פייתוןLooks almost like a Python dict
  • true/false/null במקום True/False/Nonetrue/false/null instead of True/False/None
  • json.dump(data, f) כותב לקובץjson.dump(data, f) writes to a file
  • json.load(f) קורא מקובץjson.load(f) reads from a file
  • dict, list, str, int, float, bool, Nonedict, list, str, int, float, bool, None
  • לא set, לא תאריך, לא אובייקטNo set, no date, no object
  • שורה ראשונה: כותרותFirst line: headers
  • csv.DictReader → מילון לכל שורהcsv.DictReader → a dict per row
  • csv.DictWriter(f, fieldnames=[...])csv.DictWriter(f, fieldnames=[...])

מפגשSession 22: APIs עם requestsAPIs with requests

  • דף לבני אדם, API לתוכנותPages for people, APIs for programs
  • בקשה → תשובה עם קוד וגוףRequest → reply with a code and a body
  • 200 הצליח, 404 לא נמצא, 500 תקלה אצלם200 OK, 404 not found, 500 their problem
  • r.ok = True לכל 2xxr.ok = True for any 2xx
  • params={"q": "dune"} במקום לבנות מחרוזתparams={"q": "dune"} instead of building a string
  • requests מקודד רווחים ותווים מיוחדיםrequests encodes spaces and special characters
  • תמיד timeout=Always timeout=
  • requests.exceptions.RequestException תופסת הכולrequests.exceptions.RequestException catches them all
  • GET מבקש, POST שולחGET asks, POST sends

מפגשSession 23: SQLiteSQLite

  • JSON טוב לקצת נתוניםJSON is fine for a little data
  • מסד: חיפוש מהיר, עדכון של שורה אחתA database: fast search, update one row
  • CREATE TABLE עם עמודות וטיפוסיםCREATE TABLE with columns and types
  • `id INTEGER PRIMARY KEY` גדל לבד`id INTEGER PRIMARY KEY` grows by itself
  • WHERE מסנן, ORDER BY ממיין, LIMIT חותךWHERE filters, ORDER BY sorts, LIMIT trims
  • LIKE '%dahl%' לחיפוש חלקיLIKE '%dahl%' for partial search
  • לעולם לא f-string בתוך SQLNever an f-string inside SQL
  • ? + טאפל ערכים? + a tuple of values
  • UPDATE ... SET ... WHEREUPDATE ... SET ... WHERE

מפגשSession 24: pandas למתחיליםpandas for beginners

  • import pandas as pdimport pandas as pd
  • pd.read_csv → DataFramepd.read_csv → a DataFrame
  • df["title"] → Seriesdf["title"] → a Series
  • df[["title", "pages"]] → טבלה קטנהdf[["title", "pages"]] → a smaller table
  • df[df["pages"] > 300]: מסכהdf[df["pages"] > 300]: a mask
  • & ו-| עם סוגריים& and | with parentheses
  • df["hours"] = df["pages"] / 40df["hours"] = df["pages"] / 40
  • פעולה על עמודה שלמה בבת אחתOne operation on a whole column at once
  • df.groupby("author")["pages"].sum()df.groupby("author")["pages"].sum()

מפגשSession 25: גרפים עם matplotlibCharts with matplotlib

  • fig, ax = plt.subplots()fig, ax = plt.subplots()
  • ax.plot(x, y) מצייר קוax.plot(x, y) draws a line
  • ax.set_title, set_xlabel, set_ylabelax.set_title, set_xlabel, set_ylabel
  • label= לכל קו + ax.legend()label= per line + ax.legend()
  • שינוי לאורך זמן → קוChange over time → line
  • השוואה בין קטגוריות → עמודותComparing categories → bars
  • צבע אחד, והדגשה רק למה שחשובOne colour, highlight only what matters
  • ערכים על העמודות: ax.bar_labelValues on the bars: ax.bar_label
  • df.plot(...) מחזיר Axesdf.plot(...) returns an Axes

מפגשSession 26: Web scraping אחראיResponsible web scraping

  • תגיות פותחות וסוגרות: <p>...</p>Opening and closing tags: <p>...</p>
  • מאפיינים: class, hrefAttributes: class, href
  • BeautifulSoup(html, "html.parser")BeautifulSoup(html, "html.parser")
  • find = הראשון, find_all = כולםfind = the first, find_all = all
  • soup.select("article.book h3 a")soup.select("article.book h3 a")
  • .class, #id, רווח = בתוך.class, #id, a space = inside
  • requests.get(url, headers=...) ואז souprequests.get(url, headers=...) then soup
  • User-Agent שמזהה אתכםA User-Agent that identifies you
  • עוקבים אחרי קישור "next" עד שנגמרFollow the "next" link until it runs out

חלקPart 5: בונים דבריםBuilding things

מפגשSession 27: כלי שורת פקודה עם argparseCommand-line tools with argparse

  • sys.argv[0] הוא שם הסקריפטsys.argv[0] is the script name
  • כל השאר: מחרוזותThe rest: strings
  • ארגומנט חובה: add_argument("name")Required: add_argument("name")
  • אופציה: --times עם type=int ו-defaultOption: --times with type=int and default
  • -h / --help נוצר לבד-h / --help is made for you
  • help= לכל ארגומנטhelp= for each argument
  • add_subparsers(dest="command")add_subparsers(dest="command")
  • לכל פקודה ארגומנטים משלהEach command has its own arguments
  • 0 = הצליח, אחר = נכשל0 = success, anything else = failure

מפגשSession 28: אוטומציה של משימותAutomating tasks

  • משהו שעושים שוב ושובSomething you do again and again
  • כללים ברורים, בלי שיקול דעתClear rules, no judgement
  • מילון סיומת → תיקייהA dict extension → folder
  • shutil.move(src, dst)shutil.move(src, dst)
  • p.stem, p.suffix, p.with_name(...)p.stem, p.suffix, p.with_name(...)
  • מספור עם אפסים: f"{i:03}"Numbering with zeros: f"{i:03}"
  • חותמת זמן בשם הקובץA timestamp in the file name
  • shutil.make_archive יוצר ZIPshutil.make_archive makes a ZIP
  • אוספים נתונים מתיקייהCollect data from a folder

מפגשSession 29: אתר API עם FastAPIA web API with FastAPI

  • app = FastAPI()app = FastAPI()
  • @app.get("/") מעל פונקציה@app.get("/") above a function
  • פרמטר בנתיב: /books/{book_id}Path parameter: /books/{book_id}
  • פרמטר שאילתה: ?author=dahlQuery parameter: ?author=dahl
  • class BookIn(BaseModel) מגדיר מבנהclass BookIn(BaseModel) defines a shape
  • Field(gt=0, min_length=1) מוסיף כלליםField(gt=0, min_length=1) adds rules
  • raise HTTPException(404, ...)raise HTTPException(404, ...)
  • status_code=201 ליצירה, 204 למחיקהstatus_code=201 for create, 204 for delete
  • pip install fastapi "uvicorn[standard]"pip install fastapi "uvicorn[standard]"

מפגשSession 30: async למתחיליםasync for beginners

  • רוב הזמן תוכנית רשת מחכהA network program mostly waits
  • סדרתי: 3 × 1 שניה = 3 שניותSequential: 3 × 1 second = 3 seconds
  • async def יוצר קורוטינהasync def makes a coroutine
  • await = חכה, ותן לאחרים לרוץawait = wait, and let others run
  • await asyncio.gather(a(), b(), c())await asyncio.gather(a(), b(), c())
  • התוצאות חוזרות באותו סדרResults come back in the same order
  • asyncio.create_task(coro()) מתחיל מידasyncio.create_task(coro()) starts right away
  • async with asyncio.TaskGroup() as tg:async with asyncio.TaskGroup() as tg:
  • `asyncio.Semaphore(3)`: עד 3 ביחד`asyncio.Semaphore(3)`: up to 3 together

מפגשSession 31: פרויקט אמצעMidterm project

  • משפט אחד: מה הכלי עושהOne sentence: what the tool does
  • MVP: שלוש פקודותMVP: three commands
  • models.py: הנתוניםmodels.py: the data
  • storage.py: שמירה וטעינהstorage.py: saving and loading
  • argparse עם שלוש פקודותargparse with three commands
  • main(argv=None) לבדיקותmain(argv=None) for tests
  • tmp_path: תיקייה זמנית לכל בדיקהtmp_path: a temp folder per test
  • monkeypatch מחליף את נתיב הקובץmonkeypatch swaps the file path
  • מה, איך מתקינים, איך משתמשיםWhat, how to install, how to use

חלקPart 6: Python בעידן ה-AI וקריירהPython in the AI era & career

מפגשSession 32: עבודה נכונה עם עוזר AI לקודWorking well with an AI coding assistant

  • מצוין: טיוטה, הסבר, רעיונות, קוד חוזרGreat at: drafts, explanations, ideas, boilerplate
  • חלש: אחריות, הקשר שלא נתתם, עובדות עדכניותWeak at: responsibility, context you didn't give, current facts
  • הקשר: מה הפרויקט, איזו גרסהContext: what the project is, which version
  • דוגמת קלט ופלטAn input and output example
  • סקירה: האם אני מבין כל שורה?Review: do I understand every line?
  • מריצים על מקרי קצהRun it on edge cases
  • כותבים מפרט כבדיקותWrite the spec as tests
  • נותנים לעוזר את הבדיקותGive the assistant the tests
  • פונקציות וחבילות מומצאותMade-up functions and packages

מפגשSession 33: קריאה למודל שפה מ-PythonCalling a language model from Python

  • בקשת POST עם JSON, כמו במפגש 22A POST request with JSON, like session 22
  • שולחים הודעות, מקבלים הודעהSend messages, get a message back
  • מפתח = כסף. לא בקוד, לא ב-GitA key = money. Not in code, not in Git
  • משתנה סביבה: export / setxEnvironment variable: export / setx
  • `system`: תפקיד וסגנון`system`: role and style
  • messages: כל ההיסטוריה, בכל בקשהmessages: the full history, every request
  • מבקשים בפירוש: "רק JSON עם השדות..."Ask explicitly: "only JSON with the fields..."
  • json.loads בתוך tryjson.loads inside try
  • usage: טוקנים נכנסים ויוצאיםusage: input and output tokens

מפגשSession 34: אלגוריתמים וסיבוכיותAlgorithms & complexity

  • אלגוריתם = מתכוןAn algorithm = a recipe
  • ב-10 ספרים הכול מהירWith 10 books everything is fast
  • O(1): קבוע, לא תלוי בגודלO(1): constant, independent of size
  • O(n): לולאה אחתO(n): one loop
  • רק ברשימה ממוינתOnly on a sorted list
  • בודקים אמצע, זורקים חציCheck the middle, throw away half
  • רשימה: סדר, אינדקס. in הוא O(n)List: order, index. in is O(n)
  • set ו-dict: גיבוב, in הוא O(1)set and dict: hashing, in is O(1)
  • מיון בועות: O(n²), טוב ללמידהBubble sort: O(n²), good for learning

מפגשSession 35: הכנה לראיון עבודהJob interview prep

  • שיחת היכרות → מבחן בית/אונליין → ראיון טכניIntro call → home/online test → technical interview
  • מעריכים חשיבה, לא רק תשובהThey assess thinking, not just the answer
  • "כמה פעמים", "הכי נפוץ", "יחיד""How many times", "most common", "unique"
  • Counter או dict.get(x, 0) + 1Counter or dict.get(x, 0) + 1
  • מהקצוות פנימה: פלינדרום, סכום בזוגFrom the ends inward: palindrome, pair sum
  • ברשימה ממוינתIn a sorted list
  • "רצף של k", "הכי ארוך בלי...""A run of k", "longest without..."
  • מוסיפים את הנכנס, מחסירים את היוצאAdd what enters, subtract what leaves
  • להגיד את התוכנית לפני הקודSay the plan before the code

מפגשSession 36: פרויקט גמר והצגהFinal project & demo

  • שכבות: models → storage → service → cli/apiLayers: models → storage → service → cli/api
  • כל מה שבניתם לאורך הקורסEverything you built through the course
  • תיקיית shelf/ עם __init__.pyA shelf/ folder with __init__.py
  • pyproject.toml: שם, תלויות, פקודותpyproject.toml: name, dependencies, commands
  • כל החוקים במקום אחדAll the rules in one place
  • CLI ו-API קוראים לאותן פונקציותThe CLI and API call the same functions
  • קובץ .github/workflows/tests.ymlA .github/workflows/tests.yml file
  • GitHub מריץ pytest בכל pushGitHub runs pytest on every push
  • MAJOR.MINOR.PATCHMAJOR.MINOR.PATCH

חלקPart 7: משחקים עם PygameGames with Pygame

מפגשSession 37: ברוכים הבאים ל-Pygame: בועות קופצותWelcome to Pygame: Bubble Bounce

  • pip install pygame-cepip install pygame-ce
  • pygame.display.set_mode((w, h))pygame.display.set_mode((w, h))
  • אירועים → עדכון → ציורEvents → update → draw
  • QUIT סוגר את החלוןQUIT closes the window
  • (0, 0) בפינה השמאלית העליונה(0, 0) is the top-left corner
  • y גדל כלפי מטה!y grows downward!
  • מהירות: vx, vy בכל פרייםvelocity: vx, vy per frame
  • מיקום += מהירותposition += velocity
  • פגיעה בקיר = הופכים את סימן המהירותHitting a wall = flip the velocity's sign

מפגשSession 38: Star Catcher: תופסים כוכביםStar Catcher

  • `KEYDOWN`: פעם אחת בלחיצה`KEYDOWN`: once per press
  • get_pressed(): כל עוד מחזיקיםget_pressed(): as long as held
  • `Rect` יודע left, right, centerxA `Rect` knows left, right, centerx
  • הגבלה לטווח שומרת בתוך המסךClamping keeps it on screen
  • הופעה כל N פריימיםspawn every N frames
  • random.randint למיקוםrandom.randint for position
  • a.colliderect(b) → True/Falsea.colliderect(b) → True/False
  • collidelist / collidepointcollidelist / collidepoint
  • ניקוד עולה בתפיסהScore goes up on a catch

מפגשSession 39: Neon PongNeon Pong

  • שני מחבטים כ-RectTwo paddles as Rects
  • קו אמצע מקווקו בלולאהA dashed centre line in a loop
  • מיקום עשרוני bx, by לתנועה חלקהA float position bx, by for smooth motion
  • ה-Rect מקבל round לציורThe Rect gets round for drawing
  • פגיעה במרכז = ישר, בקצה = חדA centre hit = straight, an edge hit = sharp
  • offset בין -1 ל-1offset from -1 to 1
  • עוקב אחרי הכדורFollows the ball
  • מהירות מוגבלת = אפשר לנצחLimited speed = beatable
  • dt = שניות מאז הפריים הקודםdt = seconds since the last frame

מפגשSession 40: Retro Snake: נחש רטרוRetro Snake

  • רשת: (עמודה, שורה)grid: (column, row)
  • פיקסלים = משבצת × CELLPixels = cell × CELL
  • רשימת טאפלים, הראש ראשוןA list of tuples, head first
  • תנועה: ראש חדש בהתחלה, מוחקים את הזנבMove: a new head in front, remove the tail
  • ראש על האוכל → לא מוחקים זנבHead on the food → don't remove the tail
  • אוכל חדש רק במשבצת פנויהNew food only on a free cell
  • ראש בתוך הגוף = סוףHead inside the body = game over
  • קיר: סוף או מעבר לצד השניWall: game over or wrap-around
  • טיק כל 120ms, ציור כל פרייםA tick every 120ms, drawing every frame

מפגשSession 41: Brick Breaker: שובר לבניםBrick Breaker

  • מפת שלב: כל תו הוא לבנהA level map: each character is a brick
  • . = ריק. = empty
  • הפרדת צירים: קודם x, אז yAxis separation: x first, then y
  • פגיעה ב-x → vx = -vxA hit on x → vx = -vx
  • כדור מהיר יכול "לדלג" מעל לבנהA fast ball can "skip" a brick
  • צעדים קטנים: מחלקים את התנועהSmall steps: split the motion
  • לבנה שנשברת מפילה חיזוק לפעמיםA broken brick sometimes drops a power-up
  • תופסים במחבט → אפקטCatch it with the paddle → an effect
  • כדור מתחת למחבט = חיים פחותBall below the paddle = a life lost

מפגשSession 42: Flappy: ציפור מעופפתFlappy

  • כבידה: vel += GRAVITY בכל פרייםGravity: vel += GRAVITY every frame
  • דחיפה: vel = FLAP בלחיצהImpulse: vel = FLAP on a press
  • צינור = x ומרכז רווחA pipe = x and a gap centre
  • מלבן עליון ומלבן תחתון מחושביםTop and bottom rects are computed
  • נקודה כשהצינור עובר את הציפורA point when the pipe passes the bird
  • דגל scored = פעם אחת בלבדA scored flag = only once
  • ציור על Surface שקוףDraw on a transparent Surface
  • pygame.transform.rotate(surf, angle)pygame.transform.rotate(surf, angle)
  • פרלקסה: רחוק = איטיParallax: far = slow

מפגשSession 43: Space Shooter: יורה חללSpace Shooter

  • Sprite = image + rect + updateA Sprite = image + rect + update
  • קבוצה: group.update(), group.draw(screen)A group: group.update(), group.draw(screen)
  • cooldown: ירייה כל N פריימיםA cooldown: a shot every N frames
  • ירייה = Sprite שזז למעלהA bullet = a Sprite moving up
  • groupcollide(a, b, kill_a, kill_b)groupcollide(a, b, kill_a, kill_b)
  • מחזיר מילון: מי פגע במיReturns a dict: who hit whom
  • גל = מערך של אויביםA wave = a formation of enemies
  • זזים יחד, יורדים בקצהMove together, drop at the edge
  • חלקיק: מיקום, מהירות, זמן חייםA particle: position, velocity, lifetime

מפגשSession 44: Physics Lab: מעבדת סימולציותPhysics Lab

  • Vector2: חיבור, כפל, אורךVector2: add, scale, length
  • normalize() = כיוון באורך 1normalize() = a direction of length 1
  • כוח → תאוצה: a = F / mForce → acceleration: a = F / m
  • אוילר: v += a*dt, p += v*dtEuler: v += a*dt, p += v*dt
  • מהירות התחלתית לפי זוויתInitial velocity from an angle
  • סימולציה מול נוסחהSimulation vs formula
  • חוק הוק: F = -k × מתיחהHooke's law: F = -k × stretch
  • ריסון: vel *= 0.98damping: vel *= 0.98
  • כבידה בין שני גופים: G·M / r²Gravity between two bodies: G·M / r²

מפגשSession 45: Pixel PlatformerPixel Platformer

  • מפה: # קרקע, c מטבע, e אויבA map: # ground, c coin, e enemy
  • אריח = Rect בגודל TA tile = a Rect of size T
  • על הקרקע רק אחרי נחיתהGrounded only after landing
  • קפיצה = vy = -6 רק אם groundedA jump = vy = -6 only if grounded
  • הפרדת צירים: x ואז yAxis separation: x then y
  • ב-x: עוצרים בקירOn x: stop at the wall
  • מצלמה = היסט אופקיA camera = a horizontal offset
  • מציירים ב-rect.move(-camera, 0)Draw at rect.move(-camera, 0)
  • מטבע: נגיעה = נקודה ומחיקהA coin: a touch = a point and removal

מפגשSession 46: Tower Defense: הגנת מגדליםTower Defense

  • מסלול = רשימת נקודות ציוןA path = a list of waypoints
  • צעד לעבר הנקודה הבאה בכיוון מנורמלStep toward the next point in a normalised direction
  • בטווח = math.dist(...) <= rangeIn range = math.dist(...) <= range
  • בחירה: הראשון במסלולChoosing: the first on the path
  • זמן טעינה יורד בכל פרייםA cooldown counts down each frame
  • יורים רק ב-0, ומאפסיםFire only at 0, then reset
  • קליע מונחה מכוון מחדש בכל פרייםA homing bullet re-aims every frame
  • פגיעה = מרחק קטן מסףA hit = distance below a threshold
  • גל = כמה אויבים, מרווח, עוצמהA wave = how many, the gap, the strength

מפגשSession 47: Crystal Quest, חלק 1Crystal Quest, part 1

  • settings.py: קבועיםsettings.py: constants
  • scenes.py: מסכיםscenes.py: screens
  • סצנה = מחלקה עם update ו-drawA scene = a class with update and draw
  • game.change(new_scene)game.change(new_scene)
  • מבט על: אין כבידהTop-down: no gravity
  • אלכסון מהיר מדי? מנרמליםDiagonal too fast? Normalise
  • כל חדר = מפת אריחים במילוןEach room = a tilemap in a dict
  • דלת מובילה לחדר אחר ולנקודת כניסהA door leads to another room and an entry point
  • מלאי = מילון ספירותAn inventory = a dict of counts

מפגשSession 48: Crystal Quest, חלק 2 ופרסוםCrystal Quest, part 2 & publishing

  • מצבים: patrol, chase, returnStates: patrol, chase, return
  • מעבר לפי מרחק לשחקןSwitch by distance to the player
  • מצב המשחק → מילון → JSONGame state → dict → JSON
  • כותבים לקובץ זמני ואז מחליפיםWrite to a temp file, then replace
  • חלקיק = מיקום, מהירות, חייםA particle = position, velocity, life
  • חיכוך: vel *= 0.95Friction: vel *= 0.95
  • נתיב יחסי לקובץ הקוד: Path(__file__).parentPaths relative to the code file: Path(__file__).parent
  • תיקיית assets מסודרתA tidy assets folder
  • pygbag: לולאה async עם await asyncio.sleep(0)pygbag: an async loop with await asyncio.sleep(0)

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