Power tools from the standard library, SQLite databases, data analysis with charts, and web apps with APIs and Flask.
Every code example has a ▶ Run button. Click ✎ Edit & Run, or press L, to open the Python Lab.
D:\python-practice).1from datetime import datetime, date, timedelta23issued = datetime.strptime("15-09-2026", "%d-%m-%Y").date()4due = issued + timedelta(days=14)5returned = date(2026, 10, 8)6late_days = (returned - due).days78print("Issued :", issued.strftime("%d %b %Y (%a)"))9print("Due :", due.strftime("%d %b %Y (%a)"))10print("Returned:", returned.strftime("%d %b %Y (%a)"))11print("Late by :", max(0, late_days), "days, fine Rs", max(0, late_days) * 2)1213start = datetime(2026, 10, 8, 9, 45)14end = datetime(2026, 10, 8, 13, 10)15print("Exam duration:", end - start)16print("Is due before Diwali?", due < date(2026, 11, 8))
| Need | Use |
|---|---|
| text -> date | datetime.strptime(text, fmt) |
| date -> text | d.strftime(fmt) |
| add / subtract days | d + timedelta(days=7) |
| difference | (d2 - d1).days |
| compare | d1 < d2 |
| now | datetime.now(), date.today() |
1from pathlib import Path23downloads = Path("Downloads")4files = sorted(p for p in downloads.iterdir() if p.is_file())5print(len(files), "files in", downloads)6for p in files[:4]:7 print(f" {p.name:<20} stem={p.stem:<16} type={p.suffix}")89pdfs = list(downloads.glob("*.pdf"))10print("PDFs:", [p.name for p in pdfs])1112report = Path("Reports") / "2026" / "october"13report.mkdir(parents=True, exist_ok=True)14print("Created:", report, report.exists())
| Code | Gives |
|---|---|
p.name | "photo.jpg" |
p.stem | "photo" |
p.suffix | ".jpg" |
p.parent | the folder |
p.iterdir() | items in a folder |
p.glob("*.pdf") | matching files |
p.mkdir(...) | make folders |
Path("a") / "b" / "c.txt" joins paths correctly on Windows, Mac and Linux.1import shutil2from pathlib import Path34src = Path("project")5src.mkdir(exist_ok=True)6(src / "main.py").write_text("print('hi')")7(src / "data.csv").write_text("a,b\n1,2")89shutil.copy(src / "main.py", src / "main_backup.py") # copy one file10shutil.copytree(src, "project_copy", dirs_exist_ok=True) # copy a folder11shutil.make_archive("project_backup", "zip", src) # zip it1213print(sorted(p.name for p in src.iterdir()))14print(sorted(p.name for p in Path("project_copy").iterdir()))15print("Zip created:", Path("project_backup.zip").exists())
| Function | Does |
|---|---|
shutil.copy(a, b) | copy a file |
shutil.move(a, b) | move / rename |
shutil.copytree(a, b) | copy a whole folder |
shutil.rmtree(p) | delete a folder (careful!) |
shutil.make_archive() | create a .zip |
shutil.rmtree and os.remove delete permanently, with no Recycle Bin. Test on copies first.1from collections import Counter, defaultdict, namedtuple, deque23votes = ["Sarhul", "Karma", "Diwali", "Karma", "Karma", "Sarhul", "Chhath", "Karma"]4c = Counter(votes)5print(c.most_common(2))67by_city = defaultdict(list)8for name, city in [("Aman", "Ranchi"), ("Riya", "Dhanbad"), ("Om", "Ranchi")]:9 by_city[city].append(name) # no KeyError, list made automatically10print(dict(by_city))1112Point = namedtuple("Point", "lat lon")13ranchi = Point(23.34, 85.31)14print(ranchi.lat, ranchi)1516recent = deque(maxlen=3) # keeps only the last 317for page in ["home", "results", "fees", "contact"]:18 recent.append(page)19print(list(recent))
| Tool | Best for |
|---|---|
Counter | counting things, top-N |
defaultdict(list) | grouping without checking keys |
namedtuple | small records with field names |
deque(maxlen=n) | recent history, queues |
Type your own pattern. Yellow = matches. (The browser uses JavaScript regex, which matches Python for these common patterns.)
| Symbol | Means | Example |
|---|---|---|
\d | a digit | \d\d = 42 |
\w | letter, digit or _ | |
\s | space | |
. | any character | |
[6-9] | one of 6,7,8,9 | |
{10} | exactly 10 times | \d{10} |
+ / * / ? | 1+ / 0+ / 0 or 1 | |
^ $ | start / end | |
\b | word boundary | |
( ) | group to extract |
1import re23text = "Order 1043 by aman@gmail.com, call 9835011111. Order 1051 by riya@yahoo.in"45print(re.findall(r"\d{4}", text)) # all 4-digit numbers6print(re.findall(r"[\w.]+@[\w.]+", text)) # emails7m = re.search(r"call (\d{10})", text)8print("Phone:", m.group(1))910for mobile in ["9835011111", "1234567890", "98350"]:11 ok = re.fullmatch(r"[6-9]\d{9}", mobile) is not None12 print(mobile, "valid" if ok else "invalid")1314print(re.sub(r"\d(?=\d{4})", "X", "9835011111")) # mask all but last 4
| Function | Returns |
|---|---|
re.search(p, s) | first match (or None) |
re.findall(p, s) | list of all matches |
re.fullmatch(p, s) | match only if the WHOLE string fits |
re.sub(p, new, s) | replace matches |
m.group(1) | text inside the first ( ) |
r"..." so backslashes stay as they are.re.sub to replace every digit in a phone number with "*"strptime and add timedelta(days=10)1from datetime import datetime, date, timedelta23today = date(2026, 10, 8)4students = {"Aman": "20-09-2026", "Priya": "01-10-2026", "Rahul": "27-09-2026", "Sneha": "05-10-2026"}56for name, joined in students.items():7 due = datetime.strptime(joined, "%d-%m-%Y").date() + timedelta(days=10)8 diff = (due - today).days9 if diff > 0:10 msg = f"due in {diff} day(s) on {due:%d %b}"11 elif diff == 0:12 msg = "due TODAY"13 else:14 msg = f"LATE by {-diff} days, late fee Rs {-diff * 50}"15 print(f"{name:<6} {msg}")
Path("Downloads").iterdir()shutil.move the file1from pathlib import Path2from collections import Counter3import shutil45TYPES = {".pdf": "Documents", ".txt": "Documents", ".jpg": "Images", ".png": "Images",6 ".xlsx": "Spreadsheets", ".mp3": "Music", ".zip": "Archives"}7folder = Path("Downloads")8moved = Counter()9for f in list(folder.iterdir()):10 if f.is_file():11 target = folder / TYPES.get(f.suffix.lower(), "Others")12 target.mkdir(exist_ok=True)13 shutil.move(str(f), str(target / f.name))14 moved[target.name] += 11516for sub in sorted(p for p in folder.iterdir() if p.is_dir()):17 print(f"{sub.name:<13}", sorted(x.name for x in sub.iterdir()))18print("Moved:", dict(moved))
Counter for each class and add them togethermost_common() to rank candidatesdefaultdict(dict) for class-wise counts1from collections import Counter, defaultdict23ballots = {4 "9A": ["Anjali", "Rohit", "Anjali", "Imran", "Anjali", "Rohit"],5 "9B": ["Rohit", "Rohit", "Imran", "Anjali", "Rohit"],6 "10A": ["Imran", "Anjali", "Imran", "Imran", "Rohit", "Imran", "Anjali"],7}8total = Counter()9breakdown = defaultdict(dict)10for cls, votes in ballots.items():11 c = Counter(votes)12 total += c13 for cand, n in c.items():14 breakdown[cand][cls] = n1516for rank, (cand, n) in enumerate(total.most_common(), 1):17 print(f"{rank}. {cand:<7}{'#' * n:<10}{n:>3} {breakdown[cand]}")18print("Winner:", total.most_common(1)[0][0])
re.fullmatch for each field1import re23RULES = {4 "name": (r"[A-Za-z ]{3,40}", "letters only, 3-40 chars"),5 "mobile": (r"[6-9]\d{9}", "10 digits starting 6-9"),6 "email": (r"[\w.+-]+@[\w-]+\.[\w.]+", "like name@site.com"),7 "pin": (r"8[0-5]\d{4}", "Bihar/Jharkhand PIN, 6 digits"),8 "id_number": (r"\d{4} ?\d{4} ?\d{4}", "12 digits"),9}1011def validate(form):12 errors = [f"{f}: {msg}" for f, (pat, msg) in RULES.items() if not re.fullmatch(pat, form.get(f, "").strip())]13 return errors1415forms = [16 {"name": "Riya Kumari", "mobile": "9835011111", "email": "riya@gmail.com", "pin": "834001", "id_number": "1234 5678 9012"},17 {"name": "R2", "mobile": "5835011111", "email": "riya.gmail.com", "pin": "110001", "id_number": "12345"},18]19for i, f in enumerate(forms, 1):20 errs = validate(f)21 print(f"Form {i}:", "OK" if not errs else "")22 for e in errs:23 print(" x", e)
server.log line by lineCounter for log levelsre.search to extract order numbers, codes and page timesdefaultdict(list) to group orders by error codeif m := re.search(...) uses the "walrus" operator := (Python 3.8+): it stores the match and tests it in one step.1import re2from collections import Counter, defaultdict34levels = Counter()5failed = defaultdict(list)6slow = []7with open("server.log") as f:8 for line in f:9 levels[line.split()[2]] += 110 if m := re.search(r"order=(\d+) code=(\w+)", line):11 failed[m.group(2)].append(m.group(1))12 if m := re.search(r"page=(\S+) time=([\d.]+)s", line):13 slow.append((float(m.group(2)), m.group(1)))1415print("Levels:", dict(levels))16for code, orders in failed.items():17 print(f"Payment error {code}: orders {orders}")18print("Slowest page:", max(slow))
datetime: strptime (text to date), strftime (date to text), timedeltapathlib.Path: iterdir, glob, mkdir, name, suffix; join with /shutil: copy, move, copytree, make_archive (delete carefully)Counter counts, defaultdict groups, namedtuple names fields, deque keeps recent itemsre: findall, search, fullmatch, sub with raw-string patternsWhich gives the number of days between two dates?
Counter("banana").most_common(1)?
Regex for exactly 6 digits?
| CSV file | Database | |
|---|---|---|
| Search 1 million rows | slow (read everything) | fast (indexes) |
| Many users writing | files get corrupted | safe (transactions) |
| Relations between tables | manual | JOIN |
| Rules (unique, not null) | none | enforced |
1-- Create a table2CREATE TABLE students (3 roll INTEGER PRIMARY KEY,4 name TEXT NOT NULL,5 class TEXT, city TEXT, marks INTEGER6);7-- Create rows8INSERT INTO students (name, class, city, marks)9VALUES ('Aman', '9A', 'Ranchi', 78);10-- Read11SELECT name, marks FROM students WHERE city = 'Ranchi';12-- Update13UPDATE students SET marks = 80 WHERE roll = 1;14-- Delete15DELETE FROM students WHERE roll = 5;
| CRUD | SQL | Meaning |
|---|---|---|
| Create | INSERT | add rows |
| Read | SELECT | get rows |
| Update | UPDATE | change rows |
| Delete | DELETE | remove rows |
SELECT name, marks FROM students WHERE city = 'Ranchi'| name | marks |
|---|---|
| Aman | 78 |
| Rahul | 65 |
| Kiran | 45 |
UPDATE or DELETE without WHERE changes every row in the table!1import sqlite323con = sqlite3.connect("school.db") # creates the file if missing4cur = con.cursor()5cur.execute("""CREATE TABLE IF NOT EXISTS students (6 roll INTEGER PRIMARY KEY,7 name TEXT NOT NULL, class TEXT, city TEXT, marks INTEGER)""")89new = [("Aman", "9A", "Ranchi", 78), ("Priya", "9A", "Dhanbad", 92), ("Rahul", "9B", "Ranchi", 65)]10cur.executemany("INSERT INTO students (name, class, city, marks) VALUES (?, ?, ?, ?)", new)11con.commit() # save changes!1213for row in cur.execute("SELECT roll, name, marks FROM students"):14 print(row)15print("Rows:", cur.execute("SELECT COUNT(*) FROM students").fetchone()[0])16con.close()
1(SQLite database file, 8192 bytes)
connect() opens (or creates) the database fileexecute() runs SQL; executemany() runs it for many rowscommit() saves changes permanentlyfetchone() / fetchall()commit()? Your inserts disappear when the program ends.name = input("Name: ")cur.execute(f"SELECT * FROM users
WHERE name = '{name}'")x' OR '1'='1 the query returns every user!cur.execute("SELECT * FROM users
WHERE name = ?", (name,))1import sqlite32from school_db import make_db3con = make_db() # school.db with 6 students (helper file)45evil = "x' OR '1'='1"6bad = con.execute(f"SELECT name FROM students WHERE name = '{evil}'").fetchall()7safe = con.execute("SELECT name FROM students WHERE name = ?", (evil,)).fetchall()8print("f-string query returned:", len(bad), "rows!")9print("? placeholder returned :", len(safe), "rows")
1import sqlite32from school_db import make_db3con = make_db() # school.db with 6 students (helper file)45con.row_factory = sqlite3.Row # rows act like dicts67print("Top 3:")8for r in con.execute("SELECT name, marks FROM students ORDER BY marks DESC LIMIT 3"):9 print(f" {r['name']:<6} {r['marks']}")1011print("From Ranchi with 60+:")12for r in con.execute("SELECT name FROM students WHERE city = ? AND marks >= ?", ("Ranchi", 60)):13 print(" ", r["name"])14print("Names with S/I:", [r[0] for r in con.execute("SELECT name FROM students WHERE name LIKE 'S%' OR name LIKE 'I%'")])
| Clause | Does |
|---|---|
WHERE | filter rows |
AND / OR | combine conditions |
ORDER BY x DESC | sort (DESC = high to low) |
LIMIT n | first n rows |
LIKE 'S%' | pattern: % = anything |
con.row_factory = sqlite3.Row lets you use r["name"] instead of r[1].1import sqlite32from school_db import make_db3con = make_db() # school.db with 6 students (helper file)45q = """SELECT class, COUNT(*) AS students, ROUND(AVG(marks), 1) AS avg_marks,6 MAX(marks) AS top, MIN(marks) AS lowest7 FROM students GROUP BY class ORDER BY class"""8print(f"{'Class':<6}{'Count':>6}{'Avg':>7}{'Top':>5}{'Low':>5}")9for row in con.execute(q):10 print(f"{row[0]:<6}{row[1]:>6}{row[2]:>7}{row[3]:>5}{row[4]:>5}")1112print(con.execute("SELECT city, COUNT(*) FROM students GROUP BY city HAVING COUNT(*) > 1").fetchall())
| Function | Gives |
|---|---|
COUNT(*) | number of rows |
SUM(x) | total |
AVG(x) | average |
MAX / MIN | highest / lowest |
GROUP BY col | one result row per group |
HAVING | filter groups |
1import sqlite32con = sqlite3.connect(":memory:")3con.executescript("""4CREATE TABLE students (roll INTEGER PRIMARY KEY, name TEXT);5CREATE TABLE fees (id INTEGER PRIMARY KEY, roll INTEGER, month TEXT, amount INTEGER);6INSERT INTO students VALUES (1, 'Aman'), (2, 'Priya'), (3, 'Rahul');7INSERT INTO fees (roll, month, amount) VALUES (1, 'Aug', 1500), (1, 'Sep', 1500), (2, 'Aug', 1500), (3, 'Aug', 750);8""")9q = """SELECT s.name, COUNT(f.id) AS payments, SUM(f.amount) AS paid10 FROM students s JOIN fees f ON s.roll = f.roll11 GROUP BY s.roll ORDER BY paid DESC"""12for name, n, paid in con.execute(q):13 print(f"{name:<6} {n} payment(s) Rs {paid}")
? placeholders and commitinit_db() creates the tableadd_student(name, cls, marks) inserts with ? placeholdersfind(name) returns a row or Nonetop(n) returns the best n students1import sqlite32con = sqlite3.connect("students.db")3con.row_factory = sqlite3.Row45def init_db():6 con.execute("DROP TABLE IF EXISTS students")7 con.execute("CREATE TABLE students (roll INTEGER PRIMARY KEY, name TEXT, cls TEXT, marks INTEGER)")89def add_student(name, cls, marks):10 with con: # auto-commit11 con.execute("INSERT INTO students (name, cls, marks) VALUES (?, ?, ?)", (name, cls, marks))1213def find(name):14 return con.execute("SELECT * FROM students WHERE name = ?", (name,)).fetchone()1516def top(n=3):17 return con.execute("SELECT name, marks FROM students ORDER BY marks DESC LIMIT ?", (n,)).fetchall()1819init_db()20for s in [("Aman", "9A", 78), ("Priya", "9A", 92), ("Rahul", "9B", 65), ("Sneha", "9B", 88)]:21 add_student(*s)22r = find("Sneha")23print("Found:", dict(r) if r else None)24print("Missing:", find("Zara"))25print("Top 2:", [tuple(x) for x in top(2)])
books and issuesissue(book_id, member) checks availability firstreturn_book(book_id) sets returned = 11import sqlite32con = sqlite3.connect(":memory:")3con.executescript("""4CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT);5CREATE TABLE issues (id INTEGER PRIMARY KEY, book_id INTEGER, member TEXT, returned INTEGER DEFAULT 0);6INSERT INTO books (title) VALUES ('Wings of Fire'), ('Godan'), ('Malgudi Days');7""")89def is_out(book_id):10 return con.execute("SELECT 1 FROM issues WHERE book_id = ? AND returned = 0", (book_id,)).fetchone() is not None1112def issue(book_id, member):13 if is_out(book_id):14 return print(f"Book {book_id} is already issued")15 con.execute("INSERT INTO issues (book_id, member) VALUES (?, ?)", (book_id, member))16 print(f"Book {book_id} issued to {member}")1718def return_book(book_id):19 con.execute("UPDATE issues SET returned = 1 WHERE book_id = ? AND returned = 0", (book_id,))20 print(f"Book {book_id} returned")2122issue(1, "Asha"); issue(1, "Vikas"); issue(2, "Vikas"); return_book(1); issue(1, "Vikas")23print("Currently issued:")24for title, member in con.execute("SELECT b.title, i.member FROM issues i JOIN books b ON b.id = i.book_id WHERE i.returned = 0"):25 print(f" {title:<15} -> {member}")
items(name, qty, min_qty, price)sell(name, n) reduces qty only if enough stockqty < min_qtySUM(qty * price)1import sqlite32con = sqlite3.connect(":memory:")3con.execute("CREATE TABLE items (name TEXT PRIMARY KEY, qty INTEGER, min_qty INTEGER, price REAL)")4con.executemany("INSERT INTO items VALUES (?, ?, ?, ?)", [("Rice 5kg", 20, 5, 320), ("Dal 1kg", 8, 6, 128), ("Oil 1L", 12, 4, 175), ("Sugar 1kg", 15, 5, 46)])56def sell(name, n):7 cur = con.execute("UPDATE items SET qty = qty - ? WHERE name = ? AND qty >= ?", (n, name, n))8 print(f"{'Sold' if cur.rowcount else 'NOT enough'}: {n} x {name}")910for name, n in [("Dal 1kg", 3), ("Oil 1L", 9), ("Rice 5kg", 30), ("Sugar 1kg", 11)]:11 sell(name, n)1213print("Reorder list:")14for name, qty, mn in con.execute("SELECT name, qty, min_qty FROM items WHERE qty < min_qty"):15 print(f" {name:<10} only {qty} left (min {mn})")16value = con.execute("SELECT SUM(qty * price) FROM items").fetchone()[0]17print(f"Stock value: Rs {value:,.2f}")
LIKE ? with f"%{word}%" as the parameter (safe!)1import sqlite32con = sqlite3.connect(":memory:")3con.execute("CREATE TABLE parents (name TEXT, area TEXT, phone TEXT)")4con.executemany("INSERT INTO parents VALUES (?, ?, ?)", [5 ("Sunil Mahto", "Kanke", "98350 10001"), ("Rekha Devi", "Hinoo", "98350 10002"), ("Mohan Lal", "Doranda", "98350 10003"),6 ("Sunita Kujur", "Bariatu", "98350 10004"), ("Irfan Ansari", "Hinoo", "98350 10005"), ("Sunny Singh", "Lalpur", "98350 10006"),7 ("Anita Tirkey", "Kanke", "98350 10007"), ("Rakesh Oraon", "Ratu", "98350 10008")])89for word in [input("Search name or area: "), input("Search again: ")]:10 rows = con.execute("SELECT name, area, phone FROM parents WHERE name LIKE ? OR area LIKE ? ORDER BY name",11 (f"%{word}%", f"%{word}%")).fetchall()12 print(f"Results for '{word}':" if rows else f"No match for '{word}'")13 for r in rows:14 print(f" {r[0]:<14} {r[1]:<8} {r[2]}")
products(id, name, price) and orders(product_id, qty, month)1import sqlite32con = sqlite3.connect(":memory:")3con.executescript("""4CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price INTEGER);5CREATE TABLE orders (product_id INTEGER, qty INTEGER, month TEXT);6INSERT INTO products VALUES (1,'Earphones',799),(2,'Charger',549),(3,'Phone cover',299),(4,'Power bank',1299);7INSERT INTO orders VALUES (1,12,'Jul'),(2,20,'Jul'),(3,35,'Jul'),(4,6,'Jul'),(1,18,'Aug'),(2,15,'Aug'),8 (3,40,'Aug'),(4,11,'Aug'),(1,25,'Sep'),(2,22,'Sep'),(3,28,'Sep'),(4,14,'Sep');9""")10JOIN = "FROM orders o JOIN products p ON p.id = o.product_id"11print("Month Revenue")12for m, rev in con.execute(f"SELECT month, SUM(o.qty * p.price) {JOIN} GROUP BY month ORDER BY MIN(o.rowid)"):13 print(f"{m:<6} Rs {rev:>8,} {'#' * (rev // 5000)}")14name, units, rev = con.execute(f"SELECT p.name, SUM(o.qty), SUM(o.qty * p.price) AS r {JOIN} GROUP BY p.id ORDER BY r DESC LIMIT 1").fetchone()15print(f"Best seller: {name} ({units} units, Rs {rev:,})")
INSERT, SELECT, UPDATE, DELETE (always use WHERE with update/delete)sqlite3.connect(), execute(), commit(), fetchall()? placeholders, never f-stringsWHERE, ORDER BY, LIMIT, LIKE filter and sort; GROUP BY with COUNT/SUM/AVG summarisesJOIN ... ON combines related tablesWhich SQL command reads data?
What happens if you forget con.commit() after INSERT?
Safest way to use user input in SQL?
1import numpy as np23marks = np.array([78, 92, 65, 88, 45, 81])4print(marks + 5) # add 5 to every item5print(marks / 100 * 80) # convert out of 806print(marks[marks >= 80]) # filter with a condition7print("mean", marks.mean(), "max", marks.max(), "std", round(marks.std(), 1))89grid = np.array([[78, 85, 72], [95, 91, 88]])10print(grid.shape, grid.sum(axis=1)) # total per student (row)1112print(np.arange(0, 1, 0.25), np.zeros(3), np.random.default_rng(1).integers(1, 7, 5))
[m + 5 for m in marks]marks + 5| Code | Means |
|---|---|
np.array(list) | make an array |
a + 5, a * 2 | maths on every item |
a[a > 80] | filter (boolean mask) |
a.mean() .max() .sum() | statistics |
a.shape | size (rows, cols) |
pip install numpy pandas matplotlib. In the Lab they load automatically (first time takes a while).1import pandas as pd23df = pd.read_csv("results.csv")4print(df.head(4))5print("Shape:", df.shape)6print(df["maths"].mean())7print(df.describe().loc[["mean", "max"]].round(1))
1name,section,maths,science,english,hindi2Aman,A,78,85,72,803Priya,A,95,91,88,844Rahul,B,65,58,70,625Sneha,B,88,92,79,906Kiran,A,45,52,61,587Imran,B,81,77,85,748Ritu,A,92,89,94,919Deepak,B,38,44,50,47
| Code | Shows |
|---|---|
df.head(n) | first n rows |
df.shape | (rows, columns) |
df["col"] | one column (a Series) |
df.describe() | count, mean, min, max... |
df.info() | column types, missing values |
1import pandas as pd2df = pd.read_csv("results.csv")34print(df[["name", "maths"]].head(3))5print()6toppers = df[df["maths"] >= 85]7print(toppers[["name", "section", "maths"]])8print()9sec_b_pass = df[(df["section"] == "B") & (df["english"] >= 60)]10print(list(sec_b_pass["name"]))11print(df.sort_values("science", ascending=False)["name"].head(3).tolist())
| Task | Code |
|---|---|
| some columns | df[["name", "maths"]] |
| filter rows | df[df["maths"] >= 85] |
| two conditions | df[(cond1) & (cond2)] |
| sort | df.sort_values("col", ascending=False) |
| one cell | df.loc[0, "name"] |
& and | (not and / or) and put each condition in brackets.1import pandas as pd2df = pd.read_csv("results.csv")34subjects = ["maths", "science", "english", "hindi"]5df["total"] = df[subjects].sum(axis=1)6df["percent"] = df["total"] / 47df["result"] = df["percent"].apply(lambda p: "PASS" if p >= 50 else "RETEST")8print(df[["name", "total", "percent", "result"]].sort_values("total", ascending=False).to_string(index=False))9print()10print(df.groupby("section")[subjects].mean().round(1))11print(df["result"].value_counts().to_dict())
df["total"] = ...apply() runs a function on each valuegroupby("section") + mean() = one row per sectionvalue_counts() counts each category1import pandas as pd2df = pd.read_csv("admissions.csv")3print("Before:", df.shape)45df["name"] = df["name"].str.strip().str.title()6df["city"] = df["city"].str.strip().str.title()7df["age"] = pd.to_numeric(df["age"], errors="coerce") # "abc" -> NaN8df["fee_paid"] = df["fee_paid"].fillna(0)9df = df.drop_duplicates()10df = df.dropna(subset=["age"])1112print("After:", df.shape)13print(df.to_string(index=False))14print("Unpaid:", df[df["fee_paid"] == 0]["name"].tolist())
1name,age,city,fee_paid2Aman,15,Ranchi,45003priya ,14,dhanbad,45004Rahul,,Ranchi,5Sneha,15, Bokaro ,45006Aman,15,Ranchi,45007Kiran,16,RANCHI,30008Imran,abc,Jamshedpur,4500
| Problem | Fix |
|---|---|
| extra spaces / mixed case | .str.strip().str.title() |
| text in a number column | pd.to_numeric(..., errors="coerce") |
| blank values | fillna() or dropna() |
| repeated rows | drop_duplicates() |
1import matplotlib.pyplot as plt23months = ["Jun", "Jul", "Aug", "Sep", "Oct"]4rain_mm = [210, 320, 300, 230, 70] # sample data5visitors = [12, 26, 30, 22, 15] # thousands at Hundru Falls (sample)67fig, (a, b) = plt.subplots(1, 2, figsize=(9, 3.2))8a.plot(months, rain_mm, marker="o", color="#1971c2")9a.set_title("Ranchi monthly rainfall (mm)")10b.bar(months, visitors, color="#2f9e44")11b.set_title("Tourists (thousands)")12for ax in (a, b):13 ax.grid(alpha=0.3)14plt.tight_layout()15plt.savefig("charts.png", dpi=80)16print("Saved charts.png")
| Chart | Function | Best for |
|---|---|---|
| line | plt.plot(x, y) | change over time |
| bar | plt.bar(x, h) | compare categories |
| pie | plt.pie(values) | parts of a whole |
| histogram | plt.hist(data) | distribution |
| scatter | plt.scatter(x, y) | relationship |
plt.show() on your computer to open a window, or savefig to save an image for a report.1import pandas as pd2import matplotlib.pyplot as plt34df = pd.read_csv("sales.csv", parse_dates=["date"])5df["revenue"] = df["qty"] * df["price"]6monthly = df.groupby(df["date"].dt.strftime("%b"), sort=False)["revenue"].sum()7by_branch = df.pivot_table(index="branch", columns="product", values="revenue", aggfunc="sum", fill_value=0)8print(monthly)9print(by_branch)1011ax = by_branch.plot(kind="bar", stacked=True, figsize=(6, 3.2), title="Revenue by branch")12ax.set_ylabel("Rs")13plt.tight_layout()14plt.savefig("branch.png", dpi=80)15by_branch.to_excel("branch_report.xlsx") # needs: pip install openpyxl
english column and include it in the averagegrade column using applyresults.csv for 8 students. Produce the analysis the principal asked for.rank(ascending=False)pd.cut1import pandas as pd2df = pd.read_csv("results.csv")3subs = ["maths", "science", "english", "hindi"]4df["percent"] = df[subs].mean(axis=1)5df["rank"] = df["percent"].rank(ascending=False).astype(int)6print(df.sort_values("rank")[["rank", "name", "section", "percent"]].to_string(index=False))7print("Best subject:", df[subs].mean().idxmax(), round(df[subs].mean().max(), 1))8bands = pd.cut(df["percent"], bins=[0, 50, 75, 90, 100], labels=["Retest", "Good", "Very good", "Excellent"])9print(bands.value_counts().sort_index().to_dict())
1import pandas as pd2import matplotlib.pyplot as plt34months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]5rain = [18, 22, 25, 30, 65, 220, 330, 305, 240, 85, 12, 8] # sample values (mm)6df = pd.DataFrame({"month": months, "rain": rain})7df["monsoon"] = df["month"].isin(["Jun", "Jul", "Aug", "Sep"])89colors = ["#1971c2" if m else "#adb5bd" for m in df["monsoon"]]10plt.figure(figsize=(7, 3))11plt.bar(df["month"], df["rain"], color=colors)12plt.title("Ranchi monthly rainfall (sample data)")13plt.ylabel("mm")14plt.tight_layout()15plt.savefig("rainfall.png", dpi=80)1617share = df[df["monsoon"]]["rain"].sum() / df["rain"].sum() * 10018print(f"Yearly total: {df['rain'].sum()} mm, monsoon share: {share:.0f}%")19print("Wettest month:", df.loc[df["rain"].idxmax(), "month"])
sales.csv: revenue by month, branch and product.parse_dates and add a revenue column1import pandas as pd2import matplotlib.pyplot as plt34df = pd.read_csv("sales.csv", parse_dates=["date"])5df["revenue"] = df["qty"] * df["price"]6df["month"] = df["date"].dt.strftime("%b")7monthly = df.groupby("month", sort=False)["revenue"].sum()8branch = df.groupby("branch")["revenue"].sum().sort_values(ascending=False)9product = df.groupby("product")["revenue"].sum().sort_values()1011print("Monthly:", monthly.to_dict())12print("Best branch:", branch.index[0], f"Rs {branch.iloc[0]:,}")13print("Best product:", product.index[-1], f"Rs {product.iloc[-1]:,}")1415fig, (a, b) = plt.subplots(1, 2, figsize=(9, 3))16monthly.plot(ax=a, marker="o", title="Revenue by month")17product.plot(ax=b, kind="barh", color="#2f9e44", title="Revenue by product")18plt.tight_layout()19plt.savefig("dashboard.png", dpi=80)
1import pandas as pd2df = pd.read_csv("admissions.csv")3rows_before = len(df)4for col in ["name", "city"]:5 df[col] = df[col].str.strip().str.title()6df["age"] = pd.to_numeric(df["age"], errors="coerce")7df["fee_paid"] = df["fee_paid"].fillna(0).astype(int)8df = df.drop_duplicates()9bad_age = df[df["age"].isna()]["name"].tolist()1011print(f"Rows: {rows_before} -> {len(df)}")12print(df.to_string(index=False))13print("City counts:", df["city"].value_counts().to_dict())14print("Check age for:", bad_age)15print("Fee defaulters:", df[df["fee_paid"] < 4500]["name"].tolist())
1import pandas as pd2import matplotlib.pyplot as plt34entries = [("Rent", 8500), ("Groceries", 3200), ("Groceries", 1450), ("School fees", 2500), ("Electricity", 1180),5 ("Transport", 900), ("Groceries", 980), ("Mobile & net", 699), ("Transport", 650), ("Medicines", 540)]6df = pd.DataFrame(entries, columns=["category", "amount"])7totals = df.groupby("category")["amount"].sum().sort_values(ascending=False)8pct = (totals / totals.sum() * 100).round(1)9print(pd.DataFrame({"Rs": totals, "%": pct}))10print("Total spent: Rs", totals.sum())1112plt.figure(figsize=(5, 3.4))13plt.pie(totals, labels=totals.index, autopct="%1.0f%%", startangle=90)14plt.title("Where the money goes")15plt.tight_layout()16plt.savefig("expenses.png", dpi=80)
marks + 5, a[a > 80]read_csv, head, df["col"], filter with df[cond], sort_valuesapply, groupby().mean(), value_counts(), pivot_tablestr.strip/title, to_numeric, fillna, drop_duplicatesplot, bar, pie, hist; savefig or showto_csv / to_excel for reportsRows where maths > 80?
Average marks per section?
Best chart for parts of a whole?
| Method | Used to |
|---|---|
GET | read data (open a page, fetch weather) |
POST | send new data (submit a form, place an order) |
PUT / PATCH | update data |
DELETE | remove data |
| Status | Means |
|---|---|
| 200 OK | success |
| 201 Created | new item saved |
| 400 Bad Request | your data was wrong |
| 401 / 403 | login needed / not allowed |
| 404 Not Found | no such page or item |
| 500 | server error |
1import requests23url = "https://api.open-meteo.com/v1/forecast"4params = {"latitude": 23.34, "longitude": 85.31,5 "current": "temperature_2m,relative_humidity_2m,wind_speed_10m", "timezone": "Asia/Kolkata"}6r = requests.get(url, params=params, timeout=10)7print("Status:", r.status_code)89data = r.json() # JSON text -> Python dict10now = data["current"]11print(f"Ranchi now: {now['temperature_2m']} C, humidity {now['relative_humidity_2m']}%, wind {now['wind_speed_10m']} km/h")12print("Keys in the response:", list(data.keys()))
pip install requests (once)requests.get(url, params=...) sends the requestr.status_code: did it work?r.json() turns the JSON into a dict you can indextimeout. Without it, a slow server can freeze your program.1import requests23def get_user(uid):4 try:5 r = requests.get(f"https://api.example.com/users/{uid}", timeout=5)6 r.raise_for_status() # 4xx/5xx -> exception7 return r.json()8 except requests.exceptions.Timeout:9 print("Server too slow, try later")10 except requests.exceptions.HTTPError as e:11 print("HTTP problem:", e)12 except requests.exceptions.RequestException as e:13 print("Network problem:", e)14 return None1516print(get_user(1))17print(get_user(99))18try:19 requests.get("https://api.example.com/slow", timeout=2)20except requests.exceptions.Timeout as e:21 print("Timeout:", e)
1from bs4 import BeautifulSoup23html = """4<html><body>5 <h1>Jharkhand Tourism</h1>6 <ul class="spots">7 <li data-km="45">Hundru Falls</li>8 <li data-km="40">Dassam Falls</li>9 <li data-km="156">Netarhat</li>10 </ul>11 <a href="/booking">Book a tour</a>12</body></html>13"""14soup = BeautifulSoup(html, "html.parser")15print(soup.h1.text)16for li in soup.select("ul.spots li"):17 print(f"{li.text:<14} {li['data-km']} km from Ranchi")18print("Link:", soup.find("a")["href"])
requests.get(url).text)BeautifulSoup(html, "html.parser")find, find_all or CSS select.text and attributes like ["href"]pip install beautifulsoup4)1from flask import Flask23app = Flask(__name__)45@app.route("/")6def home():7 return "<h1>Welcome to BrainBit Infotech Pvt Ltd</h1><p>Python batch starts 15 October.</p>"89@app.route("/about")10def about():11 return "<h2>About us</h2><p>Computer training centre in Ranchi since 2010.</p>"1213@app.route("/student/<name>")14def student(name):15 return f"<h2>Hello, {name.title()}!</h2><p>Your profile page.</p>"1617if __name__ == "__main__":18 app.run(debug=True)
@app.route("/") connects a URL to a function. Whatever the function returns is sent to the browser. Open http://127.0.0.1:5000 after running.1from flask import Flask, render_template_string23app = Flask(__name__)4RESULTS = {"aman": 412, "priya": 468, "rahul": 301}56PAGE = """7<h2>Class 9A Results</h2>8<table border="1" cellpadding="6">9 <tr><th>Name</th><th>Marks</th><th>Result</th></tr>10 {% for name, m in results.items() %}11 <tr><td>{{ name.title() }}</td><td>{{ m }}</td>12 <td>{{ "PASS" if m >= 165 else "FAIL" }}</td></tr>13 {% endfor %}14</table>15<p>Total students: {{ results|length }}</p>16"""1718@app.route("/results")19def results():20 return render_template_string(PAGE, results=RESULTS)
| Template code | Means |
|---|---|
{{ value }} | print a value |
{% for x in list %} | loop |
{% if cond %} | condition |
|length | a filter |
templates/ folder and you call render_template("results.html", ...).1from flask import Flask, request23app = Flask(__name__)4MARKS = {"101": ("Aman", 412), "102": ("Priya", 468)}56@app.route("/", methods=["GET", "POST"])7def lookup():8 msg = ""9 if request.method == "POST":10 roll = request.form.get("roll", "").strip()11 if roll in MARKS:12 name, m = MARKS[roll]13 msg = f"<p><b>{name}</b> scored {m}/500 ({m / 5:.1f}%)</p>"14 else:15 msg = "<p style='color:red'>Roll number not found</p>"16 return f"""<h3>Result Lookup</h3>17 <form method="post"><input name="roll" placeholder="Roll no">18 <button>Check</button></form>{msg}"""
methods=["GET", "POST"] allows bothrequest.form.get("roll") reads the typed value1from flask import Flask, jsonify, request23app = Flask(__name__)4books = [{"id": 1, "title": "Wings of Fire", "available": True},5 {"id": 2, "title": "Godan", "available": False}]67@app.get("/api/books")8def list_books():9 return jsonify(books)1011@app.get("/api/books/<int:book_id>")12def one_book(book_id):13 for b in books:14 if b["id"] == book_id:15 return jsonify(b)16 return jsonify({"error": "not found"}), 4041718@app.post("/api/books")19def add_book():20 data = request.get_json()21 book = {"id": len(books) + 1, "title": data["title"], "available": True}22 books.append(book)23 return jsonify(book), 201
fetch(). Status 201 = created, 404 = not found.max(..., key=...)json.dumps(data, indent=2)pip install requests flask and try the slides' codeparams and timeout1import requests23CITIES = {"Ranchi": (23.34, 85.31), "Jamshedpur": (22.80, 86.18), "Dhanbad": (23.80, 86.43), "Netarhat": (23.47, 84.27)}4URL = "https://api.open-meteo.com/v1/forecast"56print(f"{'City':<11}{'Temp':>6}{'Hum':>6} Tip")7for city, (lat, lon) in CITIES.items():8 r = requests.get(URL, params={"latitude": lat, "longitude": lon, "current": "temperature_2m,relative_humidity_2m"}, timeout=10)9 if r.status_code != 200:10 print(city, "unavailable")11 continue12 cur = r.json()["current"]13 t, h = cur["temperature_2m"], cur["relative_humidity_2m"]14 tip = "carry a jacket" if t < 20 else "umbrella!" if h > 85 else "nice weather"15 print(f"{city:<11}{t:>5}C{h:>5}% {tip}")
1import requests23try:4 r = requests.get("https://api.example-rates.com/latest", params={"base": "INR"}, timeout=10)5 r.raise_for_status()6 rates = r.json()["rates"]7except requests.exceptions.RequestException as e:8 print("Could not get rates:", e)9 rates = {}1011amount = float(input("Amount in rupees: "))12print(f"Rs {amount:,.0f} on {r.json()['date']} =")13for code, rate in sorted(rates.items()):14 print(f" {code} {amount * rate:>12,.2f}")
/course/<key>1from flask import Flask23app = Flask(__name__)4COURSES = {"python": "Python Programming (3 months)", "web": "HTML, CSS & JavaScript (3 months)", "excel": "Advanced Excel (1 month)"}56@app.route("/")7def home():8 links = "".join(f'<li><a href="/course/{k}">{v}</a></li>' for k, v in COURSES.items())9 return f"<h1>BrainBit Infotech Pvt Ltd</h1><h3>Our courses</h3><ul>{links}</ul>"1011@app.route("/course/<key>")12def course(key):13 if key not in COURSES:14 return "<h3>Course not found</h3>", 40415 return f"<h2>{COURSES[key]}</h2><p>Batches every month. Call 98350 00000.</p><a href='/'>Back</a>"1617if __name__ == "__main__":18 app.run(debug=True)
request.args.get("q") from the URL (?q=...)1from flask import Flask, request, render_template_string23app = Flask(__name__)4STUDENTS = [("Aman", "9A", 78), ("Priya", "9A", 92), ("Rahul", "9B", 65), ("Sneha", "9B", 88), ("Arif", "9A", 71)]5PAGE = """<h3>Find a student</h3>6<form><input name="q" value="{{ q }}"> <button>Search</button></form>7{% if q %}<p>{{ rows|length }} result(s) for "{{ q }}"</p>8<table border=1 cellpadding=5>{% for n, c, m in rows %}<tr><td>{{ n }}</td><td>{{ c }}</td><td>{{ m }}</td></tr>{% endfor %}</table>{% endif %}"""910@app.route("/")11def search():12 q = request.args.get("q", "").strip()13 rows = [s for s in STUDENTS if q and (q.lower() in s[0].lower() or q.upper() == s[1])]14 return render_template_string(PAGE, q=q, rows=rows)
/api/tasks with optional ?done=true/false/api/tasks/<id> marks it done (404 if missing)1from flask import Flask, jsonify, request23app = Flask(__name__)4tasks = []56@app.get("/api/tasks")7def all_tasks():8 done = request.args.get("done")9 result = tasks if done is None else [t for t in tasks if str(t["done"]).lower() == done]10 return jsonify(result)1112@app.post("/api/tasks")13def add_task():14 data = request.get_json(silent=True) or {}15 if not data.get("title"):16 return jsonify({"error": "title is required"}), 40017 task = {"id": len(tasks) + 1, "title": data["title"], "done": False}18 tasks.append(task)19 return jsonify(task), 2012021@app.patch("/api/tasks/<int:tid>")22def finish(tid):23 for t in tasks:24 if t["id"] == tid:25 t["done"] = True26 return jsonify(t)27 return jsonify({"error": "no such task"}), 404
requests.get(url, params=..., timeout=...) then r.json()Timeout, HTTPError, RequestException; use raise_for_status()find, select, .text, ["href"]@app.route("/path") functions return pages; templates use {{ }} and {% %}request.form / request.args / get_json() read input; jsonify returns JSONWhich HTTP method submits a form to save data?
Status code for "not found"?
In Flask, what connects a URL to a function?
You finished Advanced Python & Data: 4 modules and 20 practice examples.
D:\python-practice\part4