Python with AI Tutorial · Chapter 25 of 48
Python modules and pip are how you stop writing everything yourself. A module is any .py file (or built-in library) whose functions you pull in with import; pip is the installer that downloads third-party packages from PyPI. Add a virtual environment and every project keeps its own clean set of packages.
Up to now every chapter fitted in one file. Real work does not. A sales report needs date handling, a statistics helper, an Excel writer and maybe an HTTP client. Modules let you split that work into named pieces, reuse them across projects and borrow code that thousands of other developers have already tested.
Importing a built-in module
Python ships with a large standard library, often described as “batteries included”. You import a module once at the top of the file, then reach its functions with dot notation. Nothing needs installing for these.
import statistics
monthly_sales = [42000, 38500, 51200, 47800, 39900, 55300]
print("Average:", statistics.mean(monthly_sales))
print("Median:", statistics.median(monthly_sales))
print("Std dev:", round(statistics.stdev(monthly_sales), 2))
Output: Average: 45783.333333333336 Median: 44900.0 Std dev: 6706.05
from, as and importing only what you need
Use from module import name to skip the prefix, and as to give a module a shorter alias (you will see import pandas as pd everywhere later in this course). Avoid from module import *; it dumps unknown names into your file and makes bugs hard to trace.
from collections import Counter
import random as rnd
rnd.seed(7)
regions = [rnd.choice(["North", "South", "East", "West"]) for _ in range(12)]
print(regions)
print(Counter(regions).most_common(2))
Output:
['South', 'East', 'West', 'North', 'West', 'South', 'North', 'South', 'North', 'East', 'East', 'North']
[('North', 4), ('South', 3)]
Writing your own module
Any file you save is a module. Put reusable business rules in one file and import it from another file in the same folder. Python looks in the folder of the running script first, so no configuration is needed for this simple layout.
# File: invoicing.py
GST_RATE = 0.18
def add_gst(amount):
"""Return the amount including 18% GST."""
return round(amount * (1 + GST_RATE), 2)
def invoice_total(lines):
return add_gst(sum(qty * price for qty, price in lines))
# File: main.py (same folder)
import invoicing
lines = [(3, 1200.00), (1, 4500.00), (10, 85.50)]
print("Subtotal + GST:", invoicing.invoice_total(lines))
print("Rate used:", invoicing.GST_RATE)
Output: Subtotal + GST: 10567.35 Rate used: 0.18
random.py, csv.py, requests.py). Python finds your file first and the real module silently disappears. The classic symptom is AttributeError: module 'random' has no attribute 'choice'.The __name__ == “__main__” guard
When Python runs a file directly, it sets the special variable __name__ to "__main__". When the same file is imported, __name__ is the module name instead. Code under this guard therefore runs only on direct execution, which lets one file work both as a script and as a library.
# File: payroll.py
def net_pay(gross, tax_rate=0.10):
return round(gross * (1 - tax_rate), 2)
if __name__ == "__main__":
print("Demo run:", net_pay(65000))
Output (python payroll.py): Demo run: 58500.0 Output (import payroll from another file): (nothing is printed)
Installing packages with pip
The standard library is large but it has no Excel writer, no HTTP client with a friendly API and no data-frame library. Those live on PyPI, the Python Package Index, and pip fetches them. pip runs in your terminal, not inside Python. Always call it through the interpreter you are using so packages land in the right place.
# Windows (PowerShell or Command Prompt)
py -m pip install requests openpyxl
# Mac / Linux
python3 -m pip install requests openpyxl
# Useful follow-ups (any OS)
python -m pip show openpyxl
python -m pip list
python -m pip install --upgrade openpyxl
python -m pip uninstall openpyxl
Output (abridged): Successfully installed certifi-2025.1.31 charset-normalizer-3.4.1 et-xmlfile-2.0.0 idna-3.10 openpyxl-3.1.5 requests-2.32.3 urllib3-2.3.0
Notice that pip also installed dependencies you never asked for. That is normal: requests needs urllib3 and certifi to work, and pip resolves the whole chain for you.
| Command | What it does |
|---|---|
pip install pkg |
Download and install the latest version from PyPI |
pip install pkg==2.1.0 |
Install an exact version |
pip install -r requirements.txt |
Install every package listed in a file |
pip freeze > requirements.txt |
Write the current versions to a file |
pip list --outdated |
Show packages with newer releases |
pip uninstall pkg |
Remove a package |
Virtual environments with venv
A virtual environment is a private folder holding its own Python and packages. One project can use pandas 2.2 while another stays on 1.5, and nothing you install pollutes the system Python. The built-in venv module creates one; the conventional folder name is .venv.
# Create it once, inside the project folder
python -m venv .venv
# Activate it - Windows PowerShell
.venv\Scripts\Activate.ps1
# Activate it - Windows Command Prompt
.venv\Scripts\activate.bat
# Activate it - Mac / Linux
source .venv/bin/activate
# Now pip installs go only into .venv
python -m pip install pandas
# Leave the environment
deactivate
Output: (.venv) C:\projects\sales-report> <- the prompt shows the active environment
If PowerShell refuses to run the activation script, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once and try again. VS Code and PyCharm detect a .venv folder automatically and select it as the interpreter.
Sharing a project with requirements.txt
A colleague should be able to recreate your environment in two commands. Freeze the installed versions to a text file, commit that file, and let them install from it.
# You, after installing everything the project needs
python -m pip freeze > requirements.txt
# Your colleague, in a fresh virtual environment
python -m pip install -r requirements.txt
Output (contents of requirements.txt): et-xmlfile==2.0.0 openpyxl==3.1.5 pandas==2.2.3 requests==2.32.3
Pin versions in this file when stability matters. A bare pandas line installs whatever is newest on the day, which is fine for a personal experiment but risky for a monthly report that has to run unattended on a server. The double-equals form freezes the exact release that you tested.
Checking where a module lives
When imports behave strangely, ask Python which file it actually loaded and where it searches. sys.path is the list of folders checked in order; the script folder comes first, then the standard library, then site-packages where pip installs.
import sys
import json
print(json.__file__)
print(len(sys.path), "search locations")
print(sys.path[-1].endswith("site-packages"))
Output (paths vary by machine): C:\Users\priya\AppData\Local\Programs\Python\Python312\Lib\json\__init__.py 6 search locations True
Ask the assistant to turn a messy script into a reusable module with a main guard.
Here is my Python script that calculates GST on a list of invoice lines. Refactor it into a module called invoicing.py with small functions, a module-level GST_RATE constant, docstrings, and an if __name__ == "__main__" demo block. Then show a separate main.py that imports and uses it.
Get an exact set of commands for your operating system when an install fails.
I am on Windows 11 with Python 3.12. When I run "pip install openpyxl" I get "pip is not recognized". Give me the exact PowerShell commands to create a virtual environment named .venv in C:\projects\report, activate it, install openpyxl and requests, and save a requirements.txt. Explain what each command does in one line.
Third-party packages you will meet later in this course include requests for web APIs, openpyxl and pandas for Excel and tabular data, matplotlib for charts and the official AI client libraries. Every one of them is installed exactly the way shown above, so the habits from this chapter carry through to the end.
Common mistakes
- Running
pip installwith one Python and the script with another. Usepython -m pipso both match. - Naming your own file the same as a library (
csv.py,random.py), which shadows the real module. - Forgetting to activate the virtual environment, then wondering why the package is "missing".
- Committing the
.venvfolder to Git. Commitrequirements.txtinstead and recreate the environment. - Using
from module import *, which hides where each name came from.
Exercise
Create a module discounts.py with a function apply_discount(price, percent) that returns the discounted price rounded to two decimals, and a constant MAX_DISCOUNT = 40. Raise ValueError if percent is above the maximum. Import it from shop.py and print the price of a 2,499 item at 15% off.
Show answer
# discounts.py
MAX_DISCOUNT = 40
def apply_discount(price, percent):
if percent > MAX_DISCOUNT:
raise ValueError(f"Discount above {MAX_DISCOUNT}% not allowed")
return round(price * (1 - percent / 100), 2)
# shop.py
from discounts import apply_discount
print(apply_discount(2499, 15)) # 2124.15
Related chapters
FAQ
What is the difference between a module and a package in Python?
A module is a single .py file. A package is a folder of modules, usually with an __init__.py file, that you import with dotted names such as email.mime.text.
Why does pip install work but import still fails?
pip installed into a different Python than the one running your script. Run python -m pip install inside the same interpreter or virtual environment your script uses.
Do I need a virtual environment for every project?
Yes for anything you keep. It isolates package versions, makes requirements.txt reproducible and prevents one upgrade from breaking an unrelated project.
Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.
Chapter 25 of 48 · Python with AI: all 48 chapters



