When you write Python programs, you don’t have to reinvent the wheel every time. Python provides a way to organize and reuse code using modules.
📝 If You Want to Practice the Code
If you plan to practice the Python code mentioned within this blog post, you’ll need a working Python environment. You can execute the commands in one of the following ways (choose only one option):
- From a Python prompt in your terminal or command line – see Getting Started with Python and Virtual Environment in Python and How to Set One Up
- Using Miniconda and Jupyter Notebook – see How to Install and Set Up Miniconda and Install Jupytor Notebook Windows, How to Install and Set Up Miniconda on MacOS, How to Install and Set Up Miniconda on Linux (Ubuntu), and Getting Started with Jupyter Notebooks.
- On Google Colab (browser-based, no installation required) – see Getting Started with Google Colab.
- Through VS Code – see Setting Up VS Code for Python Development.
👉 Choose whichever environment you’re most comfortable with. If you haven’t set up Python yet, start with one of the installation posts before trying the examples here.
What is a Module?
A module is just a Python file that contains code — functions, classes, or variables — that you can reuse in other programs.
- If you create a file called
math_tools.pywith a function inside, that’s a module. - Python also comes with a big set of built-in modules (like
math,os, anddatetime). - You can also install extra modules (called packages) with tools like
pip.
Example:
# math_tools.py
def add(a, b):
return a + b
Here, math_tools.py is a module that defines one function.
Importing a Module
To use code from another module, you use the import statement.
Import the whole module
import math
print(math.sqrt(16)) # Output: 4.0
Import a specific function or class
from math import sqrt
print(sqrt(25)) # Output: 5.0
Give a module an alias (nickname)
import math as m
print(m.pi) # Output: 3.141592653589793
Your Own Modules
If you have math_tools.py in the same folder as your main program, you can import it:
import math_tools
result = math_tools.add(3, 4)
print(result) # Output: 7
Why Are Imports Useful?
- They keep code organized and split into logical pieces.
- They allow you to reuse code instead of copying it everywhere.
- They give access to Python’s standard library and third-party libraries like
requests,numpy, or the Azure SDKs.
Quick Recap
- A module is just a Python file with reusable code.
- Use
importto bring in a module. - You can import everything, just what you need, or rename it with an alias.
👉 Next Step: Try creating your own small module with a function or two, then import it into another Python file. That’s the best way to understand how modules and imports work.