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:
Library | Use Case |
---|---|
math | Mathematics (sqrt, sin) |
random | Random numbers |
datetime | Dates and time |
os | Operating system tasks |
numpy | Numbers, arrays |
pandas | Data analysis |
matplotlib | Drawing graphs/plots |
requests | Web 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
Term | Meaning |
---|---|
Module | Single .py file |
Library | Collection of modules (ready-to-use code) |
Package | Folder of modules with __init__.py |
pip | Python package installer |
Leave a Reply