Modules help organize code by splitting it into separate files. They make programs easier to manage and allow code reuse.
What is a module?
A module is a Python file (.py) containing functions, variables, or classes.
For example, create a file named math_utils.py:
def add(a, b):
return a + b
def multiply(a, b):
return a * b
pi = 3.14159
This file is now a module.
Importing modules
Use import to load a module.
import math_utils
result = math_utils.add(5, 3)
print(result) # 8
print(math_utils.pi) # 3.14159
Import specific items:
from math_utils import add, pi
print(add(10, 20)) # 30
print(pi) # 3.14159
Import everything (not recommended for large modules):
from math_utils import *
print(multiply(4, 5)) # 20
Using built-in modules
Python has many built-in modules.
Random module:
import random
print(random.randint(1, 10)) # Random number between 1 and 10
print(random.choice(["apple", "banana", "cherry"])) # Random item
Math module:
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
Aliasing for shorter names
Give a module a shorter name with as:
import random as rnd
print(rnd.randint(1, 100))
Simple examples
Create a greeting module greet.py:
def hello(name):
return f"Hello, {name}!"
def goodbye(name):
return f"Goodbye, {name}!"
Use it in main file:
from greet import hello, goodbye
print(hello("Alex"))
print(goodbye("Sam"))
Important notes
- The module file must be in the same folder or in Python's path.
- Use descriptive module names (lowercase, underscores).
- Avoid
from module import *in larger programs (can cause name conflicts). - Modules are loaded only once per program run.
Quick summary
- Modules are separate
.pyfiles with reusable code. - Import with
import moduleorfrom module import item. - Use
asfor aliases. - Built-in modules like
randomandmathprovide extra functionality. - Organize code into modules for better structure.
Practice creating and importing small modules. They are essential for building larger Python programs.
Top comments (0)