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 page
Creating and Importing a ModuleAs 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."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"))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"))Output
Hello, Bob! Welcome to Python.
Or use an alias:
import helper as h
print(h.greet("Ada"))Output
Hello, Ada! Welcome to Python.