Modules and Packages#

A module is a .py file containing functions, classes, and variables that can be imported by other programs. A package is a folder containing multiple modules.


Importing modules#

import the whole module#

1
2
3
4
5
6
import math

print(math.sqrt(16))   # 4.0
print(math.pi)         # 3.141592653589793
print(math.ceil(3.2))  # 4
print(math.floor(3.9)) # 3

from ... import specific names#

1
2
3
4
5
from math import sqrt, pi

print(sqrt(25))  # 5.0
print(pi)        # 3.141592653589793
# No need for the math. prefix

Import with an alias (as)#

1
2
3
4
5
import numpy as np          # conventional alias
import pandas as pd         # conventional alias

import datetime as dt
print(dt.date.today())

Common standard library modules#

math: mathematical operations#

1
2
3
4
5
6
7
8
9
import math

print(math.sqrt(2))      # 1.4142... (square root)
print(math.log(100, 10)) # 2.0 (log base 10 of 100)
print(math.log(math.e))  # 1.0 (natural logarithm)
print(math.sin(math.pi / 2))  # 1.0
print(math.factorial(5)) # 120
print(math.gcd(48, 18))  # 6 (greatest common divisor)
print(math.inf)           # inf (positive infinity)

random: random numbers#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import random

# Random integer
print(random.randint(1, 100))   # random integer between 1 and 100

# Random float
print(random.random())           # between 0.0 and 1.0

# Pick one item from a list at random
fruits = ["apple", "banana", "cherry"]
print(random.choice(fruits))

# Pick n items without replacement
print(random.sample(fruits, 2))

# Shuffle a list in place
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)

# Set a random seed (for reproducible results)
random.seed(42)
print(random.randint(1, 100))  # always the same result

datetime: dates and times#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from datetime import datetime, date, timedelta

# Current date and time
now = datetime.now()
print(now)                        # 2026-04-11 15:30:00.123456
print(now.year, now.month, now.day)   # 2026 4 11
print(now.hour, now.minute, now.second)  # 15 30 0

# Formatted output
print(now.strftime("%Y-%m-%d"))       # 2026-04-11
print(now.strftime("%Y/%m/%d %H:%M")) # 2026/04/11 15:30

# Parse a string into datetime
d = datetime.strptime("2026-01-01", "%Y-%m-%d")
print(d)  # 2026-01-01 00:00:00

# Date arithmetic
today = date.today()
delta = timedelta(days=30)
future = today + delta
print(f"30 days from now: {future}")

# Calculate the difference between two dates
start = date(2026, 1, 1)
end = date(2026, 4, 11)
diff = end - start
print(f"Difference: {diff.days} days")  # Difference: 100 days

os: operating system operations#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import os

# Get current directory
print(os.getcwd())

# Path operations
path = os.path.join("folder", "subfolder", "file.txt")
print(path)  # folder/subfolder/file.txt (system-dependent format)

print(os.path.exists("file.txt"))     # Whether the file exists
print(os.path.isfile("file.txt"))     # Whether it is a file
print(os.path.isdir("folder"))        # Whether it is a directory
print(os.path.basename("/path/file.txt"))  # file.txt
print(os.path.dirname("/path/file.txt"))   # /path

# Get an environment variable
home = os.environ.get("HOME", "not set")
print(home)

json: JSON data handling#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import json

# Python object to JSON string
data = {"name": "Alice", "age": 25, "scores": [85, 92, 78]}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)

# JSON string to Python object
json_data = '{"name": "Bob", "age": 30}'
obj = json.loads(json_data)
print(obj["name"])  # Bob

# Write to a JSON file
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

# Read from a JSON file
with open("data.json", "r", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded)

collections: advanced data structures#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from collections import Counter, defaultdict, deque

# Counter: count occurrences
text = "hello world"
count = Counter(text)
print(count)              # Counter({'l': 3, 'o': 2, ...})
print(count.most_common(3))  # Top 3 most common elements

words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
word_count = Counter(words)
print(word_count)  # Counter({'apple': 3, 'banana': 2, 'cherry': 1})

# defaultdict: dictionary with a default value factory
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
dd["vegs"].append("carrot")
print(dict(dd))  # {'fruits': ['apple', 'banana'], 'vegs': ['carrot']}

# deque: double-ended queue (fast appends and pops at both ends)
d = deque([1, 2, 3])
d.appendleft(0)
d.append(4)
print(d)           # deque([0, 1, 2, 3, 4])
d.popleft()
print(d)           # deque([1, 2, 3, 4])

Creating your own module#

Create myutils.py:

1
2
3
4
5
6
7
8
9
# myutils.py

def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32

def is_even(n):
    return n % 2 == 0

PI = 3.14159

Import it in another file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# main.py (in the same folder as myutils.py)
import myutils

print(myutils.celsius_to_fahrenheit(100))  # 212.0
print(myutils.is_even(4))                  # True
print(myutils.PI)                          # 3.14159

# Or import specific names with from
from myutils import celsius_to_fahrenheit
print(celsius_to_fahrenheit(0))            # 32.0

Installing third-party packages (pip)#

Python’s package manager is pip:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# Install a package
pip install requests
pip install pandas

# Install a specific version
pip install requests==2.31.0

# List installed packages
pip list

# Export package list (useful for sharing a project)
pip freeze > requirements.txt

# Install all packages from the list
pip install -r requirements.txt

# Uninstall a package
pip uninstall requests

Common third-party packages#

PackagePurpose
requestsHTTP requests (web scraping, APIs)
pandasData analysis
numpyNumerical computing
matplotlibData visualization
beautifulsoup4HTML parsing
fastapiFast API development
sqlalchemyDatabase ORM