Programming fundamentals · Beginner · 18 min
Split Python code into modules and import them
By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)
You will turn one growing Python script into a main script, a converters module and a small package, import them three different ways, and know how Python finds each one.
On this page
Every script starts small. Then you add a helper function, then another, and one day the file is a long scroll where the code that does the real work sits under a pile of helpers. A module fixes that. In Python, a module is any .py file: put functions in one file and use them from another with import. A folder of modules is a package.
In this tutorial you start with one script that prints a road trip summary: distance, temperature, fuel needed and fuel cost. You move its helpers out in stages, and after every move you check that the output has not changed by a single character. Along the way you meet import, from ... import, aliases, what if __name__ == "__main__": is for, how Python decides where to look for a module, and why a file called random.py can break your program.
You end with a project of a main script, one module and one package that runs with python3 trip.py. Nothing is downloaded, so it costs no mobile data.
The commands use python3. On Windows outside WSL, type py instead, and create the files in your editor where a command uses cat > file <<'PY'.
Step 1 · Write the single-file script and save its output
Make a folder for the project and write the script that you will split up:
mkdir -p ~/modules-demo
cd ~/modules-demo
cat > trip.py <<'PY'
# trip.py: a road trip summary, all in one file.
def km_to_miles(km):
return km * 0.621371
def c_to_f(celsius):
return celsius * 9 / 5 + 32
def litres_needed(km, km_per_litre):
return km / km_per_litre
def money(amount, currency):
return f"{currency} {amount:,.2f}"
def line(label, value):
return f"{label:<14}{value}"
distance_km = 312
temperature_c = 31
km_per_litre = 14
fuel_price = 1150 # price of one litre, in your currency
currency = "NGN"
litres = litres_needed(distance_km, km_per_litre)
print(line("Distance", f"{distance_km} km ({km_to_miles(distance_km):.1f} miles)"))
print(line("Temperature", f"{temperature_c} C ({c_to_f(temperature_c):.1f} F)"))
print(line("Fuel", f"{litres:.1f} litres"))
print(line("Fuel cost", money(litres * fuel_price, currency)))
PY
python3 trip.py
python3 trip.py > before.txtThe first three functions convert units. money formats an amount with a thousands separator and two decimals (:,.2f), and line pads the label to 14 characters (:<14) so the values line up. Change currency and fuel_price to your own if you like, for example "KES", "ZAR" or "GBP", but do it now, before the next command saves the output.
The last command sends the output into before.txt instead of the screen. That file is your reference: after each change you compare the new output with it.
Check it worked
The script prints four aligned lines:
Distance 312 km (193.9 miles)
Temperature 31 C (87.8 F)
Fuel 22.3 litres
Fuel cost NGN 25,628.57cat before.txt shows the same four lines.
Step 2 · Move the converters into their own module
The three conversion functions belong together and have nothing to do with printing. Put them in a new file, converters.py:
cd ~/modules-demo
cat > converters.py <<'PY'
"""Unit conversions for trip planning."""
def km_to_miles(km):
return km * 0.621371
def c_to_f(celsius):
return celsius * 9 / 5 + 32
def litres_needed(km, km_per_litre):
return km / km_per_litre
PYNow rewrite trip.py without those functions. It imports the module instead:
cd ~/modules-demo
cat > trip.py <<'PY'
# trip.py: a road trip summary that uses the converters module.
import converters
def money(amount, currency):
return f"{currency} {amount:,.2f}"
def line(label, value):
return f"{label:<14}{value}"
distance_km = 312
temperature_c = 31
km_per_litre = 14
fuel_price = 1150 # price of one litre, in your currency
currency = "NGN"
litres = converters.litres_needed(distance_km, km_per_litre)
print(line("Distance", f"{distance_km} km ({converters.km_to_miles(distance_km):.1f} miles)"))
print(line("Temperature", f"{temperature_c} C ({converters.c_to_f(temperature_c):.1f} F)"))
print(line("Fuel", f"{litres:.1f} litres"))
print(line("Fuel cost", money(litres * fuel_price, currency)))
PY
python3 trip.py > after.txt
diff before.txt after.txt && echo "same output"
lsIf you changed the currency or price in the first step, make the same change here.
import converters finds the file converters.py, runs it once from top to bottom, and gives you a name, converters, that holds everything the file defined. You reach a function through that name with a dot: converters.km_to_miles. The module name is the file name without .py, which is why module file names must be valid Python names: converters.py works, unit-converters.py cannot be imported, because - means minus.
The text in triple quotes at the top of converters.py is a docstring. It describes the module, and Python shows it if you type help(converters) in the REPL.
diff compares two files line by line. It prints nothing and succeeds when they match, so && echo "same output" only runs when nothing changed.
Check it worked
The terminal prints same output. ls lists a new folder, __pycache__, next to before.txt, after.txt, converters.py and trip.py. Python saves a compiled copy of each module it imports there, so the next import is faster. You never edit it, and you can delete it at any time; Python rebuilds it.
Step 3 · Try the three ways to import
import converters is one form. Two others change the names you type. Try all of them in a scratch file:
cd ~/modules-demo
cat > try_imports.py <<'PY'
import converters
from converters import c_to_f
import converters as conv
from converters import km_to_miles as to_miles
print(round(converters.km_to_miles(10), 2))
print(c_to_f(100))
print(conv.litres_needed(140, 14))
print(round(to_miles(42.195), 1))
PY
python3 try_imports.pyLine by line:
import convertersgives you the module name. Every use says where the function comes from:converters.km_to_miles.from converters import c_to_fcopies one name from the module into your file, so you callc_to_f(...)with no prefix. Shorter, but a reader has to scroll to the top to find wherec_to_fcame from.import converters as convimports the module under a shorter name, an alias. You will see this in other people's code for long names, such asimport numpy as np.from converters import km_to_miles as to_milescopies one name and renames it, which helps when two modules use the same function name.
Python runs a module's file only once per program, however many times you import it. The second, third and fourth imports reuse the module that the first one loaded.
Check it worked
The output is four lines: 6.21, 212.0, 10.0 and 26.2 (a marathon in miles). Try python3 -c "from converters import c_to_f; print(converters)" and you get NameError: name 'converters' is not defined: from ... import brings in only the names you list, not the module name itself.
Step 4 · See what if __name__ == "__main__" does
When Python runs a file, it sets a variable called __name__ in it. In the file you started with python3 <file>, the value is "__main__". In a file that was imported, it is the module name. Add a line that prints it to converters.py and run the file both ways:
cd ~/modules-demo
cat > converters.py <<'PY'
"""Unit conversions for trip planning."""
def km_to_miles(km):
return km * 0.621371
def c_to_f(celsius):
return celsius * 9 / 5 + 32
def litres_needed(km, km_per_litre):
return km / km_per_litre
print("converters.py is running, __name__ is", __name__)
PY
python3 converters.py
python3 trip.pyRun directly, the file prints __name__ is __main__. Run through trip.py, it prints __name__ is converters before the trip summary, which is a problem: any code at the top level of a module runs when it is imported, and that stray line now pollutes the output of every program that uses the module.
The fix is to put code that should only run when the file is started directly under if __name__ == "__main__":. A good use for that block is a quick self-check of the module's own functions:
cd ~/modules-demo
cat > converters.py <<'PY'
"""Unit conversions for trip planning."""
def km_to_miles(km):
return km * 0.621371
def c_to_f(celsius):
return celsius * 9 / 5 + 32
def litres_needed(km, km_per_litre):
return km / km_per_litre
if __name__ == "__main__":
assert round(km_to_miles(100), 2) == 62.14
assert c_to_f(0) == 32
assert litres_needed(140, 14) == 10
print("converters: all checks passed")
PY
python3 converters.py
python3 trip.py > after.txt
diff before.txt after.txt && echo "same output"assert stops the program with an AssertionError if its condition is false, so the message on the last line only prints when every check holds.
Check it worked
python3 converters.py prints converters: all checks passed. Running trip.py prints only same output: the self-check did not run on import.
Step 5 · Make a package for the formatting helpers
money and line format text for the screen. Put them in a package: a folder that holds modules, with a file called __init__.py that Python runs when the package is first imported.
cd ~/modules-demo
mkdir -p report
cat > report/formatting.py <<'PY'
"""Helpers that format values for printing."""
def money(amount, currency):
return f"{currency} {amount:,.2f}"
def line(label, value):
return f"{label:<14}{value}"
PY
cat > report/__init__.py <<'PY'
"""Formatting for the trip summary."""
from .formatting import line, money
PY
ls reportYou could import from the inner module directly with from report.formatting import money: the dot in an import walks into the folder. The line in __init__.py saves that typing. from .formatting import ... is a relative import: the leading dot means "the formatting module in this same package". Because __init__.py imports line and money, they become available as report.line and report.money, so the rest of your code does not need to know which file inside the package holds them.
Check it worked
ls report lists __init__.py and formatting.py. Check that both import paths work:
cd ~/modules-demo
python3 -c "from report.formatting import money; print(money(1500, 'KES'))"
python3 -c "import report; print(report.line('Label', 'value'))"The first prints KES 1,500.00, the second Label value.
Step 6 · Finish the main script
Now trip.py only needs to hold the trip itself. Rewrite it to import from both places, and put the work in a main() function under the same __name__ check, so another file could import trip without printing a summary:
cd ~/modules-demo
cat > trip.py <<'PY'
# trip.py: the main script. It holds the trip details and prints the summary.
import converters as conv
from report import line, money
def main():
distance_km = 312
temperature_c = 31
km_per_litre = 14
fuel_price = 1150 # price of one litre, in your currency
currency = "NGN"
litres = conv.litres_needed(distance_km, km_per_litre)
print(line("Distance", f"{distance_km} km ({conv.km_to_miles(distance_km):.1f} miles)"))
print(line("Temperature", f"{temperature_c} C ({conv.c_to_f(temperature_c):.1f} F)"))
print(line("Fuel", f"{litres:.1f} litres"))
print(line("Fuel cost", money(litres * fuel_price, currency)))
if __name__ == "__main__":
main()
PY
rm try_imports.py
python3 trip.py
python3 trip.py > after.txt
diff before.txt after.txt && echo "same output"The two styles are on purpose. conv. in front of each conversion tells a reader where the maths comes from, and line and money are used so often that a prefix would be noise. Choose per module; there is no single right answer.
Check it worked
python3 trip.py prints the same four lines as in the first step, and the comparison prints same output. Your project is now:
modules-demo/
├── trip.py the main script you run
├── converters.py a module
└── report/ a package
├── __init__.py
└── formatting.pyStep 7 · See where Python looks for modules
When you write import converters, Python looks through a list of folders, in order, and uses the first converters.py (or converters package folder) it finds. The list is sys.path. Print it, and ask two modules where they came from:
cd ~/modules-demo
cat > where.py <<'PY'
import json
import sys
import converters
print(sys.path[0])
print(converters.__file__)
print(json.__file__)
PY
python3 where.pyThe first entry in sys.path is the folder of the script you ran. The rest are folders inside your Python installation, which hold the standard library, and a site-packages folder for packages you install.
Because the first entry is the script's folder, not your current folder, trip.py still works from somewhere else. A bare python3 -c command has no script, so it searches the current folder instead:
cd ~
python3 ~/modules-demo/trip.py
python3 -c "import converters" || echo "import failed"The first command prints the summary. The second fails with ModuleNotFoundError: No module named 'converters', because your home folder has no converters.py.
The search order has a trap. The script's folder comes before the standard library, so a file of your own with the same name as a standard module hides the real one. Create a random.py and then try to use Python's random module:
cd ~/modules-demo
cat > random.py <<'PY'
print("this is my own random.py")
PY
python3 -c "import random; print(random.randint(1, 6))" || echo "import random broke"
rm random.py
python3 -c "import random; print(random.randint(1, 6))"With your file in place, Python imports it instead, prints this is my own random.py, and then fails with an AttributeError saying the module has no attribute randint. Recent Python versions add a hint, something like "consider renaming ... since it has the same name as the standard library module". After rm random.py, the same command prints a number from 1 to 6. The usual culprits are files named after what you are learning: random.py, json.py, math.py, email.py, statistics.py. Name your files after what they do instead, such as dice_game.py.
Check it worked
where.py prints three paths: your modules-demo folder, the path of converters.py in it, and a path to json/__init__.py inside your Python installation. You saw import failed from your home folder, import random broke while random.py existed, and a number after it was removed.
Step 8 · Use the standard library modules you already have
json, random and sys worked without installing anything because they are part of the standard library: a few hundred modules that come with every Python. You import them exactly like your own modules. Try two more:
cd ~/modules-demo
cat > stdlib_tour.py <<'PY'
import statistics
import sys
from datetime import date
fuel_prices = [1150, 1180, 1120]
print(statistics.mean(fuel_prices))
print(date(2026, 12, 1).strftime("%A"))
print("statistics" in sys.stdlib_module_names, "requests" in sys.stdlib_module_names)
PY
python3 stdlib_tour.pystatistics.mean averages a list. date(...).strftime("%A") gives the day of the week. sys.stdlib_module_names is the set of every standard library module name, so you can check whether a module ships with Python or has to be installed.
requests is not in it. Modules like that are third-party packages that you install with a tool such as pip or uv, ideally into a virtual environment for each project. That is covered in Python virtual environments and packages; once installed, you import them the same way.
Check it worked
The output is 1150, Tuesday, and True False: statistics ships with Python and requests does not.
When you have finished exploring, delete the demo folder:
cd ~
rm -rf ~/modules-demoNext steps
- Group data and the functions that work on it into one object: write your first class in Python. Classes usually live in modules like the ones you made here.
- Install third-party packages into a project of their own: Python virtual environments and packages.
- See the same idea in another language: use JavaScript modules with import and export.
- Revisit how functions take arguments and return values: write functions that return values.
Part of these paths
Related tutorials
- Write your first class in Python: objects, attributes and methodsYou will model a library book loan as a Python class with attributes, methods, a readable __repr__ and a shared loan period, compare it with a dictionary version, rewrite it as a dataclass and end with a Loan class and a short script that uses it.
- Use JavaScript modules with import and exportYou will split a Node.js bill-splitting script into three ES modules with named and default exports, load built-ins and code on demand, recognise CommonJS and its errors, and run the same modules in a browser.
- How to Use Virtual Environments and Install Packages in PythonYou will create an isolated Python 3.15 environment for a project, install a package into it with pip, record the exact versions, rebuild the environment from that record, and then manage the same project with uv.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials