Lesson 15: Python Standard Libraries

🎯 Lesson Objective

To learn how to use Python’s standard libraries, which provide pre-built modules and functions for common tasks, making programming faster and easier.


🧩 1. What Are Standard Libraries?

Python comes with a rich set of built-in modules known as the standard library.
They cover areas like mathematics, file handling, data processing, networking, and more.

βœ… Example: Using the math module

import math

print(math.sqrt(25))  # Square root
print(math.factorial(5))  # Factorial
print(math.pi)  # Value of Pi

Output:

5.0
120
3.141592653589793

βš™οΈ 2. Commonly Used Standard Libraries

LibraryPurposeExample
mathMathematical operationsmath.sqrt(16)
randomGenerate random numbersrandom.randint(1,10)
datetimeHandle dates and timesdatetime.date.today()
osOperating system functionsos.listdir()
sysSystem-specific parameterssys.version
jsonJSON data handlingjson.dumps({"a":1})
csvCSV file handlingcsv.reader(file)
reRegular expressionsre.findall(r"\d+", "Age 25")

πŸ”„ 3. Using the random Module

import random

print(random.randint(1, 100))  # Random integer
print(random.choice(["apple", "banana", "cherry"]))  # Random element
print(random.shuffle([1, 2, 3, 4, 5]))  # Shuffle list

🧰 4. Using the datetime Module

import datetime

today = datetime.date.today()
now = datetime.datetime.now()

print("Today's Date:", today)
print("Current Time:", now)
print("Year:", now.year, "Month:", now.month, "Day:", now.day)

🧱 5. Using the os Module

import os

print("Current Directory:", os.getcwd())
print("Files in Directory:", os.listdir())
# Create a new folder
# os.mkdir("NewFolder")

πŸ› οΈ 6. Using the sys Module

import sys

print("Python Version:", sys.version)
print("Command-line Arguments:", sys.argv)

πŸ“¦ 7. Using the json Module

import json

data = {"name": "Sameer", "age": 25}
json_data = json.dumps(data)  # Convert to JSON string
print(json_data)

parsed_data = json.loads(json_data)  # Convert back to Python dict
print(parsed_data["name"])

πŸ” 8. Using the re Module

import re

text = "My phone number is 9876543210."
pattern = r"\d+"

numbers = re.findall(pattern, text)
print("Numbers found:", numbers)

Output:

Numbers found: ['9876543210']

🌍 9. Real-Life Example – Random Password Generator

import random
import string

def generate_password(length):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for i in range(length))
    return password

print("Generated Password:", generate_password(12))

Comments

Leave a Reply

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