A module in Python is a single file (with a .py extension) that contains Python definitions and statements, such as functions, classes, and variables. Modules allow you to organize related code into separate files logically.
Creating and Importing a Module
To create a module, you simply write some Python code in a file with the .py
extension. For example, let’s create a module named math_operations.py
with a few functions:
# calculation.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Importing the Module
You can use import
to bring the module into another file, making its functions available to use:
import calculation
result = calculation.add(5, 4)
print(result) # Output: 9
Importing Specific Functions or Variables
You can also import specific functions or variables from a module:
from calculation import add
result = add(10, 7)
print(result) # Output: 17
Using Aliases
You can use as
to create an alias for a module or function:
import calculation as ca
result = ca.subtract(10, 5)
print(result) # Output: 5
Standard Library Modules
Python’s standard library provides a wide range of built-in modules, such as math
, datetime
, and random
. You can import and use these without additional setup.
import math
print(math.sqrt(25)) # Output: 5.0