By the end of this lesson
Import a function and use a main guard.
Before you start
- Python 3.12 or a compatible newer Python 3 interpreter; no external packages.
- Complete lesson 13 in this route, or be comfortable with its examples.
Three words to know
- Module
- A Python source file that can be imported.
- Import
- Loading a module so its names can be used.
- Entry point
- The part of a program called when it is run directly.
1. Put one reusable rule in a module
Save this file as totals.py in your practice folder. A file’s module name usually omits .py. Do not name a practice file json.py, csv.py or unittest.py: it can shadow the standard-library module of the same name.
def total_pages(sizes):
return sum(sizes)
2. Import from the same folder
Save the next file as lesson.py alongside totals.py and run lesson.py. When a file is imported, its top-level statements execute. The main guard prevents this program’s command-line action from running merely because another file imports it.
from totals import total_pages
def main():
print(total_pages([2, 3, 1]))
if __name__ == "__main__":
main()
What you should see · example output
6
3. Imports are not installations
The standard library ships with Python. A local module is found through Python’s import search path. Third-party packages need a separate installation step, ideally in a virtual environment. An import failure can mean a wrong folder, wrong interpreter or missing dependency; it does not always mean you should install something.
YOUR TURN
A small check before you continue
If you import lesson from another script, should main print the total automatically? Why?
Show a suggested answer
No. During import its __name__ is lesson, not __main__, so the guard does not call main. The imported functions remain available.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
