6. The Python Ecosystem

Tools and conventions for managing environments, dependencies, modules, and projects.

Question: What is pip and what is requirements.txt used for?

Answer: pip is Python's package installer, used to install libraries from the Python Package Index (PyPI). A requirements.txt file lists a project's dependencies, allowing anyone to install the exact same versions with pip install -r requirements.txt.

Question: Why should you use a virtual environment (venv)?

Answer: A virtual environment creates an isolated Python setup for each project. This prevents dependency conflicts between projects that might require different versions of the same library.

Question: What is the purpose of if __name__ == "__main__"?

Answer: This block of code runs only when the Python script is executed directly, not when it is imported as a module into another script. It is the standard way to make a file both a reusable module and an executable script.

Question: What is Git and what are the most common commands?

Answer: Git is a version control system used to track changes in code. Common commands include git clone (to copy a repository), git add (to stage changes), git commit (to save changes), git push (to upload changes), and git pull (to download changes).

Question: How do modules and packages work?

Answer: A module is a single .py file; a package is a directory with Python modules (optionally with __init__.py). Use absolute imports for clarity and relative imports for intra-package references.

# mypkg/__init__.py (optional), mypkg/util.py
from mypkg import util           # absolute import
from . import util as u          # relative import (inside the package)

Question: How do you run a module as a script?

Answer: Use python -m package.module so imports resolve relative to the package.

python -m http.server 8000
python -m pip list