Store many values in lists, tuples, sets and dictionaries, and organise code into reusable functions and modules.
Every code example has a ▶ Run button. Click ✎ Edit & Run, or press L, to open the Python Lab.
D:\python-practice).1students = ["Aman", "Priya", "Rahul", "Sneha"]2marks = [78, 92, 65, 88]3mixed = ["Ranchi", 834001, 23.36, True]4empty = []56print(students)7print(len(students), "students")8print("First:", students[0])9print("Last:", students[-1])10print("Top two:", marks[:2])11print(type(marks))
[ ] and commas. Indexing and slicing work exactly like strings (Module 4).1prices = [40, 60, 25, 90]2print("Before:", prices)34prices[1] = 55 # change item at index 15prices[-1] = prices[-1] - 106print("After :", prices)78name = "Ranchi"9# name[0] = "D" -> TypeError: strings cannot change10letters = list(name) # make a list of characters11letters[0] = "D"12print("".join(letters))
prices[1] = 55.list("abc") is ['a', 'b', 'c'].| Method | Does | Returns |
|---|---|---|
append(x) | add at end | None |
insert(i, x) | add at position | None |
extend(list) | add many | None |
remove(x) | delete by value | None |
pop(i) | delete by index | the item |
clear() | empty the list | None |
remove("Pencil") when "Pencil" is not in the list raises ValueError. Check with if "Pencil" in cart: first.list.sort() changes the list and returns None. sorted(list) returns a new list.1marks = [78, 92, 65, 88, 34, 71]23total = 04for m in marks:5 total += m6average = total / len(marks)7print(f"Total {total}, average {average:.1f}")89passed = []10for m in marks:11 if m >= 40:12 passed.append(m)13print("Passed marks:", passed)1415for i, m in enumerate(marks, start=1):16 print(f"Student {i}: {m}", "*" if m == max(marks) else "")
This "keep the best so far" pattern is how max() works inside. Two lists are linked by the same index.
1names = ["Aman", "Priya", "Rahul"]2marks = [78, 92, 85]3best = 04topper = ""5for i in range(len(marks)):6 if marks[i] > best:7 best = marks[i]8 topper = names[i]9print(topper, "topped with", best)
1seats = [2 ["Aman", "Riya", "Kunal", "Sana"],3 ["Dev", "Isha", "Ravi", "Neha"],4 ["Om", "Tara", "Arif", "Jiya"],5]6print("Row 1, seat 3:", seats[1][2])7seats[2][0] = "Vikas" # Om moved out89for row in seats:10 print(" | ".join(row))
seats[1][2] means: row 1, then item 2 in that row. Spreadsheets, game boards and images are all 2D grids.Watch line 4 carefully. This surprises many beginners (and causes real bugs in apps).
1a = ["Ranchi", "Dhanbad"]2b = a # same list, two names3c = a.copy() # a real copy4b.append("Bokaro")5print("a:", a)6print("b:", b)7print("c:", c)
append to both lists1marks = [67, 89, 45, 92, 78, 56, 83, 71]23highest = max(marks)4lowest = min(marks)5total = sum(marks)6average = total / len(marks)7above = 08for m in marks:9 if m > average:10 above += 11112print(f"Students : {len(marks)}")13print(f"Highest : {highest}")14print(f"Lowest : {lowest}")15print(f"Average : {average:.2f}")16print(f"Above avg: {above}")17print("Ranked :", sorted(marks, reverse=True))
items and priceswhile Trueappend to add and index + pop to remove1items, prices = [], []2while True:3 choice = input("\n1 Add 2 Remove 3 View 4 Checkout: ")4 if choice == "1":5 items.append(input("Item: "))6 prices.append(float(input("Price: ")))7 elif choice == "2":8 name = input("Remove which item? ")9 if name in items:10 i = items.index(name)11 items.pop(i)12 prices.pop(i)13 print(name, "removed")14 else:15 print("Not in cart")16 elif choice == "3":17 print("Cart:", items)18 elif choice == "4":19 for name, p in zip(items, prices):20 print(f"{name:<12} Rs {p:>8.2f}")21 print(f"{'TOTAL':<12} Rs {sum(prices):>8.2f}")22 break
1todo = []2while True:3 task = input("Add task (or 'done'): ")4 if task == "done":5 break6 todo.append(task)78finished = []9num = int(input("Which task number did you finish? "))10finished.append(todo.pop(num - 1))1112print("\nSTILL TO DO:")13for i, t in enumerate(todo, 1):14 print(f" {i}. [ ] {t}")15print("COMPLETED:")16for t in finished:17 print(f" [x] {t}")
zip()sorted(..., key=..., reverse=True)key=lambda p: p[1] means "sort by item 1 of each pair" (the score). You will learn lambda properly in Module 10. [n for n, s in ...] is a list comprehension (Module 16).1names = ["Aditi", "Rohan", "Sahil", "Meera", "Javed", "Pooja"]2scores = [84, 91, 77, 95, 91, 68]34pairs = list(zip(names, scores))5ranked = sorted(pairs, key=lambda p: p[1], reverse=True)6medals = ["Gold", "Silver", "Bronze"]78print("DISTRICT QUIZ - TOP 3")9for medal, (name, score) in zip(medals, ranked[:3]):10 print(f"{medal:<7} {name:<8} {score}")11print("Others:", [n for n, s in ranked[3:]])
1rolls = list(range(101, 113))2rows, cols = 3, 43hall = []4k = 05for r in range(rows):6 row = []7 for c in range(cols):8 row.append(rolls[k])9 k += 110 hall.append(row)1112for r, row in enumerate(hall):13 print("ABC"[r], row)1415find = int(input("Find roll number: "))16for r in range(rows):17 if find in hall[r]:18 print(f"Seat: {'ABC'[r]}{hall[r].index(find) + 1}")19print("Seats used:", sum(len(row) for row in hall))
[1, 2, 3]; index from 0lst[i] = xappend, insert, extend; remove: remove, pop, del, clearsort() changes the list; sorted() returns a new onesum, min, max, len, in, count, index answer questions about a listb = a shares the list; use a.copy() for a real copyx = [5, 8, 2]; x.append(4). What is x?
[10, 20, 30][-1] is?
Which returns a NEW sorted list?
1ranchi = (23.34, 85.31) # (latitude, longitude)2rgb_green = (0, 128, 0)3exam_date = (2026, 3, 15)4single = ("Ranchi",) # one item needs a comma!56print("Ranchi is at", ranchi)7print("Latitude:", ranchi[0])8print("Year:", exam_date[0], "Month:", exam_date[1])9print(len(rgb_green), type(single))1011ranchi[0] = 10 # try to change it
( ). Indexing, slicing, len, in and loops work like lists.("Ranchi") is just a string in brackets. A one-item tuple needs a trailing comma: ("Ranchi",).Unpacking is used everywhere: looping over pairs, reading coordinates, and getting several return values from a function.
1city = ("Jamshedpur", 1.34, "Steel City") # packing2name, population, nickname = city # unpacking3print(name, "is called the", nickname)45lat, lon = (22.80, 86.18)6first, *rest = [5, 10, 15, 20]7print(first, rest)
| List [ ] | Tuple ( ) | |
|---|---|---|
| Can change? | Yes (mutable) | No (immutable) |
| Typical data | cart items, marks, tasks | coordinates, dates, RGB, records |
| Methods | many (append, sort...) | only count, index |
| Speed / memory | a little more | a little less |
| Dictionary key? | No | Yes |
1visitors = ["amit", "riya", "amit", "john", "riya", "amit"]2unique = set(visitors)3print("All visits :", len(visitors))4print("Unique people:", len(unique))5print(unique)67tags = {"python", "ranchi", "coding"}8tags.add("jharkhand")9tags.add("python") # already there: ignored10tags.discard("coding")11print(sorted(tags))12print("python" in tags)
{"a", "b"} makes a set. set(list) removes duplicates from a list.tags[0] is an error. The printed order may look random; use sorted() for display.x in big_set is super fast even with millions of items.{} is an empty dictionary, not a set. An empty set is set().1A = {"Cricket", "Chess", "Football", "Kabaddi"}2B = {"Hockey", "Archery", "Football", "Kabaddi"}34print(A | B) # union5print(A & B) # intersection6print(A - B) # difference7print(A ^ B) # symmetric difference
| Operator | Method | Meaning |
|---|---|---|
| | union | all items |
& | intersection | common |
- | difference | only in first |
^ | symmetric_difference | not common |
1class_list = {"Aman", "Priya", "Rahul", "Sneha", "Kiran", "Farhan"}2submitted = {"Priya", "Sneha", "Farhan", "Guest01"}34not_submitted = class_list - submitted5unknown = submitted - class_list67print("Pending :", sorted(not_submitted))8print("Unknown :", sorted(unknown))9print("Done :", len(class_list & submitted), "of", len(class_list))
wednesday set and find students who came all three dayshundru[0] and read the error(dx**2 + dy**2) ** 0.51ranchi = (23.34, 85.31)2cities = [3 ("Jamshedpur", 22.80, 86.18),4 ("Dhanbad", 23.80, 86.43),5 ("Bokaro", 23.67, 86.15),6 ("Deoghar", 24.48, 86.70),7]8print(f"{'City':<12}{'Lat':>7}{'Lon':>8}{'~km':>7}")9for name, lat, lon in cities:10 dy = (lat - ranchi[0]) * 11111 dx = (lon - ranchi[1]) * 11112 km = (dx ** 2 + dy ** 2) ** 0.513 print(f"{name:<12}{lat:>7}{lon:>8}{km:>7.0f}")
max(set, key=log.count)1log = ["u12", "u07", "u12", "u33", "u07", "u12", "u45", "u33", "u12"]23unique = set(log)4top = max(unique, key=log.count)56print("Total visits :", len(log))7print("Unique visitors :", len(unique))8print("Visitor IDs :", sorted(unique))9print(f"Most active : {top} ({log.count(top)} visits)")
1aman = {"Riya", "Kunal", "Sana", "Dev", "Isha"}2riya = {"Aman", "Kunal", "Isha", "Tara", "Omkar"}34mutual = aman & riya5suggest = riya - aman - {"Aman"}67print(f"Mutual friends ({len(mutual)}):", ", ".join(sorted(mutual)))8print("People Aman may know:", ", ".join(sorted(suggest)))9print("All friends together:", len(aman | riya))
issubset() to check the core subjects are includedadd()1core = {"English", "Physics", "Chemistry"}2neha = {"English", "Physics", "Chemistry", "Maths", "Computer Science"}3irfan = {"English", "Physics", "Chemistry", "Biology", "Hindi"}45print("Common :", sorted(neha & irfan))6print("Only Neha :", sorted(neha - irfan))7print("Only Irfan :", sorted(irfan - neha))8print("Neha has core subjects? ", core.issubset(neha))910irfan.add("Physical Education")11print("Irfan now takes", len(irfan), "subjects")
set()random.sample(sorted(unique), 3)1import random2entries = [1021, 1088, 1021, 1105, 1130, 1088, 1177, 1202, 1130, 1251]3unique = set(entries)4print(f"Entries: {len(entries)}, unique: {len(unique)}")56winners = tuple(random.sample(sorted(unique), 3))7print("Winners (1st, 2nd, 3rd):", winners)8first, second, third = winners9print(f"First prize goes to coupon {first}!")
( ): ordered, cannot change; great for fixed recordslat, lon = point; *rest collects the rest{ }: unique items, no order, no index; set() removes duplicates| & - ^ (union, intersection, difference, symmetric)set(), not {}len(set([1, 1, 2, 3, 3])) is?
Which creates a tuple with ONE item?
{1, 2, 3} & {2, 3, 4} gives?
{"name": ..., "price": ..., "stock": ...}A list finds items by position (0, 1, 2...). A dictionary finds values by a key you choose, like a word in a real dictionary or a name in your contacts.
1student = {2 "name": "Priya Kumari",3 "class": 10,4 "city": "Ranchi",5 "marks": [88, 92, 79],6}7print(student["name"])8print("Maths:", student["marks"][1])9print(student.get("city"))10print(student.get("phone")) # missing key -> None11print(student.get("phone", "not given")) # default value12print(len(student), "keys")13print(student["phone"]) # missing key -> error
.get() to stay safe.| Code | Effect |
|---|---|
d[k] = v | add new or update existing |
d.update(other) | add / update many |
d.pop(k) | remove, return value |
del d[k] | remove |
k in d | is the key present? |
d.clear() | remove everything |
in checks keys, not values: "Tea" in prices is True, 12 in prices is False.1stock = {"Rice": 40, "Dal": 12, "Sugar": 0, "Oil": 7}23for item in stock: # keys4 print(item, end=" ")5print()67print(list(stock.values())) # values89for item, qty in stock.items(): # key AND value10 status = "OUT OF STOCK" if qty == 0 else f"{qty} left"11 print(f"{item:<6} {status}")1213print("Total units:", sum(stock.values()))
| Method | Gives you |
|---|---|
d.keys() | all keys |
d.values() | all values |
d.items() | (key, value) pairs |
for k, v in d.items(): is the most used dictionary loop in Python.This "count with a dictionary" pattern is one of the most useful in programming: votes, words, sales per product, visits per city.
1votes = ["Tiger", "Elephant", "Tiger", "Peacock", "Tiger", "Elephant"]2count = {}3for animal in votes:4 if animal in count:5 count[animal] += 16 else:7 count[animal] = 18winner = max(count, key=count.get)9print(count)10print("State animal poll winner:", winner)
1students = [2 {"roll": 1, "name": "Aman", "marks": 78, "city": "Ranchi"},3 {"roll": 2, "name": "Priya", "marks": 92, "city": "Dhanbad"},4 {"roll": 3, "name": "Rahul", "marks": 65, "city": "Ranchi"},5]67print(f"{'Roll':<5}{'Name':<8}{'Marks':>6} City")8for s in students:9 print(f"{s['roll']:<5}{s['name']:<8}{s['marks']:>6} {s['city']}")1011ranchi = [s["name"] for s in students if s["city"] == "Ranchi"]12print("From Ranchi:", ranchi)13print("Topper:", max(students, key=lambda s: s["marks"])["name"])
Each dictionary is one row; the keys are the columns. This is exactly how data looks when it comes from a database or an API.
| roll | name | marks | city |
|---|---|---|---|
| 1 | Aman | 78 | Ranchi |
| 2 | Priya | 92 | Dhanbad |
| 3 | Rahul | 65 | Ranchi |
[{"id": 1, "name": "..."}, ...]. You will fetch real JSON in Module 20.1school = {2 "name": "Kendriya Vidyalaya, Hinoo",3 "address": {"city": "Ranchi", "pin": "834002"},4 "classes": {"9A": 42, "9B": 39, "10A": 44},5}6print(school["address"]["city"])7school["classes"]["9B"] += 1 # new admission8print("Total students:", sum(school["classes"].values()))910menu = dict(tea=12, coffee=25) # another way to create11squares = {n: n * n for n in range(1, 6)}12print(menu)13print(squares)
school["address"]["city"]: open the outer dict, then the inner one.{n: n*n for n in range(1, 6)} builds a dict in one line (more in Module 16).popinput() and show "not found" if it is missing.title()1book = {"Aman": "98350 11111", "Priya": "70040 22222", "Rahul": "62000 33333"}23name = input("Search name: ").strip().title()4if name in book:5 print(f"{name}: {book[name]}")6else:7 print(f"{name} not found.")8 book[name] = input(f"Enter {name}'s number to save: ")9 print("Saved!")1011for n, p in sorted(book.items()):12 print(f" {n:<8}{p}")
1prices = {"rice": 64, "atta": 42, "sugar": 46, "oil": 175, "dal": 128}2order = {}3while True:4 item = input("Item (or done): ").lower()5 if item == "done":6 break7 if item not in prices:8 print("Sorry, we do not have", item)9 continue10 order[item] = order.get(item, 0) + int(input("Quantity (kg/L): "))1112total = 013for item, qty in order.items():14 cost = prices[item] * qty15 total += cost16 print(f"{item.title():<7} {qty:>2} x {prices[item]:>4} = {cost:>6}")17print(f"{'TOTAL':<20}= {total:>6}")
replaceget(word, 0) + 1sorted(..., key=..., reverse=True)1speech = """Education is the key to growth. Jharkhand needs education,2skills and jobs. Skills create jobs and jobs create growth."""34text = speech.lower()5for ch in ".,":6 text = text.replace(ch, "")7words = text.split()89freq = {}10for w in words:11 freq[w] = freq.get(w, 0) + 11213top = sorted(freq.items(), key=lambda kv: kv[1], reverse=True)[:5]14print("Total words:", len(words), "| unique:", len(freq))15for word, n in top:16 print(f"{word:<10} {'#' * n} {n}")
{name: {subject: marks}}max(marks, key=marks.get)1report = {2 "Aman": {"Maths": 78, "Science": 85, "English": 72, "Hindi": 80},3 "Priya": {"Maths": 95, "Science": 91, "English": 88, "Hindi": 84},4}5for name, marks in report.items():6 total = sum(marks.values())7 pct = total / (len(marks) * 100) * 1008 best = max(marks, key=marks.get)9 print(f"===== {name} =====")10 for sub, m in marks.items():11 print(f" {sub:<8} {m:>3}")12 print(f" Total {total}, {pct:.1f}% Best: {best}")
.get() to handle unknown districts1districts = {2 "ranchi": {"hq": "Ranchi", "famous": "Hundru Falls", "division": "South Chotanagpur"},3 "east singhbhum": {"hq": "Jamshedpur", "famous": "Jubilee Park", "division": "Kolhan"},4 "dhanbad": {"hq": "Dhanbad", "famous": "Maithon Dam", "division": "North Chotanagpur"},5 "deoghar": {"hq": "Deoghar", "famous": "Baidyanath Temple", "division": "Santhal Pargana"},6 "latehar": {"hq": "Latehar", "famous": "Netarhat", "division": "Palamu"},7}8while True:9 q = input("District (or exit): ").strip().lower()10 if q == "exit":11 break12 info = districts.get(q)13 if info:14 print(f" HQ: {info['hq']} | Famous: {info['famous']} | Division: {info['division']}")15 else:16 print(" Not found. Try:", ", ".join(d.title() for d in districts))
{"name": "Priya"}d[key] (error if missing) or d.get(key, default) (safe)d[key] = value; remove with pop or delfor k, v in d.items():d[x] = d.get(x, 0) + 1d = {"a": 1}; d["b"] = 2. Now len(d)?
Safest way to read a key that may be missing?
for k, v in d.items() gives...
upload_photo() and like_post()calculate_gst() once and uses it on every billbill(40, 3), bill(250, 1)...print(), len(), input(). Now you will make your own.1def greet():2 print("Namaste!")3 print("Welcome to BrainBit Infotech Pvt Ltd")45greet() # call it6greet() # call it again78def greet_student(name, course):9 print(f"Hello {name}, welcome to the {course} course!")1011greet_student("Riya", "Python")12greet_student("Kunal", "Web Design")
def only defines the function; nothing runs yetgreet() runs the indented bodyname, course) receive the arguments ("Riya", "Python")NameError.1def gst_amount(price, rate=18):2 return price * rate / 10034def total_with_gst(price):5 return price + gst_amount(price)67phone_cover = total_with_gst(499)8charger = total_with_gst(899)9print(f"Cover: Rs {phone_cover:.2f}")10print(f"Charger: Rs {charger:.2f}")11print(f"Both: Rs {phone_cover + charger:.2f}")
None and cannot use it.return it. Let the caller decide whether to print.return also ends the function immediately. Lines after it do not run.Watch the purple "Inside area()" box: each call gets its own fresh variables, which disappear when the function returns.
1def area(length, breadth):2 a = length * breadth3 return a45room = area(12, 10)6hall = area(30, 20)7total = room + hall8print("Total floor area:", total, "sq ft")
1def ticket(name, destination="Ranchi", seat_class="Sleeper", passengers=1):2 fare = {"Sleeper": 350, "3AC": 950, "2AC": 1400}[seat_class] * passengers3 print(f"{name}: to {destination}, {seat_class} x{passengers} = Rs {fare}")45ticket("Amit") # uses all defaults6ticket("Neha", "Kolkata") # positional7ticket("Ravi", seat_class="3AC", passengers=2) # keyword arguments8ticket(passengers=3, name="Family", destination="Patna", seat_class="2AC")
destination="Ranchi": used when the caller leaves it out.seat_class="3AC": name the parameter; the order does not matter.def f(a, b=1) is fine, def f(a=1, b) is an error.print(..., sep=" ", end="\n") uses exactly this: defaults you can override by keyword.1def total_marks(*marks):2 print("Received:", marks)3 return sum(marks)45print(total_marks(78, 92))6print(total_marks(65, 70, 88, 91, 59))78def make_profile(name, **details):9 print(f"Profile of {name}")10 for key, value in details.items():11 print(f" {key}: {value}")1213make_profile("Sana", city="Bokaro", hobby="Chess", age=15)
| Syntax | Collects | As a |
|---|---|---|
*args | extra positional values | tuple |
**kwargs | extra name=value pairs | dictionary |
print(*values) and max(*values) work this way. Frameworks like Django and Flask use **kwargs a lot.Variables made inside a function are local. They vanish when the function ends. Global variables live for the whole program.
1shop = "Gupta Stores" # global2count = 034def add_sale(amount):5 tax = amount * 0.18 # local6 global count7 count += 18 return amount + tax910bill = add_sale(200)11bill2 = add_sale(500)12print(shop, "sales:", count, "last bill:", bill2)
1square = lambda x: x * x2print(square(12))34students = [("Aman", 78), ("Priya", 92), ("Rahul", 65)]5by_marks = sorted(students, key=lambda s: s[1], reverse=True)6print(by_marks)78def emi(principal, annual_rate, months):9 """Return the monthly EMI using the standard formula.1011 principal : loan amount in rupees12 annual_rate : yearly interest in percent, e.g. 10.513 months : number of monthly payments14 """15 r = annual_rate / 12 / 10016 return principal * r * (1 + r) ** months / ((1 + r) ** months - 1)1718print(round(emi(100000, 10.5, 12), 2))19print(emi.__doc__.splitlines()[0])
key for sorting, max, min."""...""" text right after def. help(emi) shows it. Professionals document every function.4! = 4 x 3 x 2 x 1. Each call waits for a smaller call. Watch the function frames go deeper, then return one by one.
1def factorial(n):2 if n == 1:3 return 14 return n * factorial(n - 1)56print(factorial(4))
is_pass(pct) that returns True when pct >= 33percentage(45, 50) using a different totalaverage(*nums) that returns the average of any numbersgrade and print grade.__doc__add_gst(price, rate=18) that returns the final priceshow(item, price, rate) that prints one bill lineadd_gst1def add_gst(price, rate=18):2 """Return price including GST."""3 return round(price * (1 + rate / 100), 2)45def show(item, price, rate=18):6 final = add_gst(price, rate)7 print(f"{item:<12} Rs {price:>8.2f} + {rate:>2}% GST = Rs {final:>9.2f}")8 return final910total = 011total += show("Thali", 150, 5)12total += show("Umbrella", 450, 12)13total += show("Earphones", 1299)14print(f"{'GRAND TOTAL':<40} Rs {total:>9.2f}")
rectangle(l, b), circle(r), triangle(base, h)3.14159 for picost(area, rate) for flooring cost1PI = 3.1415923def rectangle(l, b):4 return l * b56def circle(r):7 return PI * r ** 289def triangle(base, height):10 return 0.5 * base * height1112def cost(area, rate_per_sqft=85):13 return area * rate_per_sqft1415jobs = [("Bedroom", rectangle(12, 14)), ("Gazebo", circle(6)), ("Garden plot", triangle(20, 15))]16for name, a in jobs:17 print(f"{name:<12} {a:>8.1f} sq ft Rs {cost(a):>10,.0f}")
check_password(pw) that returns a (score, list_of_problems) tupleisupper(), isdigit()label(score)1def check_password(pw):2 problems = []3 if len(pw) < 8:4 problems.append("at least 8 characters")5 if not any(ch.isupper() for ch in pw):6 problems.append("an UPPER-case letter")7 if not any(ch.isdigit() for ch in pw):8 problems.append("a digit")9 if not any(ch in "!@#$%&*_" for ch in pw):10 problems.append("a special character")11 return 4 - len(problems), problems1213def label(score):14 return "Strong" if score == 4 else "Medium" if score >= 2 else "Weak"1516for pw in ["ranchi", "Ranchi2026", "R@nchi#2026"]:17 score, missing = check_password(pw)18 print(f"{pw:<12} {label(score):<7}", "needs: " + ", ".join(missing) if missing else "")
emi(principal, rate=9.5, years=2) that returns the monthly EMIplan(principal, *tenures) that prints a row for each tenure using *args1def emi(principal, rate=9.5, years=2):2 r = rate / 12 / 1003 n = years * 124 return principal * r * (1 + r) ** n / ((1 + r) ** n - 1)56def plan(principal, *tenures, rate=9.5):7 print(f"Loan Rs {principal:,} at {rate}%")8 for y in tenures:9 m = emi(principal, rate, y)10 interest = m * y * 12 - principal11 print(f" {y} yr: EMI Rs {m:>8,.0f} interest Rs {interest:>8,.0f}")1213plan(85000, 1, 2, 3)14plan(85000, 2, 3, rate=11.0)
factorial(n) with base case n <= 1digit_sum(n): last digit + digit_sum(rest)countdown(n) that prints and calls itself1def factorial(n):2 if n <= 1:3 return 14 return n * factorial(n - 1)56def digit_sum(n):7 if n < 10:8 return n9 return n % 10 + digit_sum(n // 10)1011def countdown(n):12 if n == 0:13 print("Go!")14 return15 print(n, end=" ")16 countdown(n - 1)1718for k in [1, 5, 10]:19 print(f"{k}! = {factorial(k)}")20print("Digit sum of 834001 =", digit_sum(834001))21countdown(5)
def name(params): defines; name(args) callsreturn sends a value back (and ends the function); prefer it over printrate=18 and keyword args f(rate=12) make calls flexible*args = tuple of extra values, **kwargs = dict of extra named valuesglobal rarelylambda x: ... for tiny functions; recursion needs a base caseWhat does a function return if it has no return statement?
def f(a, b=2): return a * b. f(5)?
A recursive function must have a...
pip| Word | Meaning |
|---|---|
| Module | one .py file full of functions and variables |
| Package | a folder of modules (with __init__.py) |
| Standard library | modules that come with Python (math, random...) |
| Third-party | packages you install with pip (pandas, requests...) |
| PyPI | Python Package Index: the online store of packages |
random.py or math.py! Python will import your file instead of the real module.1import math2print(math.sqrt(144))3print(math.pi)45from math import ceil, floor6print(ceil(4.1), floor(4.9))78import datetime as dt9print(dt.date(2026, 10, 8).strftime("%d %B %Y"))1011import random12print(random.choice(["Ranchi", "Dhanbad", "Bokaro"]))
| Style | Use as | When |
|---|---|---|
import math | math.sqrt() | clear where it comes from (best) |
from math import sqrt | sqrt() | a few functions, used often |
import pandas as pd | pd.read_csv() | long names (common convention) |
from math import *: you cannot tell where names come from, and they may overwrite your variables.1import math23print("sqrt(625) =", math.sqrt(625))4print("ceil(7.2) =", math.ceil(7.2), "| floor(7.8) =", math.floor(7.8))5print("pi =", round(math.pi, 5))6print("5! =", math.factorial(5))7print("gcd(48, 36) =", math.gcd(48, 36))8print("2^10 =", math.pow(2, 10))910radius = 711print(f"Area of a 7 m round tank: {math.pi * radius ** 2:.2f} sq m")1213students, bus_capacity = 130, 4014print("Buses needed:", math.ceil(students / bus_capacity))
ceil(3.25) = 4 buses. round would wrongly give 3.sqrt, ceil, floor, pi, factorial, gcd, log, sin, cosmath.1import random23print("Dice:", random.randint(1, 6))4print("Toss:", random.choice(["Heads", "Tails"]))5print("Discount:", round(random.uniform(5, 15), 1), "%")67quiz = ["Q1", "Q2", "Q3", "Q4", "Q5"]8random.shuffle(quiz)9print("Shuffled quiz:", quiz)10print("Pick 2 winners:", random.sample(["Aman", "Riya", "Kunal", "Sana", "Dev"], 2))1112otp = "".join(random.choices("0123456789", k=6))13print("Your OTP:", otp)
| Function | Gives |
|---|---|
randint(a, b) | whole number a..b (both included) |
choice(seq) | one random item |
shuffle(list) | mixes the list in place |
sample(seq, k) | k different items |
choices(seq, k=) | k items, repeats allowed |
secrets module, which is designed for security. random is for games and simulations.1from datetime import date, datetime, timedelta23exam = date(2027, 2, 15)4today = date(2026, 10, 8) # use date.today() in real programs5left = exam - today6print("Days to board exam:", left.days)78due = today + timedelta(days=30)9print("Fee due on:", due.strftime("%d-%m-%Y (%A)"))1011birthday = date(2011, 6, 21)12age = today.year - birthday.year - ((today.month, today.day) < (birthday.month, birthday.day))13print("Age:", age)1415now = datetime(2026, 10, 8, 9, 30)16print(now.strftime("Attendance marked at %I:%M %p on %d %b %Y"))
| Code | Means | Example |
|---|---|---|
%d | day | 08 |
%m / %B / %b | month | 10 / October / Oct |
%Y | year | 2026 |
%A | weekday | Thursday |
%I:%M %p | 12-hour time | 09:30 AM |
timedelta; .days gives the number of days. Used in fee reminders, library fines and countdowns.1"""utils.py - helpers for the BrainBit Infotech billing app"""2GST_RATE = 1834def add_gst(amount, rate=GST_RATE):5 return round(amount * (1 + rate / 100), 2)67def rupees(amount):8 return f"Rs {amount:,.2f}"910if __name__ == "__main__":11 # runs only when utils.py is run directly12 print("Testing utils:", rupees(add_gst(1000)))
1import utils2from utils import rupees34bill = utils.add_gst(2499)5print("Total:", rupees(bill))6print("GST rate used:", utils.GST_RATE)
import utils (no .py). The test line under if __name__ == "__main__": does not run on import.1# Useful pip commands2pip install requests # install3pip install pandas==2.2.3 # exact version4pip install --upgrade pandas # upgrade5pip uninstall tabulate # remove6pip list # what is installed7pip freeze > requirements.txt # save the list for your team
| Package | Used for |
|---|---|
requests | download web pages, call APIs |
pandas, numpy | data analysis |
matplotlib | charts |
flask, django | websites |
openpyxl | Excel files |
pillow | images |
pygame | games |
tabulate | pretty tables in the terminal |
pip is not found on Windows, use py -m pip install name. In Module 22 you will use virtual environments so each project has its own packages.1from tabulate import tabulate23rows = [4 ["Aman", "Ranchi", 78],5 ["Priya", "Dhanbad", 92],6 ["Rahul", "Bokaro", 65],7]8print(tabulate(rows, headers=["Name", "City", "Marks"], tablefmt="grid"))
pip install tabulate oncefrom tabulate import tabulate in your programmath.ceil(95 / 12): how many boxes for 95 eggs, 12 per box?make_otp(length=6) using random.randint(0, 9) in a loop1import random23def make_otp(length=6):4 return "".join(str(random.randint(0, 9)) for _ in range(length))56otp = make_otp()7print(f"SMS: Your BrainBit Infotech login OTP is {otp}. Valid for 5 minutes.")8entered = input("Enter OTP: ")9print("Verified!" if entered == otp else "Wrong OTP. Please try again.")
random.randint(1, 6)1import random2scores = {"Riya": 0, "Kunal": 0}3winner = None4round_no = 05while winner is None:6 round_no += 17 for player in scores:8 roll = random.randint(1, 6)9 scores[player] += roll10 extra = ""11 if roll == 6:12 bonus = random.randint(1, 6)13 scores[player] += bonus14 extra = f" +{bonus} bonus"15 print(f"R{round_no} {player:<6} rolled {roll}{extra:<10} total {scores[player]}")16 if scores[player] >= 20:17 winner = player18 break19print(f"{winner} wins!")
datetime.strptime(text, "%d-%m-%Y").date()1from datetime import datetime, date23today = date(2026, 10, 8) # date.today() in a real app4dob = datetime.strptime(input("Date of birth (DD-MM-YYYY): "), "%d-%m-%Y").date()56age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))7next_bd = dob.replace(year=today.year)8if next_bd < today:9 next_bd = next_bd.replace(year=today.year + 1)1011print("Age:", age, "years")12print("Next birthday:", next_bd.strftime("%d %B %Y, %A"))13print("Days left:", (next_bd - today).days)
school_utils.py write percentage(), grade() and report_line()if __name__ == "__main__":main.py import the module and process 3 students1SCHOOL = "DAV Public School, Ranchi"23def percentage(marks, total=500):4 return marks / total * 10056def grade(pct):7 return "A" if pct >= 80 else "B" if pct >= 60 else "C"89def report_line(name, marks):10 p = percentage(marks)11 return f"{name:<6} {marks:>3} {p:5.1f}% {grade(p)}"1213if __name__ == "__main__":14 print("Self-test:", report_line("Test", 400))
1import school_utils as su23students = {"Aman": 412, "Priya": 468, "Rahul": 301}4print(su.SCHOOL)5for name, marks in students.items():6 print(su.report_line(name, marks))
pip install tabulatetablefmt="github" (Markdown-style)1from tabulate import tabulate23results = {"Ranchi": (5120, 4610), "Dhanbad": (4380, 3820), "Bokaro": (3010, 2755), "Deoghar": (2240, 1890)}4rows = []5for district, (appeared, passed) in results.items():6 rows.append([district, appeared, passed, f"{passed / appeared * 100:.1f}%"])7ta = sum(a for a, p in results.values())8tp = sum(p for a, p in results.values())9rows.append(["TOTAL", ta, tp, f"{tp / ta * 100:.1f}%"])10print(tabulate(rows, headers=["District", "Appeared", "Passed", "Pass %"], tablefmt="github"))
import math, from math import sqrt, import pandas as pdmath (sqrt, ceil), random (randint, choice), datetime (date, timedelta)utils.py in the same folder and import utilsif __name__ == "__main__": runs only when the file is run directlypip install name gets packages from PyPIWhich gives the number of buses for 130 students, 40 per bus?
Command to install the requests package?
random.randint(1, 6) can return 6?
You finished Data Structures & Functions: 5 modules and 25 practice examples.
D:\python-practice\part2