Python Basics: Your First Steps Into Programming
Python Modules
Lesson 11 of 16 • 10 XP
Keep your place in this quest
Log in or sign up for free to subscribe, follow lesson progress, and access more learning content.
In Python, a module is simply a file that contains code — functions, classes, or variables — that you can use in other programs.
Modules are one of Python’s most powerful features because they let you reuse code instead of rewriting it from scratch each time.
Think of a module as a toolbox: once you’ve built it, you can bring it into any project and use its tools whenever you need.
Why Use Modules?
Imagine you’ve written a function that you use in multiple programs.
Without modules, you’d have to copy and paste that function into every file — which is messy and hard to maintain.
With modules, you:
• Keep your code organized.
• Avoid duplication.
• Make updates in one place and have them reflected everywhere.
Creating a Module
Creating a module in Python is as easy as saving your code in a .py file.
Example — let’s create a file named mymodule.py:
def say_hello():
print("Hello, world!")
That’s it — mymodule.py is now a module.
Importing a Module
To use this function in another Python file, you import the module with the import keyword.
Example — in a different file:
import mymodule
mymodule.say_hello()
Output:
Hello, world!
Here’s what’s happening:
import mymoduleloads the code frommymodule.py.mymodule.say_hello()calls the function from that module.
TIP: The module file must be in the same folder as the script importing it, or be installed/available in Python’s search path.
Wrapping Up
Modules are your gateway to writing reusable, shareable code. They also open the door to Python’s massive standard library and third-party packages, which we’ll explore soon.
In the next lesson, we’ll talk about packages — a way to group multiple modules together into a larger, organized structure.