Library and Packages in Python -Introduction

Here’s a simple explanation of Libraries and Packages in Python โ€” with examples, usage, and practice questions


๐Ÿ“š What is a Library in Python?

  • A library is a collection of useful code (functions, classes, modules).
  • It helps you do things quickly, without writing code from scratch.
  • Python has many libraries for math, data, web, AI, etc.

๐Ÿ”น Examples of Libraries:

LibraryUse Case
mathMathematics (sqrt, sin)
randomRandom numbers
datetimeDates and time
osOperating system tasks
numpyNumbers, arrays
pandasData analysis
matplotlibDrawing graphs/plots
requestsWeb API calls

๐Ÿ“ฆ What is a Package?

  • A package is a folder that contains modules (Python files) and a special file called __init__.py.
  • Packages help to organize libraries better.
  • You can think of:
    • Library = a toolset
    • Package = toolbox with organized tools (modules)

โœ… Example: Using a Library

1. Math Library:

import math
print(math.pi)         # 3.1415...
print(math.sqrt(25))   # 5.0

2. Random Library:

import random
print(random.randint(1, 10))  # Random number between 1 and 10


โœ… Using an External Library

  • Some libraries are not built-in. You need to install them using pip:
pip install pandas

Then use it:

import pandas as pd
data = pd.Series([1, 2, 3])
print(data)


โœ… Example: Package Structure

Imagine this folder:

mypackage/
    __init__.py
    add.py
    sub.py

add.py

def add(x, y):
    return x + y

sub.py

def sub(x, y):
    return x - y

Use the Package:

from mypackage import add, sub
print(add.add(3, 2))
print(sub.sub(5, 2))


๐Ÿ“ Practice Questions + Answers


โ“ Q1: What is the difference between a module and a library?

โœ… Answer:

  • A module is one Python file (.py) with code.
  • A library is a collection of modules.
  • A package is a folder containing modules.

โ“ Q2: Use the random library to generate a number between 100 and 200.

โœ… Code:

import random
print(random.randint(100, 200))


โ“ Q3: Install and use the numpy library to create a number array.

โœ… Code:

pip install numpy

โœ… Python:

import numpy as np
arr = np.array([10, 20, 30])
print(arr)


โ“ Q4: What is the role of __init__.py in a package?

โœ… Answer:

  • It tells Python that the folder is a package.
  • It can be empty or contain startup code.

โ“ Q5: Create your own library with a function to find the square of a number.

โœ… Create mylib.py:

def square(n):
    return n * n

โœ… Use it:

import mylib
print(mylib.square(6))  # Output: 36


๐Ÿ”„ Summary Table

TermMeaning
ModuleSingle .py file
LibraryCollection of modules (ready-to-use code)
PackageFolder of modules with __init__.py
pipPython package installer

Comments

Leave a Reply

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