Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 6 · Introduction to Modules

Introduction to Modules

Functions organise a task within a program. Modules extend that organisation across files, allowing related definitions to be kept together and used elsewhere.

On this pageCreating and Importing a Module

As programs grow, it becomes inefficient to keep all the code in one file. Python solves this with modules—separate files that organize reusable code. A module can contain functions, variables, and even entire classes, making your projects cleaner and easier to manage.

Some modules come with Python’s standard library, such as math and datetime; others are files you write or packages you install. Once imported, the functions inside a module can be used anywhere in your program.

Creating and Importing a Module

You can create your own module by saving a Python file (for example,helper.py) with some functions inside it.

# helper.py
def greet(name):
    return f"Hello, {name}! Welcome to Python."
Listing 239 — Creating and Importing a Module

Save the first listing as helper.py. Put the following code in main.py in the same folder and run main.py; the file named helper.py supplies the imported module:

import helper
print(helper.greet("Alice"))
Listing 240 — Creating and Importing a Module

Output

Hello, Alice! Welcome to Python.

This example is deterministic: the same name produces the same greeting.

You can also import specific items:

from helper import greet
print(greet("Bob"))
Listing 241 — Creating and Importing a Module

Output

Hello, Bob! Welcome to Python.

Or use an alias:

import helper as h
print(h.greet("Ada"))
Listing 242 — Creating and Importing a Module

Output

Hello, Ada! Welcome to Python.