12. Python Libraries

Python libraries provide ready-made functions and modules that help perform tasks easily.

Python includes many built-in libraries called:

Standard Libraries

These libraries come pre-installed with Python.


Standard Libraries in Python

Some commonly used standard libraries are:

  • math
  • random
  • datetime
  • os
  • sys
  • collections

1. math Module

The math module provides mathematical functions.


Importing math

import math

Common Math Functions

FunctionDescription
sqrt()Square root
pow()Power
ceil()Round up
floor()Round down
factorial()Factorial
piValue of π

Example: Square Root

import math

print(math.sqrt(25))

Output:

5.0

Example: Power

print(math.pow(2, 3))

Output:

8.0

Example: Ceiling and Floor

print(math.ceil(4.2))
print(math.floor(4.8))

Output:

5
4

Example: Factorial

print(math.factorial(5))

Output:

120

Example: Value of Pi

print(math.pi)

2. random Module

The random module generates random values.


Importing random

import random

Random Integer

print(random.randint(1, 10))

Returns random number between 1 and 10.


Random Float

print(random.random())

Returns float between 0 and 1.


Random Choice

fruits = ["Apple", "Banana", "Mango"]

print(random.choice(fruits))

Shuffle List

numbers = [1, 2, 3, 4, 5]

random.shuffle(numbers)

print(numbers)

Generate OTP

otp = random.randint(1000, 9999)

print("OTP:", otp)

3. datetime Module

Used for date and time operations.


Importing datetime

from datetime import datetime

Current Date and Time

now = datetime.now()

print(now)

Current Date Only

print(now.date())

Current Time Only

print(now.time())

Formatting Date

print(now.strftime("%d-%m-%Y"))

Output Example:

25-05-2026

Common Date Formats

FormatMeaning
%dDay
%mMonth
%YYear
%HHour
%MMinute
%SSecond

Create Custom Date

from datetime import datetime

date = datetime(2026, 5, 25)

print(date)

Date Difference

from datetime import datetime

d1 = datetime(2026, 1, 1)
d2 = datetime(2026, 5, 25)

difference = d2 - d1

print(difference.days)

4. os Module

Used for interacting with operating system.


Importing os

import os

Current Working Directory

print(os.getcwd())

List Files and Folders

print(os.listdir())

Create Directory

os.mkdir("new_folder")

Remove Directory

os.rmdir("new_folder")

Rename File

os.rename("old.txt", "new.txt")

Check File Exists

print(os.path.exists("data.txt"))

Join File Paths

path = os.path.join("folder", "file.txt")

print(path)

Environment Variables

print(os.environ)

5. sys Module

Provides system-specific functions.


Importing sys

import sys

Python Version

print(sys.version)

Command Line Arguments

print(sys.argv)

Exit Program

sys.exit()

System Path

print(sys.path)

Memory Size

x = [1, 2, 3]

print(sys.getsizeof(x))

6. collections Module

Provides advanced container datatypes.


Importing collections

from collections import Counter

Counter

Counts occurrences.

from collections import Counter

data = ["apple", "banana", "apple"]

count = Counter(data)

print(count)

Output:

Counter({'apple': 2, 'banana': 1})

defaultdict

Provides default values.

from collections import defaultdict

data = defaultdict(int)

data["a"] += 1

print(data["a"])

deque

Fast insertion/removal from both ends.

from collections import deque

dq = deque([1, 2, 3])

dq.appendleft(0)

print(dq)

namedtuple

Tuple with named fields.

from collections import namedtuple

Student = namedtuple("Student", ["name", "age"])

s = Student("Aditya", 25)

print(s.name)
print(s.age)

Practical Example

Dice Simulator

import random

while True:

input("Press Enter to roll dice")

print("Dice:", random.randint(1, 6))

choice = input("Roll again? (y/n): ")

if choice.lower() != "y":
break

Advantages of Standard Libraries

✅ Save development time
✅ Ready-made functions
✅ Reliable and optimized
✅ Cross-platform support
✅ Easy to use