Lesson 3.2Lesson 3.2 · Functions, Modules & Files
Modules & Libraries
Almost anything you need, someone has already written - learn to import it and you rarely start from scratch
Need pi, a square root, a random pick, a CSV reader, a data table? Someone wrote it years ago. Your job is to import it, not rebuild it.
A beginner's instinct is to write everything from scratch. Python's whole philosophy pushes the other way: batteries included. The language ships with a large standard library of ready-made tools, and beyond it sits a vast open-source ecosystem you can install in seconds.
Importing is how you reach all of it. One import line and you have trigonometry, random numbers, file formats, dates, web requests or a full data-analysis engine at your fingertips. This lesson shows how import works, what comes free in the box, how pip pulls in the rest, and how to split your own growing code into tidy modules you can reuse across projects.
import = reach existing code. Standard library free; pip for the rest; your files are modules too.
import: borrowing code by name
A module is just a file of Python code - functions, values, classes - that someone has already written. import brings that file's contents into your script so you can use them. The standard library alone has hundreds of modules; here is the math module giving you constants and functions you would not want to write yourself:
import math
radius = 3.0
print(math.pi) # 3.141592653589793
print(math.sqrt(2)) # 1.4142135623730951
print(round(math.pi * radius ** 2, 2)) # circle area: 28.27After import math, everything the module offers is reached as math.something - the module name, a dot, then the tool. That dotted prefix is deliberate: it keeps math.pi clearly separate from any pi of your own, so names never collide. Importing does not copy code into your file; it loads the module once and points your script at it. The mental model to hold is simple - your script sits on top of a mountain of code other people wrote, and import is how you reach up and take exactly the piece you need.
A small habit matters here: put your imports at the very top of the file. It is not required - Python will accept an import anywhere - but gathering them at the top lets any reader see at a glance what a script depends on, the same way a drawing's title block lists its references. It also means a missing package fails immediately with a clear message rather than halfway through a long run. One thing import is not is slow or wasteful: Python loads each module only once per program, even if several files import it, so there is no cost to importing the same standard-library module in every file that needs it. Reaching for existing code is the normal state of writing Python, not a special case - by the end of this course almost every script you write will start with a few import lines.
A module is a file of ready-made code. import loads it; use it as module.thing.
Three ways to import, and when to use each
You will see imports written a few ways. Each has a place:
import math # use as math.sqrt(2)
from math import sqrt, pi # use as sqrt(2), pi
import statistics as stats # use as stats.mean([...])Plain import math is the safe default - the math. prefix always tells the reader where a name came from. from math import sqrt pulls specific names straight into your file so you can write sqrt(2) without the prefix; handy when you use one thing a lot, but overdone it clutters your namespace and hides origins. import numpy as np gives a module a short alias - and some aliases are near-universal conventions (np for numpy, pd for pandas) that every reader recognises. One thing to avoid: from math import *, which dumps every name into your file and makes it impossible to tell what came from where. When two modules both define, say, sqrt, the last star-import silently wins - a nasty, invisible bug. Prefer explicit imports; your future self reading the code will thank you.
The deeper reason to care is traceability. When you read someone's script (or your own from last year) and see mean([...]), you have to guess where mean came from - statistics? numpy? a function they wrote? Written as statistics.mean([...]), the answer is right there in the call. That is why the plain import module form is the professional default despite being a few characters longer: it keeps every name's origin visible, which is worth far more than the brevity. The aliases you should adopt are the community-standard ones - import numpy as np, import pandas as pd, import matplotlib.pyplot as plt - precisely because they are universal, so every reader recognises pd.DataFrame instantly. Invent your own quirky aliases and you lose that shared vocabulary. In short: import explicitly, alias only by convention, and never reach for the star.
import x is safest. from x import y is handy. import x as np is a convention. Avoid import *.
The standard library: what comes free in the box
Before you install anything, Python already includes a remarkable toolkit. A designer's most-used corners of it:
import random
palette = ["oak", "walnut", "ash", "birch"]
print(random.choice(palette)) # one random finish
print(random.sample(palette, 2)) # two, no repeats
random.seed(42) # make runs repeatablerandom (options, sampling, noise for generative studies), math (trigonometry and roots for geometry), statistics (mean, median of a data set), csv and json (the file formats of the next two lessons), os and pathlib (files and folders), datetime (dates and durations), and collections (handy specialised containers) will cover an enormous share of everyday scripting. None of these needs installing - they are part of Python itself. It is genuinely worth skimming the standard-library index once so you carry a rough map of what exists; a five-minute browse saves you from writing, badly, something that already ships polished. The habit to build is to ask 'is this in the standard library already?' before writing anything non-trivial - the answer is often yes.
The random example above hides a detail worth pulling out, because it matters for design work. random.seed(42) makes the sequence of random choices repeatable: run the script again and you get the same picks. That sounds contradictory, but it is exactly what you want when a generative study needs to be reproducible - you can share the seed so a colleague sees the same result, then change it to explore a different variation. This is your first taste of the generative scripting that Module 9 develops fully. The broader point is that the standard library is not a dumping ground of trivia; it is a curated set of well-tested tools that has grown over decades. A designer who knows that statistics.mean exists, that datetime does date arithmetic properly (including leap years and month lengths you should never compute by hand), and that collections.Counter tallies items in one line, writes less code and fewer bugs. Treat the standard-library index as a reference you skim, not a manual you memorise.
Standard library = free, always there: math, random, statistics, csv, json, os, datetime.
pip: installing the rest of the world
Beyond the standard library sits PyPI, the Python Package Index - hundreds of thousands of free packages. pip is the tool that installs them. You run it in your terminal, not inside a script:
# In a terminal (not in the Python file):
# pip install pandas
#
# Then, in your script:
import pandas as pd
rooms = pd.DataFrame({"room": ["living", "kitchen"], "area": [18.0, 12.0]})
print(rooms["area"].sum()) # 30.0This is how you get pandas (data tables, Module 4), numpy (fast numbers and geometry), matplotlib (charts), requests (web data), openpyxl (Excel), Pillow (images) and thousands more. A word of care about environments: installing packages system-wide can create version clashes between projects, so real practice uses a virtual environment - an isolated per-project sandbox for packages. You do not need to master that today; just know that when a tutorial says pip install something, it is fetching a package from PyPI, and that the same command underlies the powerful libraries the rest of this course leans on. If an import ever fails with 'No module named ...', it usually just means that package is not installed yet.
A little judgement helps when choosing packages, because PyPI is open to anyone and quality varies. For the mainstream design-and-data work this course covers you will lean on a short list of mature, widely-used packages - pandas, numpy, matplotlib, requests, openpyxl, Pillow - and these are safe, well-documented and everywhere. For anything more obscure, glance at whether it is actively maintained and reasonably popular before you build on it, and be a little careful about running pip install on a package name you half-remember, since a typo can occasionally fetch something you did not mean. None of this should make you hesitant - installing packages is routine and one of Python's great strengths - but treat the ecosystem like any body of sources you cite: prefer the well-established, and know roughly where your tools come from. The reward is enormous: a few pip install commands put decades of other people's careful engineering at your disposal.
pip install <name> fetches from PyPI. That is how pandas, numpy, requests arrive.
Organising your own code into modules
Modules are not only for other people's code - any .py file you write is a module, and you can import it. As your scripts grow, moving reusable functions into their own file keeps each script short and lets you share tools between projects. Say you saved your design functions from the last lesson in a file called design_calcs.py:
# design_calcs.py
def window_ratio(glass, floor):
return glass / floor
def paint_litres(wall_area, coats=2, coverage=10):
return wall_area * coats / coverage# schedule.py (in the same folder)
import design_calcs
print(design_calcs.window_ratio(2.4, 18.0))
print(design_calcs.paint_litres(45))That is the entire mechanism - a file becomes an importable toolbox just by sitting next to your script. This is how the toolkit you began building in Lesson 3.1 becomes portable: gather your trusted functions into a module, and every new project starts with import design_calcs and your whole kit is available. It is also the first step towards code you can genuinely share with colleagues. Modular thinking - small files that each do one thing, imported where needed - is the same instinct scaled up, and it is what keeps larger scripting projects from collapsing into one unreadable file.
One subtlety to know before it surprises you: when Python imports your module, it runs the file top to bottom. That is fine for a file of function definitions, but if design_calcs.py also had loose lines that print or calculate at the top level, those would fire every time it is imported - usually not what you want. The convention that solves this is the if __name__ == "__main__": guard: code under it runs only when the file is executed directly, not when it is imported. You will meet it constantly, and now you know what it is for - it lets one file be both an importable toolbox and a runnable script. For now, the takeaway is lighter: keep modules to definitions (functions and constants), keep the code that uses them in a separate script, and your own growing library stays clean, importable and easy to reuse across every project you take on.
Your own .py file is a module too. Put your functions in one and import it anywhere.
import
Loading a module's code into your script
One line reaches an entire toolbox; access its contents as module.name.
standard library
Modules that ship with Python itself
math, random, statistics, csv, json, os, pathlib, datetime - free, always present, no install.
pip / PyPI
Installing third-party packages from the Python Package Index
Run pip install <name> in a terminal; how pandas, numpy, requests and thousands more arrive.
alias (import as)
A short name for a module
import numpy as np, import pandas as pd - conventions every reader recognises.
module (your own)
Any .py file you can import
Move reusable functions into a file and import it - the basis of organising and sharing your code.
Workshop - build and import your own module
You will use a standard-library module, then package your own functions into a separate file and import them - proving both halves of how Python code is shared.
Python 3. Optionally try pip install pandas in a terminal to see a package install (not required).
Goal: import from the standard library and from your own module Inputs: two functions you have written before Time: ~30 minutes
- 1Import the math module and use it: compute a diagonal with math.sqrt(a2 + b2) or a circle area with math.pi. Print the result rounded.
- 2Import random and use random.choice and random.sample on a small list (finishes, room names); add random.seed(1) and run twice to see the picks repeat.
- 3Create a new file design_calcs.py in the same folder and move two of your reusable functions into it (for example a ratio and an estimate).
- 4In a second file, write import designcalcs and call both functions through it - designcalcs.paint_litres(45) - confirming they work exactly as before.
- 5Try one from-import (from math import sqrt) and note in a comment how the call changes; then explain why import math is often the clearer default.
You’ll walk away with
Two .py files - one module holding your functions, one script that imports both the standard library and your module and prints results - plus a one-line note on when you would install a package with pip.
Three altitudes on the same idea
Read the band that fits you — or all three.
The libraries are the reason scripting scales to real practice. pandas turns a messy area schedule into an analysable table, numpy handles the vector maths behind geometry, matplotlib draws sun-hour or cost charts for a report. You do not build these - you import them. Gathering your own repeated calculations into a shared in-house module, meanwhile, turns scattered scripts into a library your whole studio can import and rely on.
Most of what you need is a one-line import away. openpyxl reads and writes the Excel schedules you already live in, Pillow batch-resizes moodboard images, csv and json move data between tools. Learning which library solves which chore - rather than fighting each by hand - is the highest-leverage habit in this whole module, and none of it requires writing the hard parts yourself.
Knowing the ecosystem is half of being employable. Studios expect you to reach for pandas, numpy and matplotlib by name and to install what a project needs with pip without fuss. Learn the standard-library staples now and practise splitting your assignments into clean modules - readable, reusable code is what separates a strong portfolio from a working-but-messy one.
“A real programmer writes everything themselves - using libraries is cheating or a crutch.”
Do it yourself
Predict, then check by running.
- 1After import math, how do you refer to the square-root function?
- 2What is the difference between import math and from math import sqrt in how you then call it?
- 3Name three standard-library modules a designer would use and what each is for.
- 4Where do you run pip install - inside the Python file or in the terminal - and what does it fetch?
- 5How do you turn a file of your own functions into something another script can import?
The one line to carry out
Peer-reviewed journals & authoritative standards
- 01Library (computing) — Wikipedia, 2026.
- 02Modular programming — Wikipedia, 2026.
- 03The Python Standard Library — Python Software Foundation, 2026.
- 04random - Generate pseudo-random numbers — Python Software Foundation, 2026.
Libraries let you reach code; now you need to reach data. Next we open real files - reading and writing text on disk with open() and with - the skill every later data lesson stands on.
The author
Amogh N P
Architect, interior designer, and creative polymath. Studio Matrx began in his notebooks — his vision of design made honest, useful, and open to everyone. Its Academy is written and taught in his memory, and free, forever.
More about Amogh →