🐍 Python Beginner

What are Python modules and packages?

Answer

A module is a single Python file (.py) that can contain functions, classes, and variables. Import a module: import math or from math import sqrt, pi or import math as m. A package is a directory containing an __init__.py file (can be empty) and multiple modules: from mypackage.utils import helper. The __init__.py is executed when the package is imported. Python's standard library is a collection of built-in modules: os, sys, json, datetime, collections, itertools, functools, pathlib, re, logging. Third-party packages are installed with pip: pip install requests. Namespaces prevent name conflicts between modules. The __name__ == "__main__" guard lets a module run standalone or be imported without executing top-level code.