Site icon CBSECS

modules-libraries-in-python-class-12

Library and Modules


What is Python Library?

A Python library is a collection of pre-written code (modules and packages) that provides useful functionality so you don’t have to write everything from scratch.

Think of it as a toolbox: instead of reinventing the wheel, you can use ready-made tools that solve common problems.


Key Characteristics


Types of Libraries

What is Module?

A module is just a Python file (.py) that contains code like functions, variables, or classes.
Think of it like a chapter in a book – instead of writing the whole book in one place, we break it into chapters.


📖 Example

Suppose you write a file called mymath.py:

# mymath.py
def add(a, b):
    return a + b

def square(x):
    return x * x

This file is a module named mymath.


🔹 How to Use It?

In another program, you can import and use it:

import mymath

print(mymath.add(5, 3))     # Output: 8
print(mymath.square(4))     # Output: 16

So instead of writing the same add and square functions again, you just use the module.


✅ Why Modules are Useful?

  1. Reusability → You can use the same code in many programs.
  2. Organization → Breaks large programs into small, manageable parts.
  3. Less Work → Python already provides many modules (like math, random, datetime) that you can use directly.

📌 Simple Example with Built-in Module

import math

print(math.sqrt(16))   # 4.0
print(math.factorial(5)) # 120

Here, math is a built-in module in Python.


👉 In short:
A module = a Python file with code that we can use in other programs. It saves time, reduces mistakes, and keeps programs neat.


Exit mobile version