Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Module

Module

A module in Python is simply a file that contains Python code — like functions, classes, or variables — that you can reuse in other programs.

✅ It helps keep code organized, readable, and reusable

Example: Creating and Using a Module

1. Create a module (say in a file called mymath.py):

# mymath.py

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

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

2. Use this module in another file:

import mymath

print(mymath.add(5, 3))  # Output: 8
print(mymath.sub(5, 3))  # Output: 2

🧩 Built-in vs. User-defined Modules

TypeExampleDescription
Built-in Modulemath, randomComes with Python
User-definedmymath, helperCreated by you or other developers

🔹 Example: Using a Built-in Module

import math

print(math.sqrt(16))  # Output: 4.0
print(math.pi)        # Output: 3.141592653589793

📦 Importing Modules – Options:

SyntaxUsage
import module_nameImport full module
from module_name import funcImport specific function
import module_name as shortImport module with alias

✅ Example:

from math import sqrt
print(sqrt(25))  # Output: 5.0

import math as m
print(m.pi)      # Output: 3.14159...

🎯 Why Use Modules?

  • ✅ Reuse code
  • ✅ Organize large programs
  • ✅ Share code with others
  • ✅ Avoid repeating yourself (DRY principle)

✅ Summary

FeatureDescription
ModuleA file containing Python code
UseTo organize and reuse code
Examplesmath, random, your own files

    Leave a Reply

    Your email address will not be published.

    Need Help?