• Power BI: Chapter 1 – Getting Started with Power BI

    🎯 What You’ll Learn

    By the end of this chapter, you’ll be able to:

    • Understand what Power BI is and why it’s used
    • Identify the main components of the Power BI ecosystem
    • Install and launch Power BI Desktop
    • Navigate all key views inside Power BI
    • Compare Power BI to Excel in a business context

    1️⃣ What is Power BI?

    Power BI is Microsoft’s Business Intelligence (BI) platform used for:

    • Connecting to various data sources (Excel, databases, websites, etc.)
    • Cleaning and transforming raw data
    • Creating interactive dashboards and visuals
    • Sharing insights securely via the cloud

    It helps users turn raw data into meaningful insights and business decisions without writing much code.

    ✅ Think of Power BI as Excel + Dashboards + Automation + Cloud Sharing.


    2️⃣ Power BI Components Overview

    ComponentPurpose
    Power BI DesktopCreate reports and dashboards (free desktop app for Windows)
    Power BI ServiceCloud-based platform to publish, view, and collaborate on reports
    Power BI MobileView and interact with reports on mobile devices
    Power BI Report ServerOn-premises reporting solution for enterprises

    🎯 For this course, we’ll mainly use Power BI Desktop and Power BI Service.


    3️⃣ Installing Power BI Desktop

    To Install:

    1. Visit https://powerbi.microsoft.com/desktop
    2. Download from the Microsoft Store (recommended) or direct .exe file
    3. Launch the app after installation

    Minimum Requirements:

    • Windows 10/11
    • 64-bit system
    • At least 4 GB RAM recommended

    ⚠️ Power BI Desktop is not natively available for Mac. You’ll need Windows via Parallels or Remote Desktop if using macOS.


    4️⃣ Power BI vs Excel

    FeatureExcelPower BI
    Data CapacityUp to ~1M rowsHandles tens of millions of rows
    DashboardsLimited interactivityRich, interactive, web-based visuals
    ModelingManual linkingAuto-detect relationships, star schema
    AutomationLimitedScheduled refresh, DAX logic
    CollaborationEmail or OneDriveWeb-based, versioned, and shared

    🔍 Power BI is better suited for large datasets, live dashboards, and sharing insights with teams.


    5️⃣ Power BI Desktop: Views Explained

    When you launch Power BI Desktop, you’ll interact with several key views:


    🧭 1. Report View

    • Design your dashboards with visuals (charts, KPIs, slicers, etc.)
    • Add multiple pages like a presentation
    • Apply formatting and interactions

    📍 Access: Left panel → top icon (chart symbol)


    📋 2. Data View (Table View)

    • Shows your loaded tables like a spreadsheet
    • You can inspect row-level data and add calculated columns using DAX

    📍 Access: Left panel → middle icon (table symbol)


    🔗 3. Model View

    • Displays the relationships between your tables
    • Drag and connect fields to define one-to-many relationships
    • Rename and hide tables, set data roles

    📍 Access: Left panel → bottom icon (diagram symbol)


    🧮 4. DAX Query View (Advanced)

    • Lets you write DAX queries to directly explore or summarize your data
    • Useful for performance tuning and advanced users

    📍 Access: Modeling tab → New DAX Query
    🔧 May need to enable from File → Options → Preview Features


    🧪 Mini Activity: Explore Power BI Desktop

    1. Open Power BI Desktop
    2. Click Home → Get Data → Excel and load any sample dataset
    3. Try switching between:
      • Report View (design)
      • Data View (see table rows)
      • Model View (relationship diagram)
    4. Try dragging a field to create your first bar chart on the canvas

    📌 Chapter Summary

    You Now Know…
    ✅ What Power BI is and what it’s used for
    ✅ The key components: Desktop, Service, Mobile
    ✅ How to install Power BI Desktop
    ✅ How Power BI compares to Excel
    ✅ The 4 main views inside Power BI and what each one does
  • Python 10: Working with APIs and Web Data

    🎯 Goal:

    By the end of this lesson, you’ll be able to:

    • Understand what an API is
    • Use Python to send GET requests
    • Handle JSON responses
    • Pull real-time data (like weather, stock prices, etc.)

    1. What Is an API?

    An API (Application Programming Interface) is a way for your code to talk to another system or service.
    Instead of scraping websites, you ask the website:

    “Can you give me this data in a clean format?”

    They respond with structured data, usually in JSON format.


    2. Installing the requests Library

    You’ll use requests to connect to APIs:

    pip install requests
    

    Then import it in your code:

    import requests
    

    3. Fetch Data from a Public API

    Example: Get weather from the Open-Meteo API (no key required)

    url = "https://api.open-meteo.com/v1/forecast?latitude=51.05&longitude=-114.07&current_weather=true"
    response = requests.get(url)
    
    # Check if it worked
    print(response.status_code)  # 200 means OK
    

    4. Working with JSON

    Convert the response to a dictionary:

    data = response.json()
    print(data)
    
    # Access nested values
    temperature = data["current_weather"]["temperature"]
    windspeed = data["current_weather"]["windspeed"]
    print(f"Current temp: {temperature}°C, Wind: {windspeed} km/h")
    

    5. Example: Build a Simple Weather Reporter

    def get_weather(lat, lon):
        url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&current_weather=true"
        r = requests.get(url)
        if r.status_code == 200:
            data = r.json()
            temp = data["current_weather"]["temperature"]
            wind = data["current_weather"]["windspeed"]
            return f"Temperature: {temp}°C | Wind: {wind} km/h"
        else:
            return "Failed to fetch data."
    
    print(get_weather(51.05, -114.07)) 
    

    6. Handling Errors

    Always wrap your API calls with try-except:

    try:
        response = requests.get(url)
        response.raise_for_status()  # raises error for bad response
    except requests.exceptions.RequestException as e:
        print("API error:", e)
    

    7. Practice Time

    Try these in your blog_env:

    • Use an API to get exchange rates (hint: exchangerate.host or currencyapi.com)
    • Get a random joke from https://official-joke-api.appspot.com/random_joke
    • Print the joke’s setup and punchline
    • Save JSON data to a file
    • Load it back using json.load()

    ✅ Summary

    • APIs are how you get real-time data (weather, news, prices)
    • requests.get() sends a call; .json() lets you work with the result
    • Handle errors with try-except for reliability
    • Real-world: pull product data, crypto prices, delivery ETAs — anything!
  • Python 9: NumPy for Scientific Computing

    Goal:

    By the end of this lesson, you’ll:

    • Understand what NumPy is and why it’s fast
    • Work with arrays instead of lists
    • Perform fast mathematical operations
    • Manipulate data like a data scientist

    What Is NumPy?

    NumPy (Numerical Python) is a powerful library used for:

    • Fast calculations with large datasets
    • Handling numerical matrices (tables of numbers)
    • Vectorized operations (no more for-loops!)

    First, install it:

    pip install numpy
    

    And import it:

    import numpy as np
    

    Creating Arrays

    arr = np.array([1, 2, 3, 4])
    print(arr)          # [1 2 3 4]
    print(arr.shape)    # (4,)
    

    2D array:

    matrix = np.array([[1, 2], [3, 4]])
    print(matrix)
    

    Generate useful arrays:

    np.zeros(5)        # [0. 0. 0. 0. 0.]
    np.ones((2, 3))    # 2 rows, 3 cols of ones
    np.arange(0, 10, 2)  # [0 2 4 6 8]
    np.linspace(0, 1, 5)  # 5 evenly spaced values from 0 to 1
    

    Array Math (Vectorized)

    a = np.array([1, 2, 3])
    b = np.array([10, 20, 30])
    
    print(a + b)     # [11 22 33]
    print(a * b)     # [10 40 90]
    print(a ** 2)    # [1 4 9]
    

    ✅ Way faster than using Python for loops!


    Reshaping and Indexing

    x = np.arange(12)     # [0 to 11]
    x = x.reshape(3, 4)   # 3 rows, 4 columns
    print(x)
    
    print(x[0, 1])  # value at row 0, column 1
    print(x[:, 2])  # all rows, column 2
    

    Basic Statistics

    data = np.array([10, 20, 30, 40, 50])
    
    print(data.mean())     # 30.0
    print(data.std())      # Standard deviation
    print(data.max())      # 50
    print(data.min())      # 10
    

    🧪 6. Practice Time

    Try these in your blog_env notebook:

    • Create an array of daily sales: [2500, 2700, 2600, 3000, 3100]
    • Calculate total, average, and standard deviation
    • Create a 2D array of stock levels by product and day
    • Reshape a 1D array of 12 numbers into 3 rows and 4 columns
    • Use slicing to get the second column of that matrix

    ✅ Summary

    • NumPy is fast, memory-efficient, and the foundation of data science
    • Arrays replace lists for calculations
    • Use .mean(), .std(), and .reshape() often
    • Avoid loops — vectorize your code!

  • Practice Problems for Python 8: Data Visualization

    Here are 5 hands-on practice problems for your Python 8: Data Visualization lesson — focused on real-world retail and business analytics:

    Problem 1: Inventory Bar Chart

    You have the following product stock data:

    products = ["Ring", "Necklace", "Bracelet", "Earring"]
    stock = [12, 5, 8, 15]
    

    Task:

    • Create a vertical bar chart using matplotlib
    • Add title: “Current Inventory”
    • Label axes and add grid lines

    Problem 2: Daily Sales Line Chart

    You tracked sales over 7 days:

    days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
    sales = [3000, 4500, 4000, 4200, 5000, 7500, 6800]
    

    Task:

    • Plot a line graph of sales using matplotlib
    • Add data points (marker=’o’)
    • Highlight the day with the highest sale in the title

    Problem 3: Employee Sales Bar Plot with seaborn

    Create a pandas DataFrame with this data:

    EmployeeTotal_Sales
    Prince15000
    Neha13000
    John18000

    Task:

    • Use seaborn to create a bar plot of Total_Sales by Employee
    • Add appropriate labels and a title

    Problem 4: Price vs Stock Scatter Plot

    You have the following data:

    ProductPriceStock
    Ring250010
    Necklace18005
    Bracelet12008
    Earring90012

    Task:

    • Create a scatter plot using seaborn
    • X-axis = Price, Y-axis = Stock, color by product name
    • Use size=100 and add a chart title

    Problem 5: Create Your Own Dashboard (Bonus)

    Task:

    • Create 3 subplots (side by side or top-bottom) using matplotlib:
      1. Line plot of daily sales
      2. Bar chart of inventory
      3. Scatter plot of price vs stock

    💡 Use plt.subplot(1, 3, i) or plt.subplots() to arrange them.


    Would you like the solution code for each of these too? Or shall I convert these problems into a printable PDF practice sheet?

  • Python 8: Data Visualization with matplotlib and seaborn

    🎯 Goal:

    By the end of this lesson, you’ll be able to:

    • Create simple and beautiful charts using matplotlib and seaborn
    • Visualize sales, product stock, and trends
    • Understand how plots can help make data-driven retail decisions

    🧰 1. Getting Started

    First, install the libraries (if you haven’t already):

    pip install matplotlib seaborn
    

    Then, import them in your notebook:

    import matplotlib.pyplot as plt
    import seaborn as sns
    

    ✅ matplotlib is like the engine

    🎨 seaborn adds style and beauty on top


    📈 2. Visualize Product Stock Levels

    Let’s say you’re running a jewelry store and you want to see what’s in stock.

    products = ["Rings", "Necklaces", "Earrings", "Bracelets"]
    stock = [10, 5, 12, 8]
    
    plt.figure(figsize=(8, 5))
    plt.bar(products, stock)
    plt.title("Product Inventory")
    plt.xlabel("Product")
    plt.ylabel("Stock Level")
    plt.show()
    

    This shows which categories are running low.


    📊 3. Plotting Sales Data

    You have daily sales over a week:

    days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
    sales = [3000, 5000, 4000, 4500, 7000, 9000, 8500]
    
    plt.plot(days, sales, marker='o')
    plt.title("Weekly Sales Trend")
    plt.ylabel("Sales ($)")
    plt.grid(True)
    plt.show()
    

    This helps spot peak shopping days (hello, Saturday!).


    🧠 4. seaborn: Better Looks with Less Code

    Let’s say you have product data in a DataFrame:

    import pandas as pd
    
    data = pd.DataFrame({
        "Product": ["Ring", "Necklace", "Earring", "Bracelet"],
        "Price": [2500, 1800, 1200, 900],
        "Stock": [10, 5, 12, 8]
    })
    
    sns.barplot(x="Product", y="Stock", data=data)
    plt.title("Stock by Product")
    plt.show()
    

    Want to show price vs stock?

    sns.scatterplot(x="Price", y="Stock", data=data, hue="Product", s=100)
    plt.title("Price vs Stock Position")
    plt.show()
    

    🧪 5. Practice Time

    Try these:

    • Plot your own sales data for 10 days
    • Create a bar chart comparing 3 different employees’ total sales
    • Use seaborn to show stock levels across 6 product types
    • Visualize discounts vs. final prices with a line or scatter plot

    ✅ Summary

    • matplotlib and seaborn help you see your data clearly
    • Bar charts are great for inventory, line charts for trends, and scatter plots for comparisons
    • Start visualizing early to spot opportunities and problems in retail

  • Python 7: Practice OOP with 5 Real-World Problems

    🎯 Goal:

    In this blog, you’ll build real Python classes to solve practical problems. Each one will stretch your understanding of:

    • Class creation and methods
    • Object interaction
    • Inheritance
    • Retail sales logic

    If you’ve followed the previous posts, this is your moment to apply it all!


    🛒 1. Build a Product Class

    Every retail system starts with a product. Let’s model one!

    Problem:
    Create a class Product with the following:

    • name, price, and stock as attributes
    • A method sell(quantity) that reduces the stock
    • A method get_info() that prints product name and remaining stock

    Example:

    p1 = Product("Ring", 1000, 10)
    p1.sell(2)      # reduces stock to 8
    p1.get_info()   # shows name + updated stock
    

    💸 2. Add Discount Logic

    Retail isn’t just about selling — it’s about pricing smartly.

    Problem:
    Add a method apply_discount(percent) to your Product class that updates the price after reducing it by the given percentage.

    Update get_info() to also show the current price.

    Example:

    p1.apply_discount(10)  # price drops to 900
    p1.get_info()          # shows updated price and stock
    

    👥 3. Model an Employee Who Processes Sales

    Let’s bring employees into the scene.

    Problem:
    Create a class Employee with:

    • name and role
    • A method process_sale(product, quantity)
      This method should call product.sell() and print a message showing who sold what.

    Example:

    e1 = Employee("Prince", "Sales Associate")
    e1.process_sale(p1, 3)
    # Prince sold 3 x Ring for $2700
    

    📊 4. Track Each Sale as a Sale Object

    We don’t just want to sell — we want to track each transaction.

    Problem:
    Create a Sale class that stores:

    • The product, employee, and quantity
    • Automatically calculates the total
    • A summary() method that prints the full transaction

    Example:

    s1 = Sale(p1, e1, 2)
    s1.summary()
    # Prince sold 2 x Ring for $1800
    

    🏪 5. Build a Store That Manages Inventory

    Now let’s manage multiple products in a single place.

    Problem:
    Create a class Store with:

    • A list of products
    • A method add_product(product)
    • A method list_inventory() that prints each product’s name and stock

    Bonus: Add a method to find a product by name.

    Example:

    store = Store()
    store.add_product(p1)
    store.list_inventory()
    # Ring - 5 in stock
    

    ✅ Summary

    With these 5 problems, you’ve touched on:

    • Object creation and method chaining
    • Collaboration between classes
    • Real-world use of OOP in retail
    • The foundation for dashboards, APIs, and full apps
  • Python 6: Why Use Classes in Python? (Intro to OOP Logic)

    🎯 Goal:

    By the end of this lesson, you’ll understand:

    • What a class really is
    • Why classes are needed for real-world applications
    • When to use classes instead of plain functions and variables

    🍪 1. What is a Class (Really)?

    Think of a class as a blueprint or cookie cutter. It defines the structure and behavior of things you want to model — like a product, employee, or order in a retail store.

    class Product:
        def __init__(self, name, price):
            self.name = name
            self.price = price
    

    This is just the design. You still have to create actual products using it (called objects):

    ring = Product("Diamond Ring", 2500)
    

    Now you’ve made a real product — just like baking cookies from a mold.


    🛠 2. The Problem Without Classes

    Let’s say you’re selling a ring. Without using classes, here’s how you might track it:

    product_name = "Diamond Ring"
    product_price = 2500
    product_stock = 10
    
    def sell(quantity):
        global product_stock
        product_stock -= quantity
    

    🧱 This works for one product. But what if you have 50?
    You’d need:

    • product_name1, product_name2, product_name3, …
    • sell_product1(), sell_product2() … 😩

    It becomes messy, repetitive, and hard to maintain.


    ✅ 3. Why Classes Are Better

    Here’s how much cleaner and scalable it becomes:

    class Product:
        def __init__(self, name, price, stock):
            self.name = name
            self.price = price
            self.stock = stock
    
        def sell(self, quantity):
            if quantity <= self.stock:
                self.stock -= quantity
                return f"Sold {quantity} x {self.name}"
            else:
                return f"Not enough stock for {self.name}"
    

    Now you can do:

    ring = Product("Diamond Ring", 2500, 10)
    necklace = Product("Necklace", 1500, 5)
    print(ring.sell(3))
    print(necklace.sell(2))
    

    🎉 No need for extra variables or duplicate logic. Every product has its own behavior and data.


    🔁 4. When Should You Use Classes?

    SituationUse a Class?Why?
    One-time scriptFunctions are fine
    Managing a store with products, employees, ordersReusable objects
    Building an app or dashboardClean architecture
    Prototyping something quickSimplicity matters

    💡 5. OOP Powers You Unlock

    Once you understand classes, you’ll soon be able to use:

    • Inheritance (e.g. Manager inherits from Employee)
    • Polymorphism (e.g. override behavior in different subclasses)
    • Encapsulation (keep your code tidy and modular)

    🧪 6. Practice Time

    Try these in your blog_env:

    • Create a Product class with name, price, and stock
    • Add a method called discount() that reduces the price
    • Create multiple product objects and print their updated prices

    📘 Summary

    • A class is a template that describes a type of object
    • Objects created from classes are reusable and scalable
    • OOP makes your code clean, efficient, and real-world ready
    • It’s essential for any serious application like sales dashboards, inventory systems, or APIs
  • Python 5: Object-Oriented Programming (OOP) — Retail Sales Edition

    🎯 Goal:

    By the end of this lesson, you’ll be able to:

    • Create Python classes for retail operations
    • Represent inventory, employees, and transactions
    • Use inheritance for role-based systems
    • Apply OOP to real retail workflows

    🛍️ 1. Why OOP for Retail?

    Imagine managing a retail business: you have products, employees, and sales records. Instead of juggling a mess of unrelated variables and lists, OOP lets you model everything in real-world terms.


    📦 2. Building a Product Class

    Let’s define a basic product:

    
    class Product:
        def __init__(self, name, price, stock):
            self.name = name
            self.price = price
            self.stock = stock
    
        def sell(self, quantity):
            if quantity <= self.stock:
                self.stock -= quantity
                return f"Sold {quantity} x {self.name}"
            else:
                return f"Not enough stock for {self.name}"
    
        def restock(self, quantity):
            self.stock += quantity
            return f"Restocked {quantity} x {self.name}"
    

    🛒 3. Selling and Managing Inventory

    
    item1 = Product("Diamond Ring", 2500, 10)
    print(item1.sell(2))      # Sold 2 x Diamond Ring
    print(item1.restock(5))   # Restocked 5 x Diamond Ring
    print(item1.stock)        # 13
    

    This gives us full control over inventory operations.


    👥 4. Creating an Employee Class

    
    class Employee:
        def __init__(self, name, role):
            self.name = name
            self.role = role
    
        def process_sale(self, product, quantity):
            return f"{self.name} processed sale: {product.sell(quantity)}"
    emp1 = Employee("Prince", "Sales Associate")
    print(emp1.process_sale(item1, 3))
    

    🧬 5. Inheritance for Specialized Roles

    Let’s create a Manager who can also approve discounts:

    class Manager(Employee):
        def approve_discount(self, product, percent):
            discounted_price = product.price * (1 - percent / 100)
            return f"Discount approved: {product.name} now ${discounted_price:.2f}"
    mgr = Manager("Neha", "Store Manager")
    print(mgr.approve_discount(item1, 10))
    

    📊 6. Adding Sales Records (Composition)

    class Sale:
        def __init__(self, product, employee, quantity):
            self.product = product
            self.employee = employee
            self.quantity = quantity
            self.total = product.price * quantity
    
        def summary(self):
            return f"{self.employee.name} sold {self.quantity} x {self.product.name} for ${self.total}"
    pythonCopyEditsale1 = Sale(item1, emp1, 2)
    print(sale1.summary())
    

    ✅ 7. Practice Time

    Try these in your blog_env notebook:

    • Create 3 products and simulate stock depletion
    • Create 2 employees and assign them sales
    • Add a return_item() method that refunds stock
    • Track daily sales totals using a list of Sale objects

    📘 Summary

    • OOP helps manage retail workflows like stock tracking and employee roles
    • Classes keep data and behavior bundled together
    • Inheritance helps you add features like manager privileges
    • OOP is ideal for modeling inventory, sales, and team structure
  • Python 4: Working with File Paths and Changing Directories

    🎯 Goal:

    By the end of this blog, you’ll be able to:

    • Check and change your current working directory
    • Save files to a custom folder like OneDrive
    • Build platform-safe file paths (Windows or Mac)

    📍 1. What is a Working Directory?

    When you run a Python script or a notebook, Python has a “default folder” it operates in — this is called the working directory. Any file you read/write (like notes.txt) goes here unless you tell it otherwise.

    Check it with:

    import os
    print(os.getcwd())
    

    🧠 This will tell you where Python is currently reading or writing files from.


    🔄 2. Changing the Directory

    Let’s say you want to save your file inside a folder called PythonProjects inside your OneDrive.

    🪟 On Windows:

    import os
    
    # Use raw string (r"...") to avoid errors with backslashes
    onedrive_path = r"C:\Users\Prince\OneDrive\PythonProjects"
    os.chdir(onedrive_path)
    print("Now working in:", os.getcwd())
    

    🍎 On Mac (if using OneDrive):

    import os
    
    onedrive_path = "/Users/princejohn/OneDrive/PythonProjects"
    os.chdir(onedrive_path)
    print("Now working in:", os.getcwd())
    

    📄 3. Creating the Folder (If It Doesn’t Exist)

    Just in case the folder doesn’t exist yet:

    os.makedirs(onedrive_path, exist_ok=True)
    os.chdir(onedrive_path)
    

    🔐 exist_ok=True prevents Python from throwing an error if the folder is already there.


    💾 4. Writing a File into OneDrive

    Once your working directory is changed:

    with open("notes.txt", "w") as file:
        file.write("Saved into OneDrive successfully!")
    

    Now open your OneDrive and you’ll see notes.txt inside the PythonProjects folder.


    🔧 5. Building Paths the Safe Way

    Instead of manually typing slashes, use os.path.join() — it’s safer across Windows, Mac, and Linux.

    filename = "notes.txt"
    path = os.path.join(onedrive_path, filename)
    
    with open(path, "w") as file:
        file.write("Cross-platform file writing!")
    

    ✅ Summary

    • Use os.getcwd() to see where you’re working
    • Use os.chdir() to move to folders like OneDrive
    • Use os.makedirs() to create folders safely
    • Use os.path.join() to write platform-friendly code
  • Python 3: Files and Exception Handling

    🎯 Goal:

    By the end of this lesson, you’ll be able to:

    • Read and write files in Python
    • Handle errors using try-except
    • Work with real data like CSV and JSON

    📄 1. Reading and Writing Text Files

    📝 Writing to a File

    with open("notes.txt", "w") as file:
        file.write("This is your first file write in Python!\n")
        file.write("Welcome to the file world.")
    

    "w" creates a new file or overwrites an existing one.

    📖 Reading a File

    with open("notes.txt", "r") as file:
        content = file.read()
        print(content)
    

    🔁 Line-by-Line Reading

    with open("notes.txt", "r") as file:
        for line in file:
            print(line.strip())
    

    ➕ Appending to a File

    with open("notes.txt", "a") as file:
        file.write("\nAnother line added.")
    

    🧾 2. Handling CSV Files

    import csv
    
    with open("data.csv", mode="w", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(["Name", "Role"])
        writer.writerow(["Prince", "Analyst"])
    

    Reading CSV:

    with open("data.csv", "r") as file:
        reader = csv.reader(file)
        for row in reader:
            print(row)
    

    🌐 3. JSON Basics (Web-Friendly Format)

    import json
    
    person = {"name": "Prince", "skills": ["Python", "SQL"]}
    json_data = json.dumps(person)
    print(json_data)  # convert to JSON string
    
    # Save to file
    with open("person.json", "w") as f:
        json.dump(person, f)
    
    # Load from file
    with open("person.json", "r") as f:
        loaded = json.load(f)
        print(loaded["name"])
    

    ⚠️ 4. Exception Handling

    Errors happen — Python gives you a way to handle them gracefully.

    Try-Except Block

    try:
        result = 10 / 0
    except ZeroDivisionError:
        print("Oops! Can't divide by zero.")
    

    Catching Multiple Exceptions

    try:
        x = int("abc")
    except (ValueError, TypeError) as e:
        print(f"Error occurred: {e}")
    

    Finally Block

    try:
        f = open("test.txt", "r")
    except FileNotFoundError:
        print("File not found!")
    finally:
        print("Cleanup complete.")
    

    ✅ Practice Time

    Try these in your blog_env:

    • Write a list of your favorite books to a file
    • Read from that file and print each book
    • Create a CSV file with name, age, city
    • Use try-except to catch file not found or zero division errors

    📘 Summary

    • You learned how to read/write files, handle CSV/JSON
    • You handled exceptions cleanly with try-except
    • You now have the tools to build real-world data scripts