מודולים, pip ו-venvModules, pip & venv
import, מודולים משלך, הספרייה הסטנדרטית, התקנת חבילות וסביבה וירטואלית.
import, your own modules, the standard library, installing packages and virtual environments.
01import: להשתמש בקוד מוכןimport: using ready-made code
import טוען מודול. אפשר לייבא את כולו ולגשת עם נקודה, לייבא רק שמות מסוימים עם from, או לתת לו כינוי קצר עם as.
import loads a module. Import the whole thing and use a dot, import just certain names with from, or give it a short alias with as.
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))
print(sqrt(144), round(pi, 2))
print(st.mean([412, 96, 280]))Emma 2 12.0 3.14 262.6666666666667
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מודול הוא כמו ספר מתכונים במדף: import מוריד את כל הספר, from ... import מצלם רק את המתכון שצריך.
A module is like a cookbook on the shelf: import takes down the whole book, from ... import photocopies just the recipe you need.
random.seed(7) קובע את נקודת ההתחלה של המספרים "האקראיים", ולכן כל הרצה נותנת אותן תוצאות. זה שימושי לבדיקות.
random.seed(7) fixes the starting point of the "random" numbers, so every run gives the same results. Handy for testing.
קוראים לקובץ שלכם באותו שם של מודול סטנדרטי, למשל 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.
import ranodmTraceback (most recent call last):
File "/Users/you/python-course/imports.py", line 1, in <module>
import ranodm
ModuleNotFoundError: No module named 'ranodm'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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02הספרייה הסטנדרטיתThe standard library
ל-Python יש ספרייה סטנדרטית עצומה. לפני שכותבים משהו מאפס, כדאי לבדוק אם הוא כבר קיים. datetime מחשב תאריכים, ו-Counter סופר בשורה אחת מה שבנינו במפגש 8 עם מילון.
Python has a huge standard library. Before writing something yourself, check whether it exists. datetime does date maths, and Counter counts in one line what we built in session 8 with a dict.
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"]
print(Counter(genres).most_common(2))2026-12-10 10/12/2026 21
[('sci-fi', 3), ('kids', 1)]צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הספרייה הסטנדרטית היא כמו ארגז כלים שמגיע עם הבית: מברגה, פטיש, מטר. לא צריך לקנות כלום כדי להתחיל.
The standard library is like the toolbox that comes with the house: screwdriver, hammer, tape measure. Nothing to buy to get started.
מחברים מספר לתאריך. צריך timedelta.
Adding a number to a date. You need timedelta.
from datetime import date
print(date(2026, 11, 19) + 21)Traceback (most recent call last):
File "/Users/you/python-course/stdlib.py", line 2, in <module>
print(date(2026, 11, 19) + 21)
~~~~~~~~~~~~~~~~~~~^~~~
TypeError: unsupported operand type(s) for +: 'datetime.date' and 'int'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).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הספרייה הסטנדרטית מלאה בכלים מוכנים.
The standard library is full of ready tools.
import math
from collections import Counter
print(math.sqrt(49))
print(math.ceil(4.2))
print(Counter("banana"))7.0
5
Counter({'a': 3, 'n': 2, 'b': 1})צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03מודול משלכםYour own module
כל קובץ .py הוא מודול. אם יש בתיקייה books.py עם פונקציות, קובץ אחר יכול לכתוב import books ולהשתמש בהן. ככה מפצלים פרויקט גדול לקבצים לפי נושא. הדוגמה כותבת את המודול בעצמה כדי שאפשר יהיה להריץ אותה בדפדפן, ולכן קוראת ל-importlib.invalidate_caches(): פייתון זוכרת אילו קבצים היו בתיקייה כשהתוכנית התחילה, והשורה הזו אומרת לה לבדוק שוב. ב-VS Code פשוט יוצרים את books.py כקובץ רגיל, ואז אין צורך בה.
Every .py file is a module. If a folder has books.py with functions, another file can import books and use them. That's how a big project is split into files by topic. This example writes the module itself so it runs in the browser too, which is why it calls importlib.invalidate_caches(): Python remembers which files were in the folder when the program started, and this line tells it to look again. In VS Code you simply create books.py as a normal file and don't need it.
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
print(books.card("Dune", "Frank Herbert"))
print(books.__name__)Dune by Frank Herbert books
לפצל לקבצים זה כמו לחלק ספר לפרקים: כל פרק על נושא אחד, ותוכן העניינים (import) מחבר ביניהם.
Splitting into files is like dividing a book into chapters: one topic per chapter, and the table of contents (import) links them.
מייבאים פונקציה שלא קיימת במודול.
Importing a name the module doesn't have.
import importlib
from pathlib import Path
Path("tools.py").write_text("def add(a, b):\n return a + b\n", encoding="utf-8")
importlib.invalidate_caches()
from tools import multiplyTraceback (most recent call last):
File "/Users/you/python-course/main.py", line 5, in <module>
from tools import multiply
ImportError: cannot import name 'multiply' from 'tools' (/Users/you/python-course/tools.py)ImportError: cannot import name 'multiply' from 'tools': בודקים את שם הפונקציה בקובץ המודול.ImportError: cannot import name 'multiply' from 'tools': check the function's name in the module file.04if __name__ == "__main__"if __name__ == "__main__"
כשמייבאים מודול, כל הקוד שבו רץ, כולל prints ובדיקות. כדי שקוד ירוץ רק כשמריצים את הקובץ עצמו, שמים אותו בתוך `if __name__ == "__main__":`.
When you import a module, all its code runs, prints and tests included. To make code run only when the file itself is run, put it inside `if __name__ == "__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__)📚 Dune, Frank Herbert הקובץ רץ ישירות __main__
📚 Dune, Frank Herbert run directly __main__
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
זה כמו שלט "להרצה ישירה בלבד" על כפתור הדגמה במכונה: כשמשתמשים במכונה כחלק ממפעל (import), הכפתור לא נלחץ.
It's like a "direct use only" label on a machine's demo button: when the machine is part of a factory (import), the button isn't pressed.
שוכחים את הנקודתיים או כותבים main בלי הקווים התחתונים.
Forgetting the underscores around main.
if __name__ == "main":
print("runs?")
print(__name__)
assert __name__ == "main", "the check never matches: it must be \"__main__\""__main__
Traceback (most recent call last):
File "/Users/you/python-course/books.py", line 4, in <module>
assert __name__ == "main", "the check never matches: it must be \"__main__\""
^^^^^^^^^^^^^^^^^^
AssertionError: the check never matches: it must be "__main__"AssertionError: השם המיוחד הוא "__main__" עם שני קווים תחתונים מכל צד.AssertionError: the special name is "__main__", with two underscores on each side.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הבלוק הזה רץ רק כשמריצים את הקובץ ישירות.
This block runs only when the file is run directly.
def main():
print("Running main")
print("name is", __name__)
if __name__ == "__main__":
main()name is __main__ Running main
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05pip: להתקין חבילותpip: installing packages
חבילה היא קוד שמישהו פרסם באינטרנט (במאגר PyPI). pip מוריד ומתקין אותה. כותבים python -m pip (ב-Mac python3 -m pip) כדי להיות בטוחים שההתקנה נכנסת ל-Python הנכון.
A package is code someone published online (on PyPI). pip downloads and installs it. Write python -m pip (Mac: python3 -m pip) to be sure it installs into the right Python.
python3 -m pip install requests
python3 -m pip list
python3 -m pip freeze > requirements.txt
python3 -m pip install -r requirements.txtpip הוא כמו חנות אפליקציות בטלפון: מחפשים בשם, לוחצים התקנה, והאפליקציה מוכנה לשימוש.
pip is like a phone's app store: search by name, tap install, and it's ready to use.
מייבאים חבילה שלא הותקנה.
Importing a package that isn't installed.
import not_installed_package_xyzTraceback (most recent call last):
File "/Users/you/python-course/main.py", line 1, in <module>
import not_installed_package_xyz
ModuleNotFoundError: No module named 'not_installed_package_xyz'ModuleNotFoundError: מתקינים עם python3 -m pip install ..., ובודקים ב-VS Code שנבחר אותו מפרש.ModuleNotFoundError: install with python3 -m pip install ..., and check VS Code uses the same interpreter.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06סביבה וירטואלית: venvVirtual environments: venv
סביבה וירטואלית היא תיקייה (בדרך כלל .venv) עם Python וחבילות משלה. כל פרויקט מקבל סביבה משלו, כך שגרסה של חבילה בפרויקט אחד לא שוברת פרויקט אחר. VS Code מזהה אותה ומציע לבחור בה.
A virtual environment is a folder (usually .venv) with its own Python and packages. Each project gets its own, so a package version in one project can't break another. VS Code detects it and offers to use it.
| פעולהAction | MacMac | Windows (PowerShell)Windows (PowerShell) |
|---|---|---|
| יצירהCreate | python3 -m venv .venv | python -m venv .venv |
| הפעלהActivate | source .venv/bin/activate | .venv\Scripts\Activate.ps1 |
| התקנה בתוכהInstall inside | pip install requests | pip install requests |
| כיבויDeactivate | deactivate | deactivate |
venv הוא כמו קופסת אוכל נפרדת לכל ילד: מה שבקופסה של אחד לא מתערבב עם האוכל של השני.
A venv is like a separate lunchbox for each child: what's in one box doesn't mix with the other's food.
ב-Windows, אם ההפעלה נחסמת עם הודעה על Execution Policy, מריצים פעם אחת: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned.
On Windows, if activation is blocked with an Execution Policy message, run once: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned.
בודקים מאיפה Python רצה. אם זה לא מתוך .venv, ההתקנות הולכות למקום אחר. כאן רואים את הבדיקה עצמה.
Checking where Python runs from. If it isn't inside .venv, installs go elsewhere. Here's the check itself.
import sys
print(sys.prefix)
assert ".venv" in sys.prefix, "not inside the project venv: activate it first"/usr/local
Traceback (most recent call last):
File "/Users/you/python-course/main.py", line 3, in <module>
assert ".venv" in sys.prefix, "not inside the project venv: activate it first"
^^^^^^^^^^^^^^^^^^^^^
AssertionError: not inside the project venv: activate it firstAssertionError: הסביבה לא מופעלת. מפעילים עם activate, או בוחרים ב-VS Code את המפרש מתוך .venv.AssertionError: the environment isn't active. Activate it, or pick the .venv interpreter in VS Code.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.