Python Lesson 18: Modules and Packages
Modules are Python files with reusable code. Python comes with hundreds of built-in modules, and you can install thousands more. Never write code that already exists — import it!
Importing Modules
import math
import random
import os
# Use functions from the module
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.14159...
print(math.ceil(4.3)) # 5
print(math.floor(4.9)) # 4
print(random.randint(1, 10)) # random number 1-10
print(random.choice(["a","b","c"])) # random item
from … import (specific function)
from math import sqrt, pi
from random import randint, shuffle
# Now use without "math." prefix
print(sqrt(25)) # 5.0
print(pi) # 3.14159
print(randint(1, 6)) # roll a dice!
Useful Built-in Modules
import datetime
import os
import json
import time
# Date and time
today = datetime.date.today()
print(today) # 2024-01-15
print(today.year) # 2024
# File system
print(os.getcwd()) # current directory
print(os.listdir(".")) # list files
# Sleep (pause)
time.sleep(1) # pause for 1 second
Installing External Packages
# pip is Python's package installer
# Run in Terminal/Command Prompt:
# pip install requests
# pip install pandas
# pip install pillow
# Then use in your code:
# import requests
# response = requests.get("https://api.example.com")
Creating Your Own Module
# File: my_math.py
def add(a, b):
return a + b
def square(n):
return n ** 2
PI = 3.14159
# File: main.py (same folder)
import my_math
print(my_math.add(3, 4)) # 7
print(my_math.square(5)) # 25
print(my_math.PI) # 3.14159
🏋️ Practice Task
Use the random module to build a Password Generator. Ask user how many characters they want. Generate a random password using letters + numbers + symbols. Print the password.
💡 Hint: Use random.choice() with a string of all valid characters. Use “”.join() to combine the characters. import string gives you string.ascii_letters, string.digits, string.punctuation.