π― 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
| Library | Purpose | Example |
|---|---|---|
math | Mathematical operations | math.sqrt(16) |
random | Generate random numbers | random.randint(1,10) |
datetime | Handle dates and times | datetime.date.today() |
os | Operating system functions | os.listdir() |
sys | System-specific parameters | sys.version |
json | JSON data handling | json.dumps({"a":1}) |
csv | CSV file handling | csv.reader(file) |
re | Regular expressions | re.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))

Leave a Reply