Modules and Packages
As programs grow, putting all code in a single file becomes unwieldy. Python uses modules and packages to organize code.
What is a Module?
A module is simply a Python file (.py) containing code (functions, variables, classes). The file name is the module name.
Importing Modules
The import statement brings the contents of another module into the current file.
1. Simple Import
python
Assumes a file named 'math_helpers.py' exists
import math_helpers
Access functions using the module name prefix
result = math_helpers.calculate_something()
2. Import with Alias (as)
Used to shorten long module names.
python import pandas as pd
df = pd.DataFrame(...)
3. Importing Specific Items (from...import)
Imports only specified functions, classes, or variables, allowing them to be used without the module prefix.
python from math import sqrt, pi
print(sqrt(9)) # Use sqrt directly print(pi) # Use pi directly
4. Import Everything (from...import *)
Imports all public names. Generally discouraged as it can lead to name collisions and confusion about where functions originate.