Chapter 4 — Using Python Libraries
4.1 Introduction
Python’s strength lies not only in its simplicity but also in its rich collection of libraries and
modules. A library in Python is a set of ready-made code that performs common tasks, so
programmers don’t need to write every piece of logic from scratch.
For instance, if you need to calculate a square root, Python already provides it through the math
library — no need to manually implement the algorithm.
Example:
import math
print([Link](16)) # Output: 4.0
This simple example demonstrates the power of libraries: they make programming faster, more
accurate, and highly efficient.
4.2 What is a Library?
A Python library is a collection of modules — and each module is a Python file containing
definitions, functions, and variables that can be reused.
Think of a library as a toolbox, where each tool (module) performs a specific function.
For example:
The math module handles mathematical operations.
The random module helps generate random numbers.
The datetime module works with dates and times.
When we import these modules, we’re essentially pulling out the tools we need from Python’s
huge toolbox.
Types of Libraries
1. Built-in (Standard) Libraries
Pre-installed with Python (no need to install).
Examples: math, os, sys, random, datetime
2. User-defined Libraries
Created by the programmer for custom functionality.
Example: A personal module named [Link]
3. Third-party Libraries
Created by the community; need to be installed via pip.
Examples: numpy, pandas, matplotlib, flask, requests
4.3 Importing Modules in a Python Program
Before using any module, it must be imported using the import statement.
Let’s understand how using our own sequence of connected examples.
Example 1 — Using Built-in Libraries Together
Imagine you want to build a small program that:
1. Generates a random number.
2. Calculates its square root.
3. Prints the result with today’s date.
import random
import math
import datetime
num = [Link](1, 100)
result = [Link](num)
print("The square root of", num, "is", result)
print("Calculated on:", [Link]())
Here we used three standard libraries together — random, math, and datetime — showing
how multiple modules can work in harmony.
Different Ways to Import
1. Import entire module:
2. import math
3. print([Link](49))
4. Import specific items:
5. from math import sqrt, pi
6. print(sqrt(64))
7. print(pi)
8. Import with alias:
9. import random as r
10. print([Link](1, 10))
11. Import all items (not recommended):
12. from math import *
13. print(floor(4.7))
4.4 Using Python Standard Library’s Functions and
Modules
The Python Standard Library (PSL) comes pre-installed and provides hundreds of modules for
almost every kind of task.
We’ll continue our interconnected example to show how these libraries can work together in one
small program.
Example: A Mini Program Using Multiple Libraries
import math
import random
import datetime
import os
# 1. Generate a random number
num = [Link](10, 100)
# 2. Perform a mathematical operation
sq_root = [Link](num)
# 3. Display result with current date
print("Random Number:", num)
print("Square Root:", sq_root)
print("Date:", [Link]())
# 4. Create a folder to store results
[Link]("Results")
print("Folder 'Results' created successfully!")
Now, this single example demonstrates:
Random number generation (random)
Mathematical calculation (math)
Date usage (datetime)
File handling (os)
That’s the true beauty of Python libraries — integration and reusability.
4.5 Creating a Python Library
Sometimes, the built-in modules aren’t enough. You might want to create your own module
containing frequently used functions.
Let’s continue our flow and create a custom library that calculates both the area and perimeter
of shapes.
Step 1: Create a Module
Create a file named [Link].
# [Link]
def area_square(side):
return side * side
def perimeter_square(side):
return 4 * side
def area_circle(radius):
import math
return [Link] * radius * radius
Step 2: Use the Custom Library in Another Program
# main_program.py
import geometry
side = 5
radius = 3
print("Area of square:", geometry.area_square(side))
print("Perimeter of square:", geometry.perimeter_square(side))
print("Area of circle:", geometry.area_circle(radius))
Output:
Area of square: 25
Perimeter of square: 20
Area of circle: 28.274333882308138
Now, you have your own user-defined library ([Link]) that you can reuse in any future
program.
Advantages of Creating Libraries
Encourages code reusability
Promotes modular programming
Makes maintenance easier
Keeps projects organized
4.6 Understanding Packages in Python
As your projects grow larger, you might end up with many modules. Managing dozens of .py
files separately can become difficult.
To solve this, Python introduces packages.
A package is simply a folder containing multiple related modules and a special file named
__init__.py.
The __init__.py file tells Python that the folder should be treated as a package.
Example: Building a Package from Our Custom Modules
Let’s expand our geometry example.
Suppose we want to organize multiple modules — one for shapes and another for utilities —
inside a single package named mymath.
mymath/
│
├── __init__.py
├── [Link]
└── [Link]
[Link]
def area_square(side):
return side * side
def area_circle(radius):
import math
return [Link] * radius * radius
[Link]
def add(a, b):
return a + b
def multiply(a, b):
return a * b
[Link]
# This file makes 'mymath' a package
Now, in your main program:
from mymath import geometry, operations
print(geometry.area_circle(5))
print([Link](10, 20))
This structure allows you to organize large projects into logical groups (packages) instead of a
single cluttered file.
4.7 Key Differences between Modules and Packages
Basis Module Package
A single file containing Python code A collection (directory) of related
Definition
(functions, variables, classes). modules organized together.
A folder containing an __init__.py file
File Type A .py file.
and multiple .py modules.
mymath folder containing [Link]
Example [Link]
and [Link]
Used to group related functions and Used to organize multiple modules into a
Purpose
code. logical hierarchy.
Import import geometry from mymath import geometry
Syntax
Scale Smaller unit of code organization. Larger unit (can contain many modules).
4.8 Summary
A module is a single Python file that can be imported and reused.
A package is a directory containing multiple modules and an __init__.py file.
The Python Standard Library offers pre-written modules for everyday programming
needs.
You can create your own modules and packages to make your programs modular,
readable, and maintainable.
Libraries, modules, and packages together make Python one of the most powerful and
flexible programming languages in the world.