When programs grow bigger, writing everything in a single file can become messy and hard to manage. Multiple functions, classes, and static variables can make code confusing, difficult to read, and hard to reuse.
Python provides modules and packages to help organize code in a clean, reusable way.
Read: Python OOPs Concept
What is Python Modules and Packages?
Module: A module is simply a single Python file (.py) that contains functions, classes, variables, or runnable code.
Example: mymath.py
#mymath.py
def add(x1, x2):
return x1+x2
def multiply(x1, x2):
return x1*x2Now we can use this module or file in another file using import keyword.
import mymath
print(mymath.add(5, 6))
print()
print(mymath.multiply(9, 3)You can also give a aliases (nick name) name to the moudle like: import mymath as mt and access using the nick name: print(mt.add(5, 6))
from mymath import add
print(add(2, 3))
Package: A package is a folder containing multiple modules, along with a special __init__.py file. Packages help organize modules into a directory structure. This allows large projects to remain clean and modular.
Example:
Myfolder
__init__.py
mymath.py
mycode.py
Note: __init__.py can be empty or contain initialization code. It tells Python that this folder should be treated as a package
Using a module from Package
from Myfolder import mymath
print(mymath.add(20, 30))
print()
print(mymath.multiply(10, 10)) Python built-in Module
import math
print(math.sqrt(25))
print()
print(math.pi)
import random
print(random.randint(1, 5)
Tasks:
- Create a module with a function to find square of a number.
- Import that module in another file and use it.
- Create a package with two modules.
- Use
mathmodule to calculate square root.
Mini Project: Generate Random Password
import random
import string
def gen_password(length):
new = (string.ascii_letters + string.digits)
password = "".join(random.choice(new) for i in range(length))
return(password)
# in place of "i" we can also use "_" because we don't need this value
# this is just a placeholder
print(gen_password(7))