Modules and import
Splitting code across files and unlocking Python’s enormous standard library — the key to writing bigger, cleaner programs.
"Python comes with batteries included. Before you write any code, check if Python’s standard library already solved the problem for you."
— ShurAIWhat is a Module?
A module is simply a .py file containing Python code — functions, variables, and classes. When you import it, you get access to everything inside. Python ships with over 200 built-in modules in its standard library, ready to use the moment you install Python — no extra downloading needed.
Three Ways to Import
# 1. Import the whole module — use dot notation to access things
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592...
# 2. Import specific names — call them directly, no dot needed
from math import sqrt, pi
print(sqrt(25)) # 5.0
print(pi) # 3.141592...
# 3. Import with an alias — shorter name to type
import datetime as dt
print(dt.date.today()) # today’s date
Use import math when you need several things from a module — the dot shows clearly where each function came from. Use from math import sqrt for one or two functions you call constantly. Avoid from math import * — it dumps everything into your namespace and makes bugs hard to trace.
Exploring Any Module
import math
# List everything a module contains
print(dir(math))
# [’acos’, ’acosh’, ... ’sqrt’, ’tan’, ’tau’, ’trunc’]
# Read the built-in documentation for any function
help(math.sqrt)
# sqrt(x, /) Return the square root of x.
Writing Your Own Module
Any .py file you create is a module. Save the file, then import it from another file in the same folder:
# greetings.py — your own module
SITE_NAME = "ShurAI"
def hello(name):
return f"Hello, {name}! Welcome to {SITE_NAME}."
def goodbye(name):
return f"See you soon, {name}!"
import greetings
print(greetings.hello("Riya")) # Hello, Riya! Welcome to ShurAI.
print(greetings.goodbye("Riya")) # See you soon, Riya!
print(greetings.SITE_NAME) # ShurAI
The Standard Library — Your Free Toolkit
These are some of the most useful modules that come built into every Python installation:
"The standard library is Python’s superpower. Every module was written by experts, tested by millions, and costs you nothing to use."
— ShurAI🧠 Quiz — Q1
What does import math do?
🧠 Quiz — Q2
What is the difference between import math and from math import sqrt?
🧠 Quiz — Q3
What does dir(math) show you?
🧠 Quiz — Q4
You create utils.py with a function add(). How do you use it in another file in the same folder?