Python Modules
A module is a Python file that holds ready code. A program brings a module in with import.
A module is one file
This file is a module. Its name is helpers.
# helpers.py
def greet(name):
return "Hello, " + name
def double(number):
return number * 2Import and use the dot
Import the file by its name. Then use a dot to reach inside it.
import helpers
print(helpers.greet("Ada"))
print(helpers.double(21))Bring one name in directly
Now you can use the name on its own. You do not need the dot.
from helpers import greet
print(greet("Bo"))Give a module a short name
A short name saves typing. The module works the same way.
import helpers as h
print(h.double(8))Example
# helpers.py
def add_tax(price):
return price * 1.2
def greet(name):
return "Hello, " + name
# main.py
import helpers
print(helpers.greet("Ada"))
print(helpers.add_tax(50))Key points
- Module: a Python file that holds ready code
- Use import to bring a module into your program
- Use module.name to use a name inside a module
- Use from module import name to bring one name in directly
- Use import module as short to give a module a short name
In this example, helpers.py holds two functions. One function greets a person by name. One function adds tax to a price. The main.py file sits in the same folder. It imports helpers and calls both functions with a dot. The greeting prints first. Then the price with tax prints as 60.0.
Note
The module name is the file name without .py.
A file called helpers.py is imported as helpers.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does import helpers as h do?