Skip to main content
Python for Beginners
CHAPTER 15 Beginner

Python Modules and Packages

Updated: May 17, 2026
20 min read

# Python Modules and Packages

Welcome to Chapter 15! As programs grow, you need to organize code into reusable pieces. Modules and packages let you split code across files and reuse functionality efficiently.

---

1. Learning Objectives

  • Import and use built-in modules.
  • Create custom modules.
  • Understand packages and _init.py.
  • Use pip to install third-party packages.
  • Set up virtual environments.

---

2. Importing Modules

```python id="py15ex1" # Import entire module import math print(math.sqrt(16)) # 4.0 print(math.pi) # 3.14159...

# Import specific items from math import sqrt, pi print(sqrt(25)) # 5.0

# Import with alias import datetime as dt print(dt.datetime.now())

# Import everything (avoid in production!) from math import * print(ceil(4.2)) # 5

1234
---

## 3. Useful Built-in Modules

python id="py15ex2" # os — operating system interface import os print(os.getcwd()) print(os.listdir("."))

# random import random print(random.randint(1, 100)) print(random.choice(["apple", "banana", "cherry"]))

# json import json data = {"name": "Alice", "age": 25} jsonstr = json.dumps(data, indent=2) print(json_str)

# collections from collections import Counter words = "hello world hello python hello".split() print(Counter(words)) # Counter({'hello': 3, 'world': 1, 'python': 1})

123456
---

## 4. Creating Custom Modules

Create a file `mymath.py`:

python id="py15ex3" # mymath.py PI = 3.14159

def circlearea(radius): return PI * radius ** 2

def rectangle_area(length, width): return length * width

12
Use it in another file:

python id="py15ex4" # main.py import mymath

print(mymath.circlearea(5)) # 78.53975 print(mymath.rectangle_area(4, 6)) # 24 print(mymath.PI) # 3.14159

12
### The `__name__` Variable

python id="py15ex5" # mymath.py def add(a, b): return a + b

if name == "main_": # This only runs when file is executed directly # Not when imported as a module print("Testing: add(2, 3) =", add(2, 3))

123456
---

## 5. Packages

A package is a **directory** containing modules and an `__init__.py` file:

mypackage/ ├── init.py ├── mathutils.py ├── stringutils.py └── data/ ├── init_.py └── loader.py

1

python id="py15ex6" # Using a package from mypackage import mathutils from mypackage.data import loader

1234
---

## 6. pip — Package Manager

bash # Install a package pip install requests

# Install specific version pip install requests==2.31.0

# Upgrade pip install --upgrade requests

# List installed pip list

# Save dependencies pip freeze > requirements.txt

# Install from requirements pip install -r requirements.txt

# Uninstall pip uninstall requests

123456789101112131415161718
### Popular pip Packages

| Package | Purpose |
|---------|---------|
| requests | HTTP requests |
| flask | Web framework |
| django | Full web framework |
| pandas | Data analysis |
| numpy | Numerical computing |
| beautifulsoup4 | Web scraping |
| pytest | Testing |

---

## 7. Virtual Environments

Virtual environments isolate project dependencies:

bash # Create virtual environment python -m venv myenv

# Activate (Windows) myenv\Scripts\activate

# Activate (macOS/Linux) source myenv/bin/activate

# Install packages (inside venv) pip install requests flask

# Deactivate deactivate

1

Without Virtual Environments: ┌────────────────────────────┐ │ System Python │ │ Project A: requests 2.28 │ │ Project B: requests 2.31 │ ← CONFLICT! └────────────────────────────┘

With Virtual Environments: ┌──────────────┐ ┌──────────────┐ │ Project A │ │ Project B │ │ venva/ │ │ venvb/ │ │ req. 2.28 │ │ req. 2.31 │ └──────────────┘ └──────────────┘ ← NO CONFLICT! ``

---

8. Common Mistakes

  1. 1. Circular imports: Module A imports B, B imports A → ImportError.
  1. 2. Naming files same as modules: random.py shadows built-in random.
  1. 3. Not using virtual environments: Causes dependency conflicts.
  1. 4. Forgetting _init.py: Required for Python <3.3 packages.

---

9. MCQs with Answers

Q1: import math imports: A) One function B) Entire module C) A class D) A package Answer: B

Q2: from math import pi imports: A) Entire math module B) Only pi C) All constants D) Error Answer: B

Q3: name == "main" is True when: A) Module is imported B) File is run directly C) Always D) Never Answer: B

Q4: pip stands for: A) Python Install Program B) Pip Installs Packages C) Package Import Protocol D) Python Integration Platform Answer: B

Q5: Virtual environments: A) Speed up Python B) Isolate dependencies C) Encrypt code D) Compile to binary Answer: B

Q6: pip freeze does: A) Stops pip B) Lists installed packages with versions C) Deletes cache D) Updates pip Answer: B

Q7: init.py makes a directory a: A) Module B) Package C) Script D) Library Answer: B

Q8: import numpy as npnp is: A) A copy B) An alias C) A class D) A variable Answer: B

Q9: To install from requirements.txt: A) pip install requirements.txt B) pip install -r requirements.txt C) pip get requirements.txt D) pip load requirements.txt Answer: B

Q10: Which avoids running code on import? A) if name == "main": B) if import: C) if module: D) if file: Answer: A

---

10. Interview Questions

  1. 1. What is name in Python? A special variable that is "main" when the script runs directly, or the module name when imported.
  1. 2. Module vs Package? A module is a single .py file. A package is a directory of modules with init.py.
  1. 3. Why use virtual environments? To isolate project dependencies and avoid conflicts between different projects.
  1. 4. How does Python find modules? It searches sys.path: current directory → installed packages → standard library.
  1. 5. What is a namespace? A mapping of names to objects; each module has its own namespace.

---

11. Summary

  • Modules are .py files with reusable code; import with import.
  • Packages are directories with init.py containing multiple modules.
  • pip installs third-party packages from PyPI.
  • Virtual environments isolate project dependencies.
  • Use if name == "main_":` to guard executable code.

---

12. Next Chapter Recommendation

In Chapter 16: File Handling in Python, you'll learn to read, write, and manage files — a critical skill for real-world programming! 🚀

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·