Modules and Imports
Learn how to use Python's built-in modules and install external packages to extend what your programs can do.
A module is a file of ready-made code
A module is a file containing Python code. Python comes with a large library of modules that give you ready-made tools for common tasks. Instead of writing everything from scratch, you import a module and use code that someone else already wrote and tested. It is like borrowing a toolbox instead of forging your own hammer.
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(25)) # 5.0
print(math.floor(4.7)) # 4
print(math.ceil(4.2)) # 5
After import math, you reach its tools by writing the module name, a dot, then the tool name. If you only need one or two things, import just those:
from math import sqrt, pi
print(sqrt(16)) # 4.0, no need to write math.sqrt
print(pi) # 3.141592653589793
Both styles are fine. import math keeps it clear where each tool comes from. from math import sqrt is shorter to type. Put imports at the top of your file, so anyone reading it sees what the program needs. Avoid from math import *, because it dumps everything into your code and can hide name clashes.
You can also give a module a shorter nickname with as: import datetime as dt.
A tour of the standard library
The modules that come with Python are called the standard library. You do not need to install anything. Here are the ones you will use most often:
- random: generate random numbers and make random choices
- datetime: work with dates and times
- os: interact with the operating system (files, folders, environment)
- json: read and write JSON data
- re: work with regular expressions (pattern matching in text)
- time: pause execution and measure time
- math: square roots, rounding and other math tools
- sys: information about Python itself and command line arguments
A good habit is to search before you build. If you need something common, such as dates, random numbers or reading a CSV file, there is probably already a module for it. You can see what a module offers with help(math) or dir(math) in the shell, or read the official docs at docs.python.org.
The random module
import random
print(random.randint(1, 10)) # random integer between 1 and 10
print(random.random()) # random float between 0.0 and 1.0
print(random.choice(["rock", "paper", "scissors"])) # random item from a list
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers) # shuffle a list in place
print(numbers)
Notice that randint(1, 10) includes both ends, so it can return 10 different numbers. This is different from range, which stops before the end number. random.choice picks one item, and random.shuffle mixes a list in place.
Here is a tiny number guessing game that uses it:
import random
secret = random.randint(1, 10)
guess = int(input("Guess a number from 1 to 10: "))
if guess == secret:
print("You got it!")
else:
print(f"Not this time. It was {secret}.")
The numbers are not truly random, but they are random enough for games and tests. For passwords and anything security related, use the secrets module instead.
The datetime module
from datetime import datetime, date
now = datetime.now()
print(now) # current date and time
print(now.year) # current year
print(now.strftime("%d/%m/%Y")) # format as day/month/year
today = date.today()
print(today)
datetime.now() gives the current moment. You can read its parts, such as now.year, now.month, now.day, now.hour and now.minute. The strftime() method turns a date into text using codes:
%Yfour digit year,%ytwo digit year%mmonth number,%Bmonth name%dday of the month%Hhour (24 hour),%Mminutes,%Sseconds
print(now.strftime("%B %d, %Y")) # for example: October 06, 2026
print(now.strftime("%H:%M")) # for example: 14:30
You can also do math with dates. The difference between two dates is a timedelta, and it has a .days value:
from datetime import date
start = date(2026, 1, 1)
end = date(2026, 3, 1)
print((end - start).days) # 59
The json module
JSON is a popular text format for storing and sharing data. It looks a lot like Python dictionaries and lists, so they convert to JSON and back easily. Websites and apps use it to talk to each other.
import json
data = {"name": "Alice", "age": 25, "scores": [90, 85, 92]}
# Convert Python object to JSON string
json_string = json.dumps(data, indent=2)
print(json_string)
# Convert JSON string back to Python object
loaded = json.loads(json_string)
print(loaded["name"]) # Alice
# Save to a file
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Load from a file
with open("data.json", "r") as f:
loaded = json.load(f)
print(loaded)
There is an easy way to remember the four functions. The ones ending in s work with a string (dumps, loads). The ones without the s work with a file (dump, load). And dump means Python to JSON, while load means JSON to Python.
This is the best way to save lists and dictionaries to a file. It keeps the structure, so you get the same object back next time the program starts.
Installing packages with pip
Beyond the standard library, Python has hundreds of thousands of third-party packages written by other people. The tool that installs them is called pip. Open your terminal (not the Python shell) and run:
pip install requests
On some systems the command is pip3 install requests or python -m pip install requests. The requests library makes it easy to send HTTP requests to websites and APIs:
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # 200 means success
data = response.json()
print(data)
The status code tells you how the request went. 200 means success, 404 means the page was not found, and 500 means the server had a problem. response.json() turns the reply into a Python dictionary for you.
Other pip commands you will use: pip list shows what is installed, pip uninstall name removes a package, and pip install --upgrade name updates it. Only install packages from sources you trust, since a package runs code on your computer.
Making your own module
Any Python file can be used as a module. Create a file called mytools.py:
# mytools.py
def add(a, b):
return a + b
def greet(name):
return f"Hello, {name}!"
Then in another file in the same folder:
# main.py
import mytools
print(mytools.add(3, 5)) # 8
print(mytools.greet("Alice")) # Hello, Alice!
The module name is the file name without .py. This is how big programs stay organized: related functions go in one file, and other files import them.
A useful trick is the __name__ check. When a file is run directly, Python sets __name__ to "__main__". When it is imported, it does not. So this block only runs when you start the file yourself, not when someone imports it:
# mytools.py
def add(a, b):
return a + b
if __name__ == "__main__":
print(add(2, 3)) # quick self test, only runs directly
Common mistakes
- ModuleNotFoundError. Either you misspelled the name, or the package is not installed yet. Try
pip install name. - Naming your file like a module. If you save your program as
random.py, thenimport randomloads your file instead of the real one. Pick unique names. - Forgetting the module name. After
import math, you must writemath.sqrt(...), not justsqrt(...). - Wrong folder for your own module. The file must be in the same folder as the program that imports it.
- Installing into the wrong Python. If you have several versions, use
python -m pip installso pip matches your Python.
import mth
# ModuleNotFoundError: No module named 'mth'
Read the name carefully. A tiny spelling difference is the cause most of the time.
Key takeaways
- A module is a Python file full of reusable code.
importbrings it in import maththenmath.sqrt(4), orfrom math import sqrtthensqrt(4)- The standard library includes
random,datetime,os,json,re,timeand many more random.randint(a, b)includes both ends, andrandom.choicepicks from a listjson.dumpsandjson.loadswork with strings.json.dumpandjson.loadwork with filespip install nameadds third-party packages such asrequests- Any
.pyfile in the same folder can be imported as your own module