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

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

מודולים, pip ו-venvModules, pip & venv

import, מודולים משלך, הספרייה הסטנדרטית, התקנת חבילות וסביבה וירטואלית.

import, your own modules, the standard library, installing packages and virtual environments.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • 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

מונחיםTerms

  • importimport: טעינת מודול כדי להשתמש בפונקציות שלו: import random, from math import sqrt.Loading a module to use its functions: import random, from math import sqrt.
  • הספרייה הסטנדרטיתstandard library: מאות מודולים שמגיעים עם Python ולא צריך להתקין: math, random, datetime, json, pathlib ועוד.Hundreds of modules that ship with Python, no install needed: math, random, datetime, json, pathlib and more.
  • חבילהpackage: מודול (או כמה) שמישהו פרסם, ומתקינים עם pip, כמו requests או pandas.One or more modules someone published, installed with pip, like requests or pandas.
  • pippip: מנהל החבילות של Python: python -m pip install שם.Python's package manager: python -m pip install name.
  • סביבה וירטואלית (venv)virtual environment (venv): תיקייה עם עותק נפרד של Python וחבילות לפרויקט אחד, כדי שפרויקטים לא יפריעו זה לזה.A folder with a separate copy of Python and packages for one project, so projects don't interfere.
  • __name__ == "__main__"__name__ == "__main__": תנאי שנכון רק כשמריצים את הקובץ ישירות, ולא כשמייבאים אותו.A condition that's true only when the file is run directly, not when it's imported.

Cheatsheet

importimport
import random
from math import sqrt, pi
import statistics as st

random.seed(7)
print(random.choice(["Dune", "Emma", "Matilda"]))
print(random.randint(1, 6))
stdlibstdlib
from datetime import date, timedelta
from collections import Counter

start = date(2026, 11, 19)
due = start + timedelta(days=21)
print(due, due.strftime("%d/%m/%Y"), (due - start).days)
genres = ["sci-fi", "kids", "sci-fi", "classic", "sci-fi"]
מודול משלכםYour own module
import importlib
from pathlib import Path
Path("books.py").write_text(
    "def card(t, a):\n    return f\"{t} by {a}\"\n", encoding="utf-8")
importlib.invalidate_caches()

import books
__main____main__
def card(title, author):
    return f"📚 {title}, {author}"

if __name__ == "__main__":
    print(card("Dune", "Frank Herbert"))
    print("הקובץ רץ ישירות", __name__)def card(title, author):
    return f"📚 {title}, {author}"

if __name__ == "__main__":
    print(card("Dune", "Frank Herbert"))
    print("run directly", __name__)

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
ModuleNotFoundErrorקוראים לקובץ שלכם באותו שם של מודול סטנדרטי, למשל random.py, ואז ה-import טוען אותו במקום המקורי. כאן מודגם השם השגוי עצמו.Naming your own file like a standard module, e.g. random.py, so import loads yours instead of the real one. Here the wrong name itself is shown.ModuleNotFoundError: No module named 'ranodm': בודקים איות. ואם יש לכם קובץ בשם של מודול מוכר (random.py), משנים את שמו.ModuleNotFoundError: No module named 'ranodm': check the spelling. And if you have a file named like a real module (random.py), rename it.
TypeErrorמחברים מספר לתאריך. צריך timedelta.Adding a number to a date. You need timedelta.TypeError: unsupported operand type(s) for +: 'datetime.date' and 'int': כותבים + timedelta(days=21).TypeError: unsupported operand type(s) for +: 'datetime.date' and 'int': write + timedelta(days=21).
ImportErrorמייבאים פונקציה שלא קיימת במודול.Importing a name the module doesn't have.ImportError: cannot import name 'multiply' from 'tools': בודקים את שם הפונקציה בקובץ המודול.ImportError: cannot import name 'multiply' from 'tools': check the function's name in the module file.
AssertionErrorשוכחים את הנקודתיים או כותבים main בלי הקווים התחתונים.Forgetting the underscores around main.AssertionError: השם המיוחד הוא "__main__" עם שני קווים תחתונים מכל צד.AssertionError: the special name is "__main__", with two underscores on each side.
ModuleNotFoundErrorמייבאים חבילה שלא הותקנה.Importing a package that isn't installed.ModuleNotFoundError: מתקינים עם python3 -m pip install ..., ובודקים ב-VS Code שנבחר אותו מפרש.ModuleNotFoundError: install with python3 -m pip install ..., and check VS Code uses the same interpreter.
AssertionErrorבודקים מאיפה Python רצה. אם זה לא מתוך .venv, ההתקנות הולכות למקום אחר. כאן רואים את הבדיקה עצמה.Checking where Python runs from. If it isn't inside .venv, installs go elsewhere. Here's the check itself.AssertionError: הסביבה לא מופעלת. מפעילים עם activate, או בוחרים ב-VS Code את המפרש מתוך .venv.AssertionError: the environment isn't active. Activate it, or pick the .venv interpreter in VS Code.

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