Skip to content

Creating Your Own Modules

Creating your own modules in Python is an excellent way to organize, reuse, and share your code. A module is simply a .py file that contains functions, classes, or variables that you can import and use in other programs.


  • Organization: Divides your project into smaller, more manageable files.
  • Reuse: Uses the same code in different programs without copying and pasting.
  • Maintenance: Makes it easier to update and fix errors in one place.

  1. Create a .py file For example, create a file called greetings.py with the following content:
greetings.py
def greet(name):
print(f'Hello, {name}!')
  1. Import your module into another file Now, in your main file, you can import and use the function:
Using a Custom Module
import greetings
greetings.greet('Ana')

Output:

Hello, Ana!

You can also import only what you need from your module:

Importing a Specific Function
from greetings import greet
greet('Carlos')

For Python to find your module, it must be in the same directory as your main file or in a folder included in the PYTHONPATH.


  • Use descriptive names for your modules and functions.
  • Avoid spaces and special characters in file names.
  • Keep each module focused on a single task or theme.

  • Creating modules helps you organize and reuse your code.
  • You only need a .py file to get started.
  • Import your modules and functions as needed in your projects.

Ready to practice? Create a module with your own functions and test it in a new program.