BEGINNER SERIES · SESSION 4
Python
Modules
for Beginners
import Standard Library pip & PyPI Custom Modules
Reuse code, tap into Python's ecosystem, and build modular programs!
Python Programming · Modules · import · Standard Library · pip · Custom Modules
What are Modules? pip & Third-Party Libs
01 04
Code reuse & organisation Installing from PyPI
WHAT
WE'LL import Statements Creating Custom Modules
COVER 02
How to load a module
05
Write & import your own files
Python Modules
Standard Library Packages
03 06
Built-in Python batteries Organising modules in folders
01 What are Modules?
A module is a file containing Python code (functions, classes, variables) that you can reuse in other programs by importing it.
Reusability Organisation
Write a function once, use it in many programs. No copy-pasting the Split large programs into smaller, focused files. Easier to read, debug
same code everywhere. and maintain.
Ecosystem Namespacing
Access 400,000+ ready-made modules on PyPI covering AI, web, data Variables in a module live in their own space — no accidental name
science and more. conflicts.
02 import Statements — Loading a Module
import module from module import name
import math from math import sqrt, pi
# Use [Link]() # Use directly, no prefix
print([Link](16)) # 4.0 print(sqrt(25)) # 5.0
print([Link]) # 3.14… print(pi) # 3.14…
Best practice — clear namespace Import only what you need
import module as alias from module import *
import numpy as np from math import *
import pandas as pd
# Imports EVERYTHING
# Use short alias print(sqrt(9)) # 3.0
arr = [Link]([1,2,3]) # Avoid — pollutes namespace
Shortens long module names Generally not recommended
03 Python Standard Library — Batteries Included!
Python comes with 200+ built-in modules — no installation needed! Just import and use them.
math random datetime
Mathematical functions Random numbers & choices Dates, times & durations
[Link](16) → 4.0 [Link](1,10) [Link]()
[Link](3.7) → 3 [Link](['a','b']) [Link]()
[Link] → 3.14159 [Link](list) timedelta(days=7)
os sys json
OS & file-system access Python interpreter info JSON encode / decode
[Link]() [Link] [Link](text)
[Link]('.') [Link] [Link](obj)
[Link]('[Link]') [Link](0) [Link](obj, file)
Standard Library in Action — math, random,
03+
datetime
using_math.py using_random.py using_datetime.py
import math import random from datetime import datetime, date
# Common functions # Random integer # Today's date
print([Link](144)) # 12.0 n = [Link](1, 10) today = [Link]()
print([Link](2, 8)) # 256.0 print(n) # e.g. 7 print(today) # 2025-01-15
print([Link](4.9)) # 4
print([Link](4.1)) # 5 # Pick from a list # Current date and time
print([Link]) # 3.14159… colors = ['red','blue','green'] now = [Link]()
print(math.e) # 2.71828… print([Link](colors)) print([Link]("%H:%M:%S"))
# Trigonometry # Shuffle a list # Day of the week
print([Link]([Link]/2)) # 1.0 [Link](colors) print([Link]('%A'))
04 pip & Third-Party Libraries — Supercharge Python!
400,000 packages available on PyPI (Python Package Index) — the world's largest Python repository.
+
pip Commands Popular Packages
pip install requests Install a package requests HTTP requests / APIs
pip install numpy==1.26.0 Install specific version numpy Numerical computing
pip uninstall requests Remove a package pandas Data analysis
pip list List installed packages matplotlib Data visualisation
pip show requests Info about a package flask Web framework
pip freeze > [Link] Export package list pillow Image processing
05 Creating Custom Modules — Write Your Own!
1. Create .py file → 2. Write functions → 3. Save the file → 4. Import in [Link]
[Link] ← MODULE FILE [Link] ← YOUR MAIN PROGRAM
"""My custom tools module""" # Import your custom module
import mytools
# A simple function
def greet(name): # Use functions from mytools
return f"Hello, {name}!" msg = [Link]('Bob')
print(msg) # Hello, Bob!
# A maths helper
def square(n): result = [Link](7)
return n * n print(result) # 49
def is_even(n): print(mytools.is_even(4)) # True
return n % 2 == 0 print([Link]) # Alice
# Module-level variable # OR use from-import style
AUTHOR = 'Alice' from mytools import greet, square
05+ The __name__ == "__main__" Guard
Every Python file has a special __name__ variable. When run directly it equals "__main__". When imported it equals the filename.
Running directly: python [Link] When imported: import mytools
def greet(name): # In [Link]:
return f"Hello, {name}!" import mytools
def square(n): # __name__ inside mytools = 'mytools'
return n * n # → guard block does NOT run
# Only runs when executed directly # Only the functions are loaded
if __name__ == "__main__": msg = [Link]('Alice')
print(greet("World")) print(msg) # Hello, Alice!
print(square(5))
# No unwanted side-effects!
06 Packages — Organising Modules in Folders
A package is a folder of Python modules. It must contain an __init__.py file. Packages let you organise large projects neatly.
Project Folder Structure [Link]
my_project/ # Import from a package
from mypackage import greetings
├── [Link]
from mypackage import maths
├── mypackage/
│ ├── __init__.py # Use package modules
print([Link]('Alice'))
│ ├── [Link]
print([Link](5, 3))
│ ├── [Link]
# Or dot-notation import
│ └── [Link]
import [Link] as ut
└── tests/ [Link]('Started!')
├── __init__.py
# __init__.py controls what's
└── test_math.py
# available when you import pkg
Python Modules — Quick Reference Cheatsheet
import Styles Standard Library pip Commands Custom Module
import math import math pip install <pkg> # [Link]
[Link](16) import random pip uninstall <pkg> def greet(n):
from math import sqrt import datetime pip list return f"Hi {n}"
sqrt(16) import os pip show <pkg> if __name__=="__main__":
import numpy as np import sys pip freeze > [Link] print(greet('Bob'))
[Link]([1,2,3]) import json pip install -r [Link] # [Link]
# Avoid: from x import * # 200+ built-in modules! # PyPI: 400k+ packages import mytools
dir(module) lists all attributes · help(module) shows docs · module.__file__ shows the file path
What You Learned Today!
What are Modules
Files of reusable code — import once, use everywhere
What's Next?
import Statements → Functions & Lambdas
import x, from x import y, import x as alias — 4 styles
→ File I/O
Standard Library
→ Exception Handling
200+ built-in modules: math, random, datetime, os, json…
→ Virtual Environments
pip & Third-Party
pip install to grab 400,000+ packages from PyPI
→ Web APIs (requests)
Custom Modules
→ Data Science (numpy)
Write a .py file with functions, import it in your main program
Packages
Folders of modules with __init__.py for large projects
Explore [Link] · [Link]/3/library · [Link] · [Link]