Python Modules and Imports
1Python Modules: overview
A module is a file of Python code (functions, classes and values) that you load into your program with import, so you can reuse it instead of writing it again.
Before this lesson: Python Functions, Python Variable Scope
2Python Modules: diagram
3Python Modules: explained step by step
A module is a file of Python code that another program can load and use. Python comes with hundreds of them, together called the standard library, and every .py file you write is a module too. Importing lets you reuse code that already exists instead of writing it again, and it lets you split a big program into tidy, separate files.
Three ways to import
import math # the whole module
from random import choice, seed # only the names you need
import datetime as dt # the module under a short nickname
print(math.sqrt(81))
seed(1)
print(choice(["red", "green", "blue"]))
print(dt.date(2025, 3, 15).year)import mathkeeps the module name as a prefix, so you writemath.sqrt(). It takes a few more keystrokes, but anyone reading the code can see exactly wheresqrtcame from.from random import choicecopieschoicestraight into your file, so you call it without a prefix. That's handy for names you use a lot, but if you also define your ownchoice, one silently replaces the other.asgives a module a nickname. You will seeimport numpy as npandimport pandas as pdin almost every data project.
A quick tour of the standard library
math: square roots, rounding up and down (ceil,floor),pi.random: random numbers and choices. Callrandom.seed(n)first when you need the same "random" results on every run, for example in tests.datetime: dates, times and the gaps between them (timedelta).collections: smarter containers such asCounteranddefaultdict.
from collections import Counter
from datetime import date
votes = ["tea", "coffee", "tea", "juice", "tea"]
print(Counter(votes).most_common(2))
start = date(2025, 1, 1)
deadline = date(2025, 3, 1)
print((deadline - start).days, "days to go")Writing your own module
Save a few functions in a file called helpers.py:
# helpers.py
TAX_RATE = 0.2
def add_tax(price):
return round(price * (1 + TAX_RATE), 2)
Any file in the same folder can now import it. Use the file name without .py:
# main.py
import helpers
print(helpers.add_tax(50)) # 60.0
Snippets on this page run as a single file, so they can only import built-in modules. The site's IDE lets you create several files: make a helpers.py there and import it from main.py to try this for real.
What if __name__ == "__main__" means
Importing a module runs all of its top-level code once. Python also gives every module a special variable, __name__. In the file you actually ran it is "__main__"; in a file that was imported it is the module's own name, such as "helpers". So code inside if __name__ == "__main__": runs only when you run that file directly. It's the right place for demos and quick tests that should stay quiet when someone imports your module.
def area(width, height):
return width * height
print("__name__ is", __name__)
if __name__ == "__main__":
print("Run directly, testing:", area(3, 4))Quick reference: Python Modules
- Python Module vs Package: What Is the Difference? — A **module** is a single Python file (such as `utils.py`) that you can import, while a **package** is a direc…
- How to Install a Package with pip in Python — Run `python -m pip install package_name` in your terminal (not inside the Python prompt). Using `python -m pi…
- How to Create a Virtual Environment in Python — Run `python -m venv .venv` in your project folder, then activate it with `source .venv/bin/activate` (macOS a…
- How to Run a Python Script from the Command Line — Save your code in a file such as `hello.py`, open a terminal in that folder and run `python hello.py` (or `py…
4Python Modules: syntax
import module_name # use as module_name.thing
import module_name as alias # use as alias.thing
from module_name import name1, name2 # use name1 directly
if __name__ == "__main__":
# runs only when this file is run directly, not when imported
main()
5Python Modules: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
import math
import random
from datetime import date, timedelta
from collections import Counter
students = 27
seats_per_bus = 12
buses = math.ceil(students / seats_per_bus)
print("Buses needed:", buses)
trip_day = date(2025, 5, 12)
reminder = trip_day - timedelta(days=7)
print("Send reminder on:", reminder.strftime("%A, %d %B %Y"))
random.seed(42)
leader = random.choice(["Asha", "Ben", "Chen", "Dara"])
print("Trip leader:", leader)
lunches = ["veg", "chicken", "veg", "fish", "veg", "chicken"]
print("Lunch orders:", Counter(lunches).most_common())Expected outputBuses needed: 3
Send reminder on: Monday, 05 May 2025
Trip leader: Asha
Lunch orders: [('veg', 3), ('chicken', 2), ('fish', 1)]
7Python Modules: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1-4Two import styles:
mathandrandomare imported whole (used with a prefix), whiledate,timedeltaandCounterare pulled out of their modules by name. - Line 6-927 / 12 is 2.25, and you can't book a quarter of a bus.
math.ceil()rounds up to the next whole number: 3. - Line 11-13
date(2025, 5, 12)is a fixed date. Subtracting atimedeltaof 7 days gives 5 May, andstrftime()formats it with the weekday (%A) and month name (%B). - Line 15-17
random.seed(42)fixes the starting point of the random number generator, sochoice()picks the same leader on every run. Remove the seed and the leader changes each time. - Line 19-20
Countercounts how often each value appears, andmost_common()lists them from most to least frequent.
8Python Modules: common mistakes
Naming your own file after a module you import
✗ Wrong
# this file is saved as random.py
import random
print(random.randint(1, 6))✓ Right
# this file is saved as dice.py
import random
print(random.randint(1, 6))Python looks in your own folder first, so import random loaded your file instead of the real module. Give your file a different name, such as dice.py.
Calling a function without its module name
✗ Wrong
import math
print(sqrt(49))✓ Right
import math
print(math.sqrt(49))import math creates only the name math. Either write math.sqrt(49), or import the function itself with from math import sqrt.
Mixing up the datetime module and the datetime class
✗ Wrong
import datetime
meeting = datetime(2025, 6, 1, 9, 30)✓ Right
from datetime import datetime
meeting = datetime(2025, 6, 1, 9, 30)
print(meeting)The module and the class inside it are both called datetime. Import the class with from datetime import datetime, or write datetime.datetime(...).
9Python Modules: exercises
Write your answer, then press Check. The checks run in your browser.
1. How many boxes?
Write code Easy ✓ CompletedComplete the function boxes_needed(items, per_box) so it returns how many boxes are needed to pack items things when each box holds per_box. A part-full box still counts, so round up with the math module. For example boxes_needed(10, 4) is 3.
import math
def boxes_needed(items, per_box):
# return the number of boxes (round up!)
pass
print(boxes_needed(10, 4))import math
def boxes_needed(items, per_box):
return math.ceil(items / per_box)
print(boxes_needed(10, 4))
2. Predict the imports
Predict the output Medium ✓ CompletedRead the code and type exactly what it will print. Then press Check to run it and compare.
import math as m
from collections import Counter
print(m.floor(7.9), m.ceil(7.1))
print(Counter("banana")["a"])
print(__name__)7 8
3
__main__
2 more exercises → 4 more examples
Questions learners ask
What is the difference between a module and a package in Python?
A module is a single .py file. A package is a folder that groups several modules (and sometimes smaller packages) under one name. You reach the parts with dots, for example from email.message import EmailMessage or import xml.etree.ElementTree as ET. Both are imported with the same import statements.
Why does importing my file run its code?
To create a module's functions and variables, Python runs the module's top-level code the first time it is imported. Any print() calls or tests at the top level run too. Put that code under if name == "main": so it only runs when you run the file directly. Python also caches imports, so importing the same module again does not run it a second time.
Which modules can I import on this site?
Most of the standard library works, including math, random, datetime, json, csv, re, collections, itertools and statistics. Packages listed on the Packages page, such as numpy, pandas and matplotlib, load automatically when you import them. GUI modules like tkinter and turtle cannot run inside a browser.
Further reading
10Next lesson
Up nextPython math and statisticsPython's built-in operators, the math module and the statistics module handle everyday calculations such as roots, roun…Related:
Python Variable ScopePython math and statisticsPython random ModulePython datetime Module
← Python Type Hints · All Functions and Modules lessons · Practise in the IDE