Skip to content
Laviyx Learn

Try

Practical Python Practice

Practise real-world tasks, working with SQLite databases, CSV files, folders of files, JSON from APIs, and HTML pages, all without needing an internet connection.

Intermediate7 problemsUpdated

Review first: Database Connections, Automation, Working With APIs, Web Scraping, Useful Python Scripts

  1. 1.Store and query data with SQLite

    Intermediate

    Using the built-in sqlite3 module and an in-memory database, create a products table, insert three products with a parameterised query, then print the products cheaper than 1000, cheapest first.

    Show hint

    Use ? placeholders and pass the values separately: cur.execute("... WHERE price < ?", (1000,)). executemany inserts a list of rows.

    Show solution
    Python
    import sqlite3
    
    conn = sqlite3.connect(":memory:")
    cur = conn.cursor()
    
    cur.execute("CREATE TABLE products (name TEXT, price INTEGER)")
    cur.executemany(
        "INSERT INTO products (name, price) VALUES (?, ?)",
        [("Notebook", 60), ("Headphones", 2500), ("Pen Set", 250)],
    )
    conn.commit()
    
    for name, price in cur.execute(
        "SELECT name, price FROM products WHERE price < ? ORDER BY price", (1000,)
    ):
        print(name, price)
    
    conn.close()
    Output
    Notebook 60
    Pen Set 250

    Never build SQL by joining strings with user input (for example f"... WHERE name = '{name}'"). Placeholders keep the values separate from the SQL, which prevents SQL injection.

  2. 2.Totals from a CSV file

    Intermediate

    Write this CSV to sales.csv, then read it with csv.DictReader and print the total amount for each region (in alphabetical order):

    Text
    region,amount
    North,1200
    South,800
    North,450
    East,990
    South,300
    Show hint

    DictReader gives each row as a dictionary like {"region": "North", "amount": "1200"}. The amounts are strings, so convert them.

    Show solution
    Python
    import csv
    
    data = """region,amount
    North,1200
    South,800
    North,450
    East,990
    South,300
    """
    
    with open("sales.csv", "w", encoding="utf-8", newline="") as f:
        f.write(data)
    
    totals = {}
    with open("sales.csv", encoding="utf-8", newline="") as f:
        for row in csv.DictReader(f):
            totals[row["region"]] = totals.get(row["region"], 0) + int(row["amount"])
    
    for region in sorted(totals):
        print(region, totals[region])
    Output
    East 990
    North 1650
    South 1100

    Open CSV files with newline="", as the csv module documentation recommends, so line endings are handled correctly on every operating system.

  3. 3.Organise files by extension

    Intermediate

    Create a folder downloads containing report.pdf, photo.jpg, notes.txt, scan.pdf and holiday.jpg. Then move each file into a subfolder named after its extension (pdf, jpg, txt) and print the resulting layout.

    Show hint

    pathlib.Path makes this easy: path.suffix gives ".pdf", folder.mkdir(exist_ok=True) creates a folder, and path.rename(target) moves a file.

    Show solution
    Python
    from pathlib import Path
    
    downloads = Path("downloads")
    downloads.mkdir()
    for name in ["report.pdf", "photo.jpg", "notes.txt", "scan.pdf", "holiday.jpg"]:
        (downloads / name).write_text("sample")
    
    for path in list(downloads.iterdir()):
        if path.is_file():
            folder = downloads / path.suffix.lstrip(".")
            folder.mkdir(exist_ok=True)
            path.rename(folder / path.name)
    
    for path in sorted(downloads.rglob("*")):
        if path.is_file():
            print(path.relative_to(downloads).as_posix())
    Output
    jpg/holiday.jpg
    jpg/photo.jpg
    pdf/report.pdf
    pdf/scan.pdf
    txt/notes.txt

    The loop uses list(downloads.iterdir()) so the folder listing is read once, before files start moving. as_posix() prints forward slashes on every operating system.

  4. 4.Read a JSON API response

    Intermediate

    An API returned the JSON below. Print each user's name and city, and print unknown for a missing city. Then print how many users are active.

    JSON
    {"users": [
      {"name": "Asha", "address": {"city": "Pune"}, "active": true},
      {"name": "Ravi", "address": {}, "active": false},
      {"name": "Meera", "address": {"city": "Delhi"}, "active": true}
    ]}
    Show hint

    json.loads(text) turns the JSON into dictionaries and lists. Use .get("city", "unknown") for keys that might be missing. With the requests library, response.json() does the parsing for you.

    Show solution
    Python
    import json
    
    text = """{"users": [
      {"name": "Asha", "address": {"city": "Pune"}, "active": true},
      {"name": "Ravi", "address": {}, "active": false},
      {"name": "Meera", "address": {"city": "Delhi"}, "active": true}
    ]}"""
    
    data = json.loads(text)
    
    for user in data["users"]:
        city = user.get("address", {}).get("city", "unknown")
        print(user["name"], city)
    
    print(sum(1 for user in data["users"] if user["active"]), "active users")
    Output
    Asha Pune
    Ravi unknown
    Meera Delhi
    2 active users

    Real API data is often incomplete, so reading nested values with .get() and sensible defaults keeps your program from crashing on one bad record. Notice that JSON's true becomes Python's True.

  5. 5.Extract data from HTML

    Intermediate

    Using BeautifulSoup, extract each product's name and price from this HTML (already downloaded), and print the cheapest product.

    HTML
    <ul id="products">
      <li class="product"><h2>Laptop</h2><span class="price">₹55,000</span></li>
      <li class="product"><h2>Headphones</h2><span class="price">₹2,500</span></li>
      <li class="product"><h2>Monitor</h2><span class="price">₹12,000</span></li>
    </ul>
    Show hint

    soup.select("li.product") finds the items; item.select_one(".price").get_text() reads the price text. Remove ₹ and commas before converting to int.

    Show solution
    Python
    from bs4 import BeautifulSoup
    
    html = """
    <ul id="products">
      <li class="product"><h2>Laptop</h2><span class="price">₹55,000</span></li>
      <li class="product"><h2>Headphones</h2><span class="price">₹2,500</span></li>
      <li class="product"><h2>Monitor</h2><span class="price">₹12,000</span></li>
    </ul>
    """
    
    soup = BeautifulSoup(html, "html.parser")
    
    products = []
    for item in soup.select("li.product"):
        name = item.h2.get_text(strip=True)
        price_text = item.select_one(".price").get_text(strip=True)
        price = int(price_text.replace("₹", "").replace(",", ""))
        products.append((name, price))
        print(name, price)
    
    cheapest = min(products, key=lambda p: p[1])
    print("Cheapest:", cheapest[0])
    Output
    Laptop 55000
    Headphones 2500
    Monitor 12000
    Cheapest: Headphones

    Install BeautifulSoup with python -m pip install beautifulsoup4. On a live website you would first download the page with requests.get(url).text, after checking that the site allows scraping.

  6. 6.Top words in a text

    Intermediate

    Print the three most common words in text, ignoring case and punctuation, and skipping the common words the, a, and and of.

    Show hint

    re.findall(r"[a-z']+", text.lower()) extracts the words. Filter out the stop words, then use Counter.most_common(3).

    Show solution
    Python
    import re
    from collections import Counter
    
    text = """The cat sat on the mat. The cat was happy, and the mat was warm.
    A dog saw the cat and the mat, and the dog sat too."""
    
    stop_words = {"the", "a", "and", "of"}
    
    words = re.findall(r"[a-z']+", text.lower())
    counts = Counter(w for w in words if w not in stop_words)
    
    for word, count in counts.most_common(3):
        print(word, count)
    Output
    cat 3
    mat 3
    sat 2

    sat, was and dog all appear twice. When counts tie, most_common keeps the order in which the words were first seen, so sat comes first.

  7. 7.Add dates to file names

    Intermediate

    Create the files invoice.pdf and receipt.pdf in a folder bills. Rename each one so its name starts with a fixed date, giving 2026-10-23_invoice.pdf, and print the new names. (A real script would use today's date.)

    Show hint

    path.with_name(new_name) builds the new path in the same folder; date.isoformat() gives YYYY-MM-DD.

    Show solution
    Python
    from datetime import date
    from pathlib import Path
    
    bills = Path("bills")
    bills.mkdir()
    for name in ["invoice.pdf", "receipt.pdf"]:
        (bills / name).write_text("sample")
    
    stamp = date(2026, 10, 23).isoformat()  # use date.today() in a real script
    
    for path in sorted(bills.iterdir()):
        path.rename(path.with_name(f"{stamp}_{path.name}"))
    
    print(sorted(p.name for p in bills.iterdir()))
    Output
    ['2026-10-23_invoice.pdf', '2026-10-23_receipt.pdf']

    Putting dates in YYYY-MM-DD form at the start of a file name makes files sort in date order automatically.