- Understand what modules are and why we use them
- Use import, from...import, and import...as
- Work with Python's standard library
- Know where Python looks for modules
Importing Modules
Imagine building a house. You don't make every brick yourself – you buy them! In programming, modules are like pre-made bricks. They contain ready-to-use code that saves you from reinventing the wheel.
Python has thousands of modules available: math functions, date handling, web requests, data analysis, and much more. Learning to import and use modules unlocks the true power of Python!
What is a Module?
A module is simply a Python file (.py) containing:
- Functions
- Classes
- Variables
- Runnable code
What is a Module?
my_module.py
# Variables
PI = 3.14159
# Functions
def greet(name):
return f"Hi {name}"
# Classes
class Calculator:
...
Other files can import and use PI, greet(), Calculator
Ways to Import
1. Import the Whole Module
import math
# Use with module prefix
result = math.sqrt(16) # 4.0
pi_value = math.pi # 3.14159...
circumference = 2 * math.pi * 5
Pros: Clear where functions come from
Cons: More typing
2. Import Specific Items
from math import sqrt, pi
# Use directly (no prefix)
result = sqrt(16) # 4.0
circumference = 2 * pi * 5
Pros: Less typing
Cons: Less clear where they came from
3. Import with Alias
import numpy as np
import pandas as pd
# Use short alias
array = np.array([1, 2, 3])
data = pd.DataFrame({"col": [1, 2]})
Pros: Standard aliases everyone recognizes
Use for: Long module names, common conventions
4. Import Everything (Avoid!)
from math import * # Discouraged!
# All names imported - but which module are they from?
result = sqrt(16) # Where did sqrt come from?
Why avoid: Causes naming conflicts, unclear code
Python Standard Library
Python comes with "batteries included" – a rich standard library:
| Module | Purpose | Example |
|---|---|---|
math |
Math functions | sqrt(), sin(), pi |
random |
Random numbers | random(), choice() |
datetime |
Dates and times | datetime.now() |
os |
Operating system | os.getcwd() |
json |
JSON handling | json.loads() |
re |
Regular expressions | re.search() |
collections |
Data structures | Counter, defaultdict |
Exploring Modules
import math
# See what's in a module
print(dir(math)) # Lists all names
# Get help
help(math.sqrt) # Documentation for sqrt
Practical Examples
Example 1: Math Operations
import math
# Calculate circle properties
radius = 5
area = math.pi * radius ** 2
circumference = 2 * math.pi * radius
print(f"Area: {area:.2f}")
print(f"Circumference: {circumference:.2f}")
# Trigonometry
angle = math.radians(45) # Convert degrees to radians
print(f"sin(45°) = {math.sin(angle):.4f}")
Example 2: Working with Dates
from datetime import datetime, timedelta
# Current date/time
now = datetime.now()
print(f"Now: {now}")
# Date arithmetic
tomorrow = now + timedelta(days=1)
next_week = now + timedelta(weeks=1)
# Formatting
print(now.strftime("%Y-%m-%d")) # 2024-01-15
print(now.strftime("%B %d, %Y")) # January 15, 2024
Example 3: Random Choices
import random
# Random number
dice = random.randint(1, 6)
print(f"You rolled: {dice}")
# Random choice from list
colors = ["red", "blue", "green", "yellow"]
chosen = random.choice(colors)
print(f"Random color: {chosen}")
# Shuffle a list
cards = list(range(1, 11))
random.shuffle(cards)
print(f"Shuffled: {cards}")
Where Python Looks for Modules
Module Search Path
When you write: import mymodule
Python searches in this order:
1. Current directory (where your script is)
2. PYTHONPATH environment variable directories
3. Standard library directories
4. Site-packages (installed third-party modules)
Check the path:
import sys
print(sys.path)
Common Import Mistakes
1. Circular Imports
# file_a.py
from file_b import func_b # Imports file_b
def func_a(): ...
# file_b.py
from file_a import func_a # Imports file_a -> loops!
def func_b(): ...
# Fix: Restructure code or import inside functions
2. Naming Conflicts
# BAD: Your file named 'math.py'
import math # Imports YOUR file, not Python's math!
# GOOD: Use unique names for your files
# my_math_utils.py instead of math.py
3. Import * Issues
from module_a import *
from module_b import *
# If both have 'process()', which one do you get?
process() # Confusing! Last import wins
Key Takeaways
Remember These Points
import module - imports entire module
Use as: module.function()
from module import item - imports specific items
Use as: item() (no prefix)
import module as alias - creates short name
Common: numpy as np, pandas as pd
Avoid: from module import * (unclear code)
Standard library has tons of useful modules
math, datetime, random, os, json, etc.
What's Next?
You've learned to use existing modules! In the next lesson, you'll learn to create your own modules – organizing your code for reuse across projects.
