Lesson 13: Modules and Packages in Python

๐ŸŽฏ Lesson Objective

To learn how to use and organize code with modules and packages, making programs modular, reusable, and easier to maintain.


๐Ÿงฉ 1. What Is a Module?

A module is a Python file (.py) containing functions, variables, and classes that can be imported into other programs.

โœ… Example: Using the math module

import math

print(math.sqrt(16))   # Square root
print(math.factorial(5))  # Factorial

Output:

4.0
120

โš™๏ธ 2. Creating Your Own Module

  1. Create a file mymodule.py:
def greet(name):
    print(f"Hello, {name}!")

pi = 3.14159
  1. Use it in another program:
import mymodule

mymodule.greet("Sameer")
print("Value of pi:", mymodule.pi)

Output:

Hello, Sameer!
Value of pi: 3.14159

๐Ÿ”„ 3. Importing Specific Functions

from math import sqrt, factorial

print(sqrt(25))
print(factorial(4))

โœ… Output:

5.0
24

๐Ÿงฐ 4. Using Aliases

import math as m

print(m.sqrt(36))
print(m.factorial(6))

Output:

6.0
720

๐Ÿงฑ 5. What Is a Package?

A package is a collection of Python modules organized in directories with an __init__.py file.
It helps structure large projects into multiple modules.

Example Structure:

my_package/
    __init__.py
    module1.py
    module2.py

Using a module from a package:

from my_package import module1
module1.function_name()

๐Ÿ”„ 6. Standard Library Modules

Python comes with many built-in modules:

ModuleDescription
osOperating system interaction
sysSystem-specific parameters
mathMathematical functions
randomRandom number generation
datetimeDate and time handling
jsonJSON data handling
csvCSV file operations

โœ… Example: Random number

import random
print(random.randint(1, 100))  # Random integer between 1 and 100

๐Ÿ› ๏ธ 7. Installing External Modules

Use pip to install external modules:

pip install requests

โœ… Example: Using requests module

import requests

response = requests.get("https://api.github.com")
print(response.status_code)

๐ŸŒ 8. Real-Life Example โ€“ Organizing Code

Create a package calculator:

calculator/
    __init__.py
    operations.py

operations.py:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

Use in another file:

from calculator import operations

print(operations.add(10, 5))
print(operations.subtract(10, 5))

Output:

15
5

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *