BRAINBIT INFOTECH PVT LTD · RANCHI
COMPLETE PYTHON COURSE · PART 2 OF 5

Data Structures & Functions

Store many values in lists, tuples, sets and dictionaries, and organise code into reusable functions and modules.

5 modules~16.5 hours25 practice examplesNeeds Part 1

By the end of this part you can build

  • A shopping cart and a class marks analyser
  • A phone book and a word-frequency counter
  • Reusable GST, EMI and password functions
  • An OTP generator and your own module

Every code example has a ▶ Run button. Click ✎ Edit & Run, or press L, to open the Python Lab.

ROADMAP FOR THIS PART

Module 7Lists: Store Many Values3.5 h
Module 8Tuples & Sets2.5 h
Module 9Dictionaries: Key-Value Data3.5 h
Module 10Functions: Reusable Blocks of Code4 h
Module 11Modules, Packages & pip3 h
print("Hi") >>> _
PythonBefore we begin

How to Use This Part

Suggested teaching hours per module (Part 2)012343.5 hM72.5 hM83.5 hM94 hM103 hM11

Every module has

  1. 1
    A "Where is it used?" diagram of real projects
  2. 2
    Concept slides with code + terminal: press ▶ Run to watch the output appear
  3. 3
    Step-through animations: watch variables change line by line
  4. 4
    A Live Lab: edit the code and run real Python in the browser
  5. 5
    5 practice examples (Beginner to Advanced) with solutions
  6. 6
    An animated recap + quiz
Controls→ next, ← back, M menu, L Python Lab, F fullscreen. In the Lab, Ctrl+Enter runs the code.
Running PythonOutputs on the slides were produced by real Python 3, so they work offline. The Lab loads Python from the internet the first time (10-40 s). Offline? Use ⬇ .py and run the file in IDLE or VS Code (folder D:\python-practice).
MODULE 7

Lists: Store Many Values

⏱ 3.5 hours5 practice examplesStep-through animationsPython Lab

You will learn

  • Creating lists, len(), indexing and slicing
  • Changing lists: append, insert, remove, pop
  • Sorting, searching and counting
  • Looping over lists with totals and averages
  • Lists of lists (2D) and copying safely

You will build

  • A class marks analyser
  • A shopping cart and a to-do list
  • A classroom seating chart
[ ]marks.append(92)cart[0]
Module 7Real-world use

Where Is This Used in Real Projects?

listmany values, one name🛒Shopping cartitems you add🎵Playlistsongs in order📋Class registerall student names🏆Leaderboardsorted scores✅To-do appsadd, tick, remove💬Chat listnewest first

Real projects that use this

  • Flipkart and Amazon keep your cart as a list: add items, remove items, count items
  • Spotify and YouTube playlists are ordered lists you can shuffle and sort
  • School software stores a list of marks and finds the highest, lowest and average
  • Games keep a sorted list of top scores (leaderboards)
Module 7One name, many values

A List Holds Many Values in Order

main.py  PY
1students = ["Aman", "Priya", "Rahul", "Sneha"]
2marks = [78, 92, 65, 88]
3mixed = ["Ranchi", 834001, 23.36, True]
4empty = []
5
6print(students)
7print(len(students), "students")
8print("First:", students[0])
9print("Last:", students[-1])
10print("Top two:", marks[:2])
11print(type(marks))
Terminal
C:\python-practice> python main.py
['Aman', 'Priya', 'Rahul', 'Sneha']
4 students
First: Aman
Last: Sneha
Top two: [78, 92]
<class 'list'>
students = ['Aman', 'Priya', 'Rahul', 'Sneha']
0
'Aman'
-4
1
'Priya'
-3
2
'Rahul'
-2
3
'Sneha'
-1
students[ : : ]
RememberLists use square brackets [ ] and commas. Indexing and slicing work exactly like strings (Module 4).
Module 7Lists can change

Lists Are Mutable: Change Any Item

main.py  PY
1prices = [40, 60, 25, 90]
2print("Before:", prices)
3
4prices[1] = 55 # change item at index 1
5prices[-1] = prices[-1] - 10
6print("After :", prices)
7
8name = "Ranchi"
9# name[0] = "D" -> TypeError: strings cannot change
10letters = list(name) # make a list of characters
11letters[0] = "D"
12print("".join(letters))
Terminal
C:\python-practice> python main.py
Before: [40, 60, 25, 90]
After : [40, 55, 25, 80]
Danchi
✎

Mutable

Unlike strings, you can change items in a list: prices[1] = 55.
[]

list()

Turns a string (or range) into a list: list("abc") is ['a', 'b', 'c'].
In real projectsA shop updates one price in its list without rebuilding the whole menu.
Module 7Add and remove

Adding and Removing Items (Click to Animate)

cart: a shopping cart

0
'Pen'
1
'Notebook'
cart = ["Pen", "Notebook"]
Starting value.
MethodDoesReturns
append(x)add at endNone
insert(i, x)add at positionNone
extend(list)add manyNone
remove(x)delete by valueNone
pop(i)delete by indexthe item
clear()empty the listNone
Common mistakeremove("Pencil") when "Pencil" is not in the list raises ValueError. Check with if "Pencil" in cart: first.
Module 7Sort and search

Sorting, Searching and Counting

scores

0
65
1
92
2
78
3
92
4
41
scores = [65, 92, 78, 92, 41]
Starting value.
Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 11
Rememberlist.sort() changes the list and returns None. sorted(list) returns a new list.
Module 7Loop through lists

Looping Over a List: Totals, Averages and Filters

main.py  PY
1marks = [78, 92, 65, 88, 34, 71]
2
3total = 0
4for m in marks:
5 total += m
6average = total / len(marks)
7print(f"Total {total}, average {average:.1f}")
8
9passed = []
10for m in marks:
11 if m >= 40:
12 passed.append(m)
13print("Passed marks:", passed)
14
15for i, m in enumerate(marks, start=1):
16 print(f"Student {i}: {m}", "*" if m == max(marks) else "")
Terminal
C:\python-practice> python main.py
Total 428, average 71.3
Passed marks: [78, 92, 65, 88, 71]
Student 1: 78
Student 2: 92 *
Student 3: 65
Student 4: 88
Student 5: 34
Student 6: 71
  1. 1
    Running total: start at 0, add each item
  2. 2
    Filter: start with an empty list, append items that pass a test
  3. 3
    enumerate: get the position and the item together
In real projectsThese three patterns are used in almost every data program: reports, carts, dashboards.
Module 7Watch it search

Step Through: Finding the Topper Without max()

This "keep the best so far" pattern is how max() works inside. Two lists are linked by the same index.

main.py  PY
1names = ["Aman", "Priya", "Rahul"]
2marks = [78, 92, 85]
3best = 0
4topper = ""
5for i in range(len(marks)):
6 if marks[i] > best:
7 best = marks[i]
8 topper = names[i]
9print(topper, "topped with", best)
Output
Module 72D lists

Lists of Lists: Tables, Grids and Seating Charts

main.py  PY
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 out
8
9for row in seats:
10 print(" | ".join(row))
Terminal
C:\python-practice> python main.py
Row 1, seat 3: Ravi
Aman | Riya | Kunal | Sana
Dev | Isha | Ravi | Neha
Vikas | Tara | Arif | Jiya
Aman[0][0]Riya[0][1]Kunal[0][2]Sana[0][3]row 0Dev[1][0]Isha[1][1]Ravi[1][2]Neha[1][3]row 1Om[2][0]Tara[2][1]Arif[2][2]Jiya[2][3]row 2
Rememberseats[1][2] means: row 1, then item 2 in that row. Spreadsheets, game boards and images are all 2D grids.
Module 7A tricky one

Copying Lists: b = a Does NOT Make a Copy

Watch line 4 carefully. This surprises many beginners (and causes real bugs in apps).

main.py  PY
1a = ["Ranchi", "Dhanbad"]
2b = a # same list, two names
3c = a.copy() # a real copy
4b.append("Bokaro")
5print("a:", a)
6print("b:", b)
7print("c:", c)
Output
Module 7Hands-on

Live Lab: Try It Yourself

lab.py
Output Ready
Output of the starter code (press Run after you change it):
Highest: 92
Lowest : 54
Average: 75.4
Aman 78 PASS
Priya 92 PASS
Rahul 65 PASS
Sneha 88 PASS
Kiran 54 RETEST
Your tasks
  1. Add a new student with append to both lists
  2. Print the marks sorted from high to low
  3. Count how many students scored 80 or more
  4. Print the name of the student with the lowest marks
PracticePractice 1 of 5

Class Marks Analyser

BeginnerScenario. A teacher at a Ranchi school enters the maths marks of 8 students and wants a quick analysis.

Your tasks

  1. Store the marks in a list
  2. Print the highest, lowest, total and average
  3. Count students above the average
  4. Print the marks in descending order
🏢 Used in real projects: Result analysis in school ERPs, Google Classroom grade summaries and Excel-like reports.
practice_7_1.py  PY
1marks = [67, 89, 45, 92, 78, 56, 83, 71]
2
3highest = max(marks)
4lowest = min(marks)
5total = sum(marks)
6average = total / len(marks)
7above = 0
8for m in marks:
9 if m > average:
10 above += 1
11
12print(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))
PracticePractice 2 of 5

Shopping Cart with a Menu

EasyScenario. Build a small text cart: add items, remove items, view the cart, and check out with a total.

Your tasks

  1. Keep two lists: items and prices
  2. Loop a menu with while True
  3. Use append to add and index + pop to remove
  4. At checkout print each item and the total
🏢 Used in real projects: E-commerce carts, restaurant order apps and billing counters manage parallel lists of items and prices.
practice_7_2.py  PY
1items, 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
PracticePractice 3 of 5

To-Do List Manager

IntermediateScenario. Make a to-do list for exam preparation where tasks can be added and ticked off as done.

Your tasks

  1. Keep a list of tasks and a list of done tasks
  2. Add tasks until the user types "done"
  3. Ask which task number is finished, move it to the done list
  4. Print both lists with numbers
🏢 Used in real projects: Google Tasks, Microsoft To Do and project tools like Trello are lists of tasks moved between lists.
practice_7_3.py  PY
1todo = []
2while True:
3 task = input("Add task (or 'done'): ")
4 if task == "done":
5 break
6 todo.append(task)
7
8finished = []
9num = int(input("Which task number did you finish? "))
10finished.append(todo.pop(num - 1))
11
12print("\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}")
PracticePractice 4 of 5

Top 3 Scorers (Two Lists Together)

ChallengingScenario. A district quiz competition has names and scores in two lists. Print the top 3 with medals.

Your tasks

  1. Pair names and scores with zip()
  2. Sort the pairs by score (highest first) using sorted(..., key=..., reverse=True)
  3. Take the first 3 with slicing
  4. Print with medal labels
New toolskey=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).
🏢 Used in real projects: Leaderboards in games, Kaggle competitions and fantasy cricket apps sort records by score.
practice_7_4.py  PY
1names = ["Aditi", "Rohan", "Sahil", "Meera", "Javed", "Pooja"]
2scores = [84, 91, 77, 95, 91, 68]
3
4pairs = list(zip(names, scores))
5ranked = sorted(pairs, key=lambda p: p[1], reverse=True)
6medals = ["Gold", "Silver", "Bronze"]
7
8print("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:]])
PracticePractice 5 of 5

Exam Hall Seating Chart (2D List)

AdvancedScenario. Arrange 12 roll numbers in a 3 x 4 exam hall so that the chart can be printed and any seat looked up.

Your tasks

  1. Build a 3 x 4 grid with nested loops from a list of roll numbers
  2. Print the grid with row letters A, B, C
  3. Ask a roll number and find its seat (row letter + column)
  4. Count total seats used
🏢 Used in real projects: Exam seating software, cinema seat maps, theatre bookings and spreadsheet grids are 2D lists.
practice_7_5.py  PY
1rolls = list(range(101, 113))
2rows, cols = 3, 4
3hall = []
4k = 0
5for r in range(rows):
6 row = []
7 for c in range(cols):
8 row.append(rolls[k])
9 k += 1
10 hall.append(row)
11
12for r, row in enumerate(hall):
13 print("ABC"[r], row)
14
15find = 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))
Module 7Recap

Module 7 Recap & Quiz

What you learned

  • 1A list stores many values in order: [1, 2, 3]; index from 0
  • 2Lists are mutable: change items with lst[i] = x
  • 3Add: append, insert, extend; remove: remove, pop, del, clear
  • 4sort() changes the list; sorted() returns a new one
  • 5sum, min, max, len, in, count, index answer questions about a list
  • 6b = a shares the list; use a.copy() for a real copy

Quick quiz

x = [5, 8, 2]; x.append(4). What is x?

append adds at the end.

[10, 20, 30][-1] is?

-1 is the last item.

Which returns a NEW sorted list?

sorted() returns a new list; sort() changes in place.
MODULE 8

Tuples & Sets

⏱ 2.5 hours5 practice examplesStep-through animationsPython Lab

You will learn

  • Tuples: fixed, unchangeable collections
  • Packing, unpacking and returning many values
  • Sets: unique items with no order
  • Union, intersection and difference
  • Choosing between list, tuple and set

You will build

  • GPS coordinates of Jharkhand cities
  • A unique visitor counter
  • A common friends finder
( ) { }lat, lon = pointset(names)
Module 8Real-world use

Where Is This Used in Real Projects?

tuple / setfixed & unique📍Maps & GPS(lat, lon) pairs🎨Colours(R, G, B) values📅Dates(2026, 10, 8)👥Unique visitorsset of user IDs🏷Tags#python #ranchi🤝Mutual friendsset intersection

Real projects that use this

  • Google Maps stores locations as fixed (latitude, longitude) tuples
  • Websites count unique visitors with a set: the same person twice counts once
  • Instagram and LinkedIn show "mutual friends" using set intersection
  • Image programs store colours as (R, G, B) tuples
Module 8Tuples

Tuples: Like a List, But It Cannot Change

main.py  PY
1ranchi = (23.34, 85.31) # (latitude, longitude)
2rgb_green = (0, 128, 0)
3exam_date = (2026, 3, 15)
4single = ("Ranchi",) # one item needs a comma!
5
6print("Ranchi is at", ranchi)
7print("Latitude:", ranchi[0])
8print("Year:", exam_date[0], "Month:", exam_date[1])
9print(len(rgb_green), type(single))
10
11ranchi[0] = 10 # try to change it
Terminal
C:\python-practice> python main.py
Ranchi is at (23.34, 85.31)
Latitude: 23.34
Year: 2026 Month: 3
3 <class 'tuple'>
Traceback (most recent call last):
File "main.py", line 11, in <module>
ranchi[0] = 10 # try to change it
~~~~~~^^^
TypeError: 'tuple' object does not support item assignment
( )

Round brackets

Tuples use ( ). Indexing, slicing, len, in and loops work like lists.
🔒

Immutable

Once made, a tuple cannot be changed. That makes it safe for fixed data like coordinates and dates.
Common mistake("Ranchi") is just a string in brackets. A one-item tuple needs a trailing comma: ("Ranchi",).
Module 8Unpacking

Packing and Unpacking: Open a Tuple Into Variables

Unpacking is used everywhere: looping over pairs, reading coordinates, and getting several return values from a function.

main.py  PY
1city = ("Jamshedpur", 1.34, "Steel City") # packing
2name, population, nickname = city # unpacking
3print(name, "is called the", nickname)
4
5lat, lon = (22.80, 86.18)
6first, *rest = [5, 10, 15, 20]
7print(first, rest)
Output
Module 8List or tuple?

When to Use a Tuple vs a List

List [ ]Tuple ( )
Can change?Yes (mutable)No (immutable)
Typical datacart items, marks, taskscoordinates, dates, RGB, records
Methodsmany (append, sort...)only count, index
Speed / memorya little morea little less
Dictionary key?NoYes
RememberRule of thumb: list for a collection that grows or changes; tuple for one fixed record.
Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 8
Module 8Sets

Sets: Unique Items Only, No Order

main.py  PY
1visitors = ["amit", "riya", "amit", "john", "riya", "amit"]
2unique = set(visitors)
3print("All visits :", len(visitors))
4print("Unique people:", len(unique))
5print(unique)
6
7tags = {"python", "ranchi", "coding"}
8tags.add("jharkhand")
9tags.add("python") # already there: ignored
10tags.discard("coding")
11print(sorted(tags))
12print("python" in tags)
Terminal
C:\python-practice> python main.py
All visits : 6
Unique people: 3
{'john', 'amit', 'riya'}
['jharkhand', 'python', 'ranchi']
True
{ }

Curly braces

{"a", "b"} makes a set. set(list) removes duplicates from a list.
?

No order, no index

tags[0] is an error. The printed order may look random; use sorted() for display.
⚡

Very fast "in"

Checking x in big_set is super fast even with millions of items.
Common mistake{} is an empty dictionary, not a set. An empty set is set().
Module 8Set maths

Set Operations: The Venn Diagram in Python

A = Class 9 sportsB = Class 10 sportsCricketChessFootballKabaddiHockeyArchery
Click an operation to light up its result.
venn.py  PY
1A = {"Cricket", "Chess", "Football", "Kabaddi"}
2B = {"Hockey", "Archery", "Football", "Kabaddi"}
3
4print(A | B) # union
5print(A & B) # intersection
6print(A - B) # difference
7print(A ^ B) # symmetric difference
OperatorMethodMeaning
|unionall items
&intersectioncommon
-differenceonly in first
^symmetric_differencenot common
Module 8Real use

Sets in Action: Who Has Not Submitted?

main.py  PY
1class_list = {"Aman", "Priya", "Rahul", "Sneha", "Kiran", "Farhan"}
2submitted = {"Priya", "Sneha", "Farhan", "Guest01"}
3
4not_submitted = class_list - submitted
5unknown = submitted - class_list
6
7print("Pending :", sorted(not_submitted))
8print("Unknown :", sorted(unknown))
9print("Done :", len(class_list & submitted), "of", len(class_list))
Terminal
C:\python-practice> python main.py
Pending : ['Aman', 'Kiran', 'Rahul']
Unknown : ['Guest01']
Done : 3 of 6
  1. 1
    Teacher has the full class as a set
  2. 2
    Google Form submissions are another set
  3. 3
    Difference instantly shows who is pending
  4. 4
    Reverse difference catches strange entries
In real projectsAttendance, assignment trackers and email lists use set difference to find "who is missing".
Module 8Hands-on

Live Lab: Try It Yourself

lab.py
Output Ready
Output of the starter code (press Run after you change it):
Came both days : {'Priya', 'Sneha'}
Came any day : {'Priya', 'Aman', 'Sneha', 'Kiran', 'Rahul'}
Only Monday : {'Rahul', 'Aman'}
Hundru Falls: lat 23.45, lon 85.66
Your tasks
  1. Add a wednesday set and find students who came all three days
  2. Print how many unique students came in total
  3. Make a tuple for your school's location and unpack it
  4. Try to change hundru[0] and read the error
PracticePractice 1 of 5

GPS Coordinates of Jharkhand Cities

BeginnerScenario. A travel app stores each city as a (name, latitude, longitude) tuple and shows the approximate straight-line distance from Ranchi.

Your tasks

  1. Make a list of city tuples
  2. Unpack each tuple in a for loop
  3. Approximate distance: 1 degree is about 111 km; use Pythagoras (dx**2 + dy**2) ** 0.5
  4. Print a neat table
🏢 Used in real projects: Ola, Uber, Swiggy and Google Maps store coordinates as fixed pairs and compute distances between them.
practice_8_1.py  PY
1ranchi = (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]) * 111
11 dx = (lon - ranchi[1]) * 111
12 km = (dx ** 2 + dy ** 2) ** 0.5
13 print(f"{name:<12}{lat:>7}{lon:>8}{km:>7.0f}")
PracticePractice 2 of 5

Unique Visitor Counter

EasyScenario. A school website logs every page visit by user ID. The principal wants to know total visits and unique visitors.

Your tasks

  1. Store the visit log as a list (with repeats)
  2. Convert to a set to get unique visitors
  3. Find the most frequent visitor with max(set, key=log.count)
  4. Print the results
🏢 Used in real projects: Google Analytics and every website dashboard show "users" (unique) vs "page views" (total).
practice_8_2.py  PY
1log = ["u12", "u07", "u12", "u33", "u07", "u12", "u45", "u33", "u12"]
2
3unique = set(log)
4top = max(unique, key=log.count)
5
6print("Total visits :", len(log))
7print("Unique visitors :", len(unique))
8print("Visitor IDs :", sorted(unique))
9print(f"Most active : {top} ({log.count(top)} visits)")
PracticePractice 3 of 5

Mutual Friends Finder

IntermediateScenario. Show mutual friends between two users and suggest new friends, like a social media app.

Your tasks

  1. Store each user's friends as a set
  2. Mutual friends = intersection
  3. Suggestions for Aman = friends of Riya that Aman does not know (and not Aman himself)
  4. Print counts and names
🏢 Used in real projects: Facebook, Instagram and LinkedIn "People you may know" features are built on set operations.
practice_8_3.py  PY
1aman = {"Riya", "Kunal", "Sana", "Dev", "Isha"}
2riya = {"Aman", "Kunal", "Isha", "Tara", "Omkar"}
3
4mutual = aman & riya
5suggest = riya - aman - {"Aman"}
6
7print(f"Mutual friends ({len(mutual)}):", ", ".join(sorted(mutual)))
8print("People Aman may know:", ", ".join(sorted(suggest)))
9print("All friends together:", len(aman | riya))
PracticePractice 4 of 5

Compare Subjects of Two Students

ChallengingScenario. Two students in Class 11 chose their subjects. Find common subjects, unique subjects, and check if one set is inside the other.

Your tasks

  1. Create two sets of subjects
  2. Print common subjects and subjects only one student has
  3. Use issubset() to check the core subjects are included
  4. Add an elective with add()
🏢 Used in real projects: College admission portals check that a student's chosen subjects include the required ones (subset checks).
practice_8_4.py  PY
1core = {"English", "Physics", "Chemistry"}
2neha = {"English", "Physics", "Chemistry", "Maths", "Computer Science"}
3irfan = {"English", "Physics", "Chemistry", "Biology", "Hindi"}
4
5print("Common :", sorted(neha & irfan))
6print("Only Neha :", sorted(neha - irfan))
7print("Only Irfan :", sorted(irfan - neha))
8print("Neha has core subjects? ", core.issubset(neha))
9
10irfan.add("Physical Education")
11print("Irfan now takes", len(irfan), "subjects")
PracticePractice 5 of 5

Lucky Draw with Unique Entries

AdvancedScenario. A Diwali mela lucky draw collects coupon numbers, but some people submitted the same coupon twice. Remove duplicates and pick 3 winners.

Your tasks

  1. Store the entries (with duplicates) in a list
  2. Make them unique with set()
  3. Pick 3 winners with random.sample(sorted(unique), 3)
  4. Print the winners as a tuple (results must not change!)
🏢 Used in real projects: Contest platforms remove duplicate entries with sets and pick random winners fairly.
practice_8_5.py  PY
1import random
2entries = [1021, 1088, 1021, 1105, 1130, 1088, 1177, 1202, 1130, 1251]
3unique = set(entries)
4print(f"Entries: {len(entries)}, unique: {len(unique)}")
5
6winners = tuple(random.sample(sorted(unique), 3))
7print("Winners (1st, 2nd, 3rd):", winners)
8first, second, third = winners
9print(f"First prize goes to coupon {first}!")
Module 8Recap

Module 8 Recap & Quiz

What you learned

  • 1Tuple ( ): ordered, cannot change; great for fixed records
  • 2Unpacking: lat, lon = point; *rest collects the rest
  • 3Set { }: unique items, no order, no index; set() removes duplicates
  • 4Set maths: | & - ^ (union, intersection, difference, symmetric)
  • 5Empty set is set(), not {}
  • 6List for changing collections, tuple for fixed records, set for uniqueness

Quick quiz

len(set([1, 1, 2, 3, 3])) is?

Duplicates are removed: {1, 2, 3}.

Which creates a tuple with ONE item?

The trailing comma makes it a tuple.

{1, 2, 3} & {2, 3, 4} gives?

& keeps the common items.
MODULE 9

Dictionaries: Key-Value Data

⏱ 3.5 hours5 practice examplesStep-through animationsPython Lab

You will learn

  • Key-value pairs and why they are fast
  • Reading safely with [ ] and get()
  • Adding, updating and deleting entries
  • Looping with keys(), values() and items()
  • Nested dictionaries and lists of records

You will build

  • A phone book and a price list
  • A word-frequency counter
  • A student report card
{ : }d["name"]d.get(k, 0)
Module 9Real-world use

Where Is This Used in Real Projects?

dictlook up by key📞Contacts appname to number🏷Product catalogitem to price🌐APIs / JSONdata from servers🎓Student recordsroll to details⚙App settingstheme: "dark"📈Countingword to count

Real projects that use this

  • Your phone's contacts app looks up a name and gives the number: a dictionary
  • Weather, cricket and UPI apps receive JSON from servers, which Python reads as dictionaries
  • E-commerce sites store each product as {"name": ..., "price": ..., "stock": ...}
  • Search engines count how often each word appears with a dictionary
Module 9The idea

A Dictionary Maps Keys to Values

phone_book["Rahul"]"Aman"98350 11111"Priya"70040 22222"Rahul"62000 33333"Sneha"99310 44444KEYS (unique)VALUES

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.

{
"Aman"key
:colon
"98350 11111"value
, ...}more pairs
  • Keys must be unique and unchangeable (str, int, tuple)
  • Values can be anything: numbers, lists, even other dicts
  • Lookup by key is very fast, even with millions of entries
Module 9Create and read

Creating a Dictionary and Reading Values

main.py  PY
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 -> None
11print(student.get("phone", "not given")) # default value
12print(len(student), "keys")
13print(student["phone"]) # missing key -> error
Terminal
C:\python-practice> python main.py
Priya Kumari
Maths: 92
Ranchi
None
not given
4 keys
Traceback (most recent call last):
File "main.py", line 13, in <module>
print(student["phone"]) # missing key -> error
~~~~~~~^^^^^^^^^
KeyError: 'phone'
[ ]

d[key]

Gets the value. If the key does not exist you get a KeyError (last line).
get

d.get(key, default)

Safe reading: returns None or your default instead of crashing. Use this for optional data.
In real projectsAPI data often has missing fields. Professional code uses .get() to stay safe.
Module 9Change it

Add, Update and Delete (Click to Animate)

prices: a tea stall menu

'Tea'12
'Samosa'15
prices = {"Tea": 12, "Samosa": 15}
Starting value.
CodeEffect
d[k] = vadd new or update existing
d.update(other)add / update many
d.pop(k)remove, return value
del d[k]remove
k in dis the key present?
d.clear()remove everything
Rememberin checks keys, not values: "Tea" in prices is True, 12 in prices is False.
Module 9Looping

Looping Through a Dictionary

main.py  PY
1stock = {"Rice": 40, "Dal": 12, "Sugar": 0, "Oil": 7}
2
3for item in stock: # keys
4 print(item, end=" ")
5print()
6
7print(list(stock.values())) # values
8
9for item, qty in stock.items(): # key AND value
10 status = "OUT OF STOCK" if qty == 0 else f"{qty} left"
11 print(f"{item:<6} {status}")
12
13print("Total units:", sum(stock.values()))
Terminal
C:\python-practice> python main.py
Rice Dal Sugar Oil
[40, 12, 0, 7]
Rice 40 left
Dal 12 left
Sugar OUT OF STOCK
Oil 7 left
Total units: 59
MethodGives you
d.keys()all keys
d.values()all values
d.items()(key, value) pairs
Rememberfor k, v in d.items(): is the most used dictionary loop in Python.
In real projectsInventory systems loop through stock to show low-stock alerts.
Module 9Counting pattern

Step Through: Counting Votes with a Dictionary

This "count with a dictionary" pattern is one of the most useful in programming: votes, words, sales per product, visits per city.

main.py  PY
1votes = ["Tiger", "Elephant", "Tiger", "Peacock", "Tiger", "Elephant"]
2count = {}
3for animal in votes:
4 if animal in count:
5 count[animal] += 1
6 else:
7 count[animal] = 1
8winner = max(count, key=count.get)
9print(count)
10print("State animal poll winner:", winner)
Output
Module 9Records

Nested Data: A List of Dictionaries (Like a Table)

main.py  PY
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]
6
7print(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']}")
10
11ranchi = [s["name"] for s in students if s["city"] == "Ranchi"]
12print("From Ranchi:", ranchi)
13print("Topper:", max(students, key=lambda s: s["marks"])["name"])
Terminal
C:\python-practice> python main.py
Roll Name Marks City
1 Aman 78 Ranchi
2 Priya 92 Dhanbad
3 Rahul 65 Ranchi
From Ranchi: ['Aman', 'Rahul']
Topper: Priya

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.

rollnamemarkscity
1Aman78Ranchi
2Priya92Dhanbad
3Rahul65Ranchi
In real projectsJSON from a web API looks the same: [{"id": 1, "name": "..."}, ...]. You will fetch real JSON in Module 20.
Module 9Dicts inside dicts

Nested Dictionaries and Useful Methods

main.py  PY
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 admission
8print("Total students:", sum(school["classes"].values()))
9
10menu = dict(tea=12, coffee=25) # another way to create
11squares = {n: n * n for n in range(1, 6)}
12print(menu)
13print(squares)
Terminal
C:\python-practice> python main.py
Ranchi
Total students: 126
{'tea': 12, 'coffee': 25}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
[ ][ ]

Chain the keys

school["address"]["city"]: open the outer dict, then the inner one.
{ }

dict comprehension

{n: n*n for n in range(1, 6)} builds a dict in one line (more in Module 16).
In real projectsSettings files, API responses and app configurations are deeply nested dictionaries.
Module 9Hands-on

Live Lab: Try It Yourself

lab.py
Output Ready
Output of the starter code (press Run after you change it):
Priya -> 70040 22222
Aman 98350 11111
Priya 70040 22222
Rahul 62000 33333
Saved contacts: 3
Your tasks
  1. Add two more contacts
  2. Change Aman's number
  3. Delete one contact with pop
  4. Ask a name with input() and show "not found" if it is missing
PracticePractice 1 of 5

Phone Book Search

BeginnerScenario. A shop owner keeps customer numbers. Search by name (case-insensitive) and add a new contact if not found.

Your tasks

  1. Store contacts in a dict
  2. Ask a name and convert it with .title()
  3. If found print the number, else ask the number and save it
  4. Print all contacts sorted
🏢 Used in real projects: Contacts apps, CRM software and school parent directories use key lookups like this.
practice_9_1.py  PY
1book = {"Aman": "98350 11111", "Priya": "70040 22222", "Rahul": "62000 33333"}
2
3name = 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!")
10
11for n, p in sorted(book.items()):
12 print(f" {n:<8}{p}")
PracticePractice 2 of 5

Price List and Bill

EasyScenario. A kirana store keeps prices in a dictionary. The customer enters items and quantities until they type "done".

Your tasks

  1. Store prices in a dict
  2. Loop: ask item name, check it exists, ask quantity
  3. Store the order in another dict (item: qty)
  4. Print the bill with totals
🏢 Used in real projects: Billing software and online stores look up prices by product name or code from a dictionary or database.
practice_9_2.py  PY
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 break
7 if item not in prices:
8 print("Sorry, we do not have", item)
9 continue
10 order[item] = order.get(item, 0) + int(input("Quantity (kg/L): "))
11
12total = 0
13for item, qty in order.items():
14 cost = prices[item] * qty
15 total += cost
16 print(f"{item.title():<7} {qty:>2} x {prices[item]:>4} = {cost:>6}")
17print(f"{'TOTAL':<20}= {total:>6}")
PracticePractice 3 of 5

Word Frequency Counter

IntermediateScenario. Find the most common words in a speech so that a news app can show its key topics.

Your tasks

  1. Clean the text: lower case and remove punctuation with replace
  2. Split into words
  3. Count with a dict using get(word, 0) + 1
  4. Print the top 5 words with sorted(..., key=..., reverse=True)
🏢 Used in real projects: Search engines, word clouds, spam filters and news trend tools count word frequency.
practice_9_3.py  PY
1speech = """Education is the key to growth. Jharkhand needs education,
2skills and jobs. Skills create jobs and jobs create growth."""
3
4text = speech.lower()
5for ch in ".,":
6 text = text.replace(ch, "")
7words = text.split()
8
9freq = {}
10for w in words:
11 freq[w] = freq.get(w, 0) + 1
12
13top = 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}")
PracticePractice 4 of 5

Student Report Card (Nested Dict)

ChallengingScenario. Store each student's subject marks as a nested dictionary and print a report card with total, percentage and the best subject.

Your tasks

  1. Make {name: {subject: marks}}
  2. Loop over students and their subjects
  3. Find the best subject with max(marks, key=marks.get)
  4. Print a formatted report
🏢 Used in real projects: Report-card generators in school ERPs (and JSON from result APIs) use nested dictionaries.
practice_9_4.py  PY
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) * 100
8 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}")
PracticePractice 5 of 5

Jharkhand District Info Lookup

AdvancedScenario. Build a mini information kiosk: the user types a district name and gets its headquarters, a famous place and the division.

Your tasks

  1. Store a dict of dicts for 5 districts
  2. Loop with a menu until the user types "exit"
  3. Use .get() to handle unknown districts
  4. Show the list of available districts when not found
🏢 Used in real projects: Information kiosks, chatbots and help-desk apps answer queries by looking up keys in dictionaries or databases.
practice_9_5.py  PY
1districts = {
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 break
12 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))
Module 9Recap

Module 9 Recap & Quiz

What you learned

  • 1A dict stores key: value pairs: {"name": "Priya"}
  • 2Read with d[key] (error if missing) or d.get(key, default) (safe)
  • 3Add/update with d[key] = value; remove with pop or del
  • 4Loop with for k, v in d.items():
  • 5Counting pattern: d[x] = d.get(x, 0) + 1
  • 6Lists of dicts = tables of records, just like JSON from APIs

Quick quiz

d = {"a": 1}; d["b"] = 2. Now len(d)?

Assigning to a new key adds it.

Safest way to read a key that may be missing?

get() returns None (or a default) instead of an error.

for k, v in d.items() gives...

items() yields (key, value) pairs.
MODULE 10

Functions: Reusable Blocks of Code

⏱ 4 hours5 practice examplesStep-through animationsPython Lab

You will learn

  • Why functions: reuse and organise
  • def, parameters, arguments and return
  • Default values, keyword arguments, *args and **kwargs
  • Local and global scope
  • lambda, docstrings and a first look at recursion

You will build

  • A reusable GST and EMI calculator
  • A password strength checker
  • Factorial with recursion
defdef area(l, b):return total
Module 10Real-world use

Where Is This Used in Real Projects?

defwrite once, use everywhere🧾Billingcalculate_gst()🔐Logincheck_password()📧Emailsend_email()📅Datesformat_date()🎮Gamesmove_player()🌐Web serversone function per page

Real projects that use this

  • Every real program is made of functions: Instagram has functions like upload_photo() and like_post()
  • A billing app writes calculate_gst() once and uses it on every bill
  • Web frameworks like Flask (Module 20) run one function for each web page
  • Teams split work: each developer writes and tests different functions
Module 10The idea

A Function Is a Machine: Inputs In, Answer Out

inputsprice, qtydef bill()does the workreturnthe answer
defkeyword
billfunction name
(price, qty)parameters
(inputs)
:
return ...sends the
answer back
♻

Reuse

Write the logic once, call it 100 times: bill(40, 3), bill(250, 1)...
📦

Organise

Big programs become small, named pieces that are easy to read and test.
🔧

Fix once

Change GST from 18% to 12% in one place, and every bill is correct.
RememberYou have already used functions: print(), len(), input(). Now you will make your own.
Module 10First function

Defining and Calling a Function

main.py  PY
1def greet():
2 print("Namaste!")
3 print("Welcome to BrainBit Infotech Pvt Ltd")
4
5greet() # call it
6greet() # call it again
7
8def greet_student(name, course):
9 print(f"Hello {name}, welcome to the {course} course!")
10
11greet_student("Riya", "Python")
12greet_student("Kunal", "Web Design")
Terminal
C:\python-practice> python main.py
Namaste!
Welcome to BrainBit Infotech Pvt Ltd
Namaste!
Welcome to BrainBit Infotech Pvt Ltd
Hello Riya, welcome to the Python course!
Hello Kunal, welcome to the Web Design course!
  1. 1
    def only defines the function; nothing runs yet
  2. 2
    Calling greet() runs the indented body
  3. 3
    Parameters (name, course) receive the arguments ("Riya", "Python")
Common mistakeA function must be defined before you call it, otherwise you get NameError.
Module 10return

return: Send a Value Back to the Caller

main.py  PY
1def gst_amount(price, rate=18):
2 return price * rate / 100
3
4def total_with_gst(price):
5 return price + gst_amount(price)
6
7phone_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}")
Terminal
C:\python-practice> python main.py
Cover: Rs 588.82
Charger: Rs 1060.82
Both: Rs 1649.64

print() inside

Only shows the value on screen. The caller gets None and cannot use it.

return

Gives the value back. You can store it, add it, print it, pass it to another function.
RememberRule: functions that calculate something should return it. Let the caller decide whether to print.
Common mistakereturn also ends the function immediately. Lines after it do not run.
Module 10Watch a call

Step Through: What Happens When You Call a Function

Watch the purple "Inside area()" box: each call gets its own fresh variables, which disappear when the function returns.

main.py  PY
1def area(length, breadth):
2 a = length * breadth
3 return a
4
5room = area(12, 10)
6hall = area(30, 20)
7total = room + hall
8print("Total floor area:", total, "sq ft")
Output
Module 10Flexible arguments

Default Values and Keyword Arguments

main.py  PY
1def ticket(name, destination="Ranchi", seat_class="Sleeper", passengers=1):
2 fare = {"Sleeper": 350, "3AC": 950, "2AC": 1400}[seat_class] * passengers
3 print(f"{name}: to {destination}, {seat_class} x{passengers} = Rs {fare}")
4
5ticket("Amit") # uses all defaults
6ticket("Neha", "Kolkata") # positional
7ticket("Ravi", seat_class="3AC", passengers=2) # keyword arguments
8ticket(passengers=3, name="Family", destination="Patna", seat_class="2AC")
Terminal
C:\python-practice> python main.py
Amit: to Ranchi, Sleeper x1 = Rs 350
Neha: to Kolkata, Sleeper x1 = Rs 350
Ravi: to Ranchi, 3AC x2 = Rs 1900
Family: to Patna, 2AC x3 = Rs 4200
=

Default values

destination="Ranchi": used when the caller leaves it out.
k=v

Keyword arguments

seat_class="3AC": name the parameter; the order does not matter.
Common mistakeParameters with defaults must come after those without: def f(a, b=1) is fine, def f(a=1, b) is an error.
Rememberprint(..., sep=" ", end="\n") uses exactly this: defaults you can override by keyword.
Module 10Any number of arguments

*args and **kwargs

main.py  PY
1def total_marks(*marks):
2 print("Received:", marks)
3 return sum(marks)
4
5print(total_marks(78, 92))
6print(total_marks(65, 70, 88, 91, 59))
7
8def make_profile(name, **details):
9 print(f"Profile of {name}")
10 for key, value in details.items():
11 print(f" {key}: {value}")
12
13make_profile("Sana", city="Bokaro", hobby="Chess", age=15)
Terminal
C:\python-practice> python main.py
Received: (78, 92)
170
Received: (65, 70, 88, 91, 59)
373
Profile of Sana
city: Bokaro
hobby: Chess
age: 15
SyntaxCollectsAs a
*argsextra positional valuestuple
**kwargsextra name=value pairsdictionary
In real projectsBuilt-ins like print(*values) and max(*values) work this way. Frameworks like Django and Flask use **kwargs a lot.
Module 10Scope

Local vs Global Variables

Variables made inside a function are local. They vanish when the function ends. Global variables live for the whole program.

main.py  PY
1shop = "Gupta Stores" # global
2count = 0
3
4def add_sale(amount):
5 tax = amount * 0.18 # local
6 global count
7 count += 1
8 return amount + tax
9
10bill = add_sale(200)
11bill2 = add_sale(500)
12print(shop, "sales:", count, "last bill:", bill2)
Output
Module 10Lambda and docs

lambda (One-Line Functions) and Docstrings

main.py  PY
1square = lambda x: x * x
2print(square(12))
3
4students = [("Aman", 78), ("Priya", 92), ("Rahul", 65)]
5by_marks = sorted(students, key=lambda s: s[1], reverse=True)
6print(by_marks)
7
8def emi(principal, annual_rate, months):
9 """Return the monthly EMI using the standard formula.
10
11 principal : loan amount in rupees
12 annual_rate : yearly interest in percent, e.g. 10.5
13 months : number of monthly payments
14 """
15 r = annual_rate / 12 / 100
16 return principal * r * (1 + r) ** months / ((1 + r) ** months - 1)
17
18print(round(emi(100000, 10.5, 12), 2))
19print(emi.__doc__.splitlines()[0])
Terminal
C:\python-practice> python main.py
144
[('Priya', 92), ('Aman', 78), ('Rahul', 65)]
8814.86
Return the monthly EMI using the standard formula.
λ

lambda

A tiny nameless function for one expression. Mostly used as a key for sorting, max, min.
"""

Docstring

The """...""" text right after def. help(emi) shows it. Professionals document every function.
Module 10Recursion

A Function That Calls Itself: Recursion

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.

main.py  PY
1def factorial(n):
2 if n == 1:
3 return 1
4 return n * factorial(n - 1)
5
6print(factorial(4))
Output
Module 10Hands-on

Live Lab: Try It Yourself

lab.py
Output Ready
Output of the starter code (press Run after you change it):
Aman 82.4% A
Priya 93.6% A+
Rahul 60.2% B
Your tasks
  1. Add a function is_pass(pct) that returns True when pct >= 33
  2. Call percentage(45, 50) using a different total
  3. Write average(*nums) that returns the average of any numbers
  4. Add a docstring to grade and print grade.__doc__
PracticePractice 1 of 5

Reusable GST Function

BeginnerScenario. A billing program needs GST at different rates: 5% for food, 12% for some goods, 18% for electronics.

Your tasks

  1. Write add_gst(price, rate=18) that returns the final price
  2. Write show(item, price, rate) that prints one bill line
  3. Call it for 3 items with different rates
  4. Return values, do not print inside add_gst
🏢 Used in real projects: Accounting software (Tally, Zoho Books) has tax functions reused on every invoice line.
practice_10_1.py  PY
1def add_gst(price, rate=18):
2 """Return price including GST."""
3 return round(price * (1 + rate / 100), 2)
4
5def 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 final
9
10total = 0
11total += show("Thali", 150, 5)
12total += show("Umbrella", 450, 12)
13total += show("Earphones", 1299)
14print(f"{'GRAND TOTAL':<40} Rs {total:>9.2f}")
PracticePractice 2 of 5

Area Calculator Toolkit

EasyScenario. A construction contractor in Ranchi needs areas of rooms, circular platforms and triangular plots.

Your tasks

  1. Write functions rectangle(l, b), circle(r), triangle(base, h)
  2. Use 3.14159 for pi
  3. Write cost(area, rate) for flooring cost
  4. Print a summary for 3 shapes
🏢 Used in real projects: Engineering, real-estate and CAD tools are built from many small calculation functions.
practice_10_2.py  PY
1PI = 3.14159
2
3def rectangle(l, b):
4 return l * b
5
6def circle(r):
7 return PI * r ** 2
8
9def triangle(base, height):
10 return 0.5 * base * height
11
12def cost(area, rate_per_sqft=85):
13 return area * rate_per_sqft
14
15jobs = [("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}")
PracticePractice 3 of 5

Password Strength Checker

IntermediateScenario. A college portal rejects weak passwords. A strong one has 8+ characters, an upper-case letter, a digit and a special character.

Your tasks

  1. Write check_password(pw) that returns a (score, list_of_problems) tuple
  2. Use loops and isupper(), isdigit()
  3. Return "Strong", "Medium" or "Weak" from label(score)
  4. Test 3 passwords
🏢 Used in real projects: Every sign-up page (Gmail, banking, college portals) runs a validation function like this before saving a password.
practice_10_3.py  PY
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), problems
12
13def label(score):
14 return "Strong" if score == 4 else "Medium" if score >= 2 else "Weak"
15
16for 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 "")
PracticePractice 4 of 5

EMI Planner with Default Arguments

ChallengingScenario. A two-wheeler showroom compares EMI options for different tenures, using a function with sensible defaults.

Your tasks

  1. Write emi(principal, rate=9.5, years=2) that returns the monthly EMI
  2. Write plan(principal, *tenures) that prints a row for each tenure using *args
  3. Show total interest paid for each
  4. Call with keyword arguments for a different rate
🏢 Used in real projects: Loan comparison tools on bank and NBFC websites call one EMI function with many inputs.
practice_10_4.py  PY
1def emi(principal, rate=9.5, years=2):
2 r = rate / 12 / 100
3 n = years * 12
4 return principal * r * (1 + r) ** n / ((1 + r) ** n - 1)
5
6def 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 - principal
11 print(f" {y} yr: EMI Rs {m:>8,.0f} interest Rs {interest:>8,.0f}")
12
13plan(85000, 1, 2, 3)
14plan(85000, 2, 3, rate=11.0)
PracticePractice 5 of 5

Recursion: Factorial and Digit Sum

AdvancedScenario. Practise recursion with two classic problems used in coding interviews.

Your tasks

  1. Write recursive factorial(n) with base case n <= 1
  2. Write recursive digit_sum(n): last digit + digit_sum(rest)
  3. Write countdown(n) that prints and calls itself
  4. Test them
🏢 Used in real projects: Recursion powers folder scanning (folders inside folders), menu trees, and many search algorithms.
practice_10_5.py  PY
1def factorial(n):
2 if n <= 1:
3 return 1
4 return n * factorial(n - 1)
5
6def digit_sum(n):
7 if n < 10:
8 return n
9 return n % 10 + digit_sum(n // 10)
10
11def countdown(n):
12 if n == 0:
13 print("Go!")
14 return
15 print(n, end=" ")
16 countdown(n - 1)
17
18for k in [1, 5, 10]:
19 print(f"{k}! = {factorial(k)}")
20print("Digit sum of 834001 =", digit_sum(834001))
21countdown(5)
Module 10Recap

Module 10 Recap & Quiz

What you learned

  • 1def name(params): defines; name(args) calls
  • 2return sends a value back (and ends the function); prefer it over print
  • 3Defaults rate=18 and keyword args f(rate=12) make calls flexible
  • 4*args = tuple of extra values, **kwargs = dict of extra named values
  • 5Variables inside a function are local; use global rarely
  • 6lambda x: ... for tiny functions; recursion needs a base case

Quick quiz

What does a function return if it has no return statement?

Functions without return give None.

def f(a, b=2): return a * b. f(5)?

b uses its default 2: 5 x 2 = 10.

A recursive function must have a...

Without a base case it never stops.
MODULE 11

Modules, Packages & pip

⏱ 3 hours5 practice examplesStep-through animationsPython Lab

You will learn

  • What modules and packages are
  • import, from ... import and aliases
  • Useful built-in modules: math, random, datetime, os
  • Making your own module and if __name__ == "__main__"
  • Installing packages from PyPI with pip

You will build

  • An OTP generator
  • An age calculator with datetime
  • Your own reusable utils module
importimport mathpip install
Module 11Real-world use

Where Is This Used in Real Projects?

importuse ready-made tools🔢mathengineering, GST🎲randomOTP, games, draws📅datetimebills, attendance📁os / pathliborganise files📊pandasdata analysis🌐requeststalk to websites

Real projects that use this

  • Python comes with a huge standard library: hundreds of ready modules ("batteries included")
  • PyPI (pypi.org) hosts hundreds of thousands of free packages you install with pip
  • Instagram, YouTube and NASA projects are built by combining packages, not by writing everything from zero
  • Your own code can be split into modules that your whole team reuses
Module 11The idea

Modules: Toolboxes You Can Import

mathbuilt inrandombuilt indatetimebuilt inosbuilt inpandaspip installrequestspip installyour_program.py
WordMeaning
Moduleone .py file full of functions and variables
Packagea folder of modules (with __init__.py)
Standard librarymodules that come with Python (math, random...)
Third-partypackages you install with pip (pandas, requests...)
PyPIPython Package Index: the online store of packages
Common mistakeDo not name your own file random.py or math.py! Python will import your file instead of the real module.
Module 11Import styles

Three Ways to Import

main.py  PY
1import math
2print(math.sqrt(144))
3print(math.pi)
4
5from math import ceil, floor
6print(ceil(4.1), floor(4.9))
7
8import datetime as dt
9print(dt.date(2026, 10, 8).strftime("%d %B %Y"))
10
11import random
12print(random.choice(["Ranchi", "Dhanbad", "Bokaro"]))
Terminal
C:\python-practice> python main.py
12.0
3.141592653589793
5 4
08 October 2026
Dhanbad
StyleUse asWhen
import mathmath.sqrt()clear where it comes from (best)
from math import sqrtsqrt()a few functions, used often
import pandas as pdpd.read_csv()long names (common convention)
Common mistakeAvoid from math import *: you cannot tell where names come from, and they may overwrite your variables.
Module 11math

The math Module: Maths Beyond + - * /

main.py  PY
1import math
2
3print("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))
9
10radius = 7
11print(f"Area of a 7 m round tank: {math.pi * radius ** 2:.2f} sq m")
12
13students, bus_capacity = 130, 40
14print("Buses needed:", math.ceil(students / bus_capacity))
Terminal
C:\python-practice> python main.py
sqrt(625) = 25.0
ceil(7.2) = 8 | floor(7.8) = 7
pi = 3.14159
5! = 120
gcd(48, 36) = 12
2^10 = 1024.0
Area of a 7 m round tank: 153.94 sq m
Buses needed: 4
⇧

ceil for "how many needed"

130 students, 40 per bus: ceil(3.25) = 4 buses. round would wrongly give 3.
f(x)

Common functions

sqrt, ceil, floor, pi, factorial, gcd, log, sin, cos
In real projectsEngineering, physics simulations and finance code rely on math.
Module 11random

The random Module: Games, OTPs and Lucky Draws

main.py  PY
1import random
2
3print("Dice:", random.randint(1, 6))
4print("Toss:", random.choice(["Heads", "Tails"]))
5print("Discount:", round(random.uniform(5, 15), 1), "%")
6
7quiz = ["Q1", "Q2", "Q3", "Q4", "Q5"]
8random.shuffle(quiz)
9print("Shuffled quiz:", quiz)
10print("Pick 2 winners:", random.sample(["Aman", "Riya", "Kunal", "Sana", "Dev"], 2))
11
12otp = "".join(random.choices("0123456789", k=6))
13print("Your OTP:", otp)
Terminal
C:\python-practice> python main.py
Dice: 6
Toss: Heads
Discount: 11.6 %
Shuffled quiz: ['Q3', 'Q2', 'Q5', 'Q1', 'Q4']
Pick 2 winners: ['Aman', 'Riya']
Your OTP: 699487
Random: your output will be different.
FunctionGives
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
Common mistakeFor real passwords and OTPs use the secrets module, which is designed for security. random is for games and simulations.
Module 11datetime

The datetime Module: Dates, Times and Differences

main.py  PY
1from datetime import date, datetime, timedelta
2
3exam = date(2027, 2, 15)
4today = date(2026, 10, 8) # use date.today() in real programs
5left = exam - today
6print("Days to board exam:", left.days)
7
8due = today + timedelta(days=30)
9print("Fee due on:", due.strftime("%d-%m-%Y (%A)"))
10
11birthday = date(2011, 6, 21)
12age = today.year - birthday.year - ((today.month, today.day) < (birthday.month, birthday.day))
13print("Age:", age)
14
15now = datetime(2026, 10, 8, 9, 30)
16print(now.strftime("Attendance marked at %I:%M %p on %d %b %Y"))
Terminal
C:\python-practice> python main.py
Days to board exam: 130
Fee due on: 07-11-2026 (Saturday)
Age: 15
Attendance marked at 09:30 AM on 08 Oct 2026
CodeMeansExample
%dday08
%m / %B / %bmonth10 / October / Oct
%Yyear2026
%AweekdayThursday
%I:%M %p12-hour time09:30 AM
In real projectsSubtracting two dates gives a timedelta; .days gives the number of days. Used in fee reminders, library fines and countdowns.
Module 11Your own module

Make Your Own Module (and Import It)

utils.py  PY
1"""utils.py - helpers for the BrainBit Infotech billing app"""
2GST_RATE = 18
3
4def add_gst(amount, rate=GST_RATE):
5 return round(amount * (1 + rate / 100), 2)
6
7def rupees(amount):
8 return f"Rs {amount:,.2f}"
9
10if __name__ == "__main__":
11 # runs only when utils.py is run directly
12 print("Testing utils:", rupees(add_gst(1000)))
main.py  PY
1import utils
2from utils import rupees
3
4bill = utils.add_gst(2499)
5print("Total:", rupees(bill))
6print("GST rate used:", utils.GST_RATE)
Terminal
C:\python-practice> python main.py
Total: Rs 2,948.82
GST rate used: 18
RememberKeep both files in the same folder. import utils (no .py). The test line under if __name__ == "__main__": does not run on import.
Module 11pip and PyPI

pip: Install Packages from the Internet

Command Prompt
D:\python-practice> pip install tabulate
Collecting tabulate
Downloading tabulate-0.9.0-py3-none-any.whl (35 kB)
Installing collected packages: tabulate
Successfully installed tabulate-0.9.0
commandsCMD
1# Useful pip commands
2pip install requests # install
3pip install pandas==2.2.3 # exact version
4pip install --upgrade pandas # upgrade
5pip uninstall tabulate # remove
6pip list # what is installed
7pip freeze > requirements.txt # save the list for your team
PackageUsed for
requestsdownload web pages, call APIs
pandas, numpydata analysis
matplotlibcharts
flask, djangowebsites
openpyxlExcel files
pillowimages
pygamegames
tabulatepretty tables in the terminal
Common mistakeIf 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.
Module 11Package in action

Using an Installed Package: tabulate

main.py  PY
1from tabulate import tabulate
2
3rows = [
4 ["Aman", "Ranchi", 78],
5 ["Priya", "Dhanbad", 92],
6 ["Rahul", "Bokaro", 65],
7]
8print(tabulate(rows, headers=["Name", "City", "Marks"], tablefmt="grid"))
Terminal
C:\python-practice> python main.py
+--------+---------+---------+
| Name | City | Marks |
+========+=========+=========+
| Aman | Ranchi | 78 |
+--------+---------+---------+
| Priya | Dhanbad | 92 |
+--------+---------+---------+
| Rahul | Bokaro | 65 |
+--------+---------+---------+
  1. 1
    pip install tabulate once
  2. 2
    from tabulate import tabulate in your program
  3. 3
    Call it with your data. Three lines replace a lot of formatting work!
RememberThis is the power of Python: thousands of people share packages so you can build faster.
Module 11Hands-on

Live Lab: Try It Yourself

lab.py
Output Ready
Output of the starter code (press Run after you change it):
Square root of 2: 1.4142
Dice roll: 5
Lucky city: Ranchi
Christmas is on a Friday
Your tasks
  1. Print math.ceil(95 / 12): how many boxes for 95 eggs, 12 per box?
  2. Roll two dice and print their sum
  3. Find which weekday your next birthday falls on
  4. Print the number of days between two dates you choose
PracticePractice 1 of 5

OTP Generator

BeginnerScenario. A coaching institute app sends a 6-digit OTP at login. Make OTPs and check what the user types.

Your tasks

  1. Write make_otp(length=6) using random.randint(0, 9) in a loop
  2. Print the OTP (as if sent by SMS)
  3. Ask the user to type it
  4. Compare and print Verified / Wrong OTP
🏢 Used in real projects: Banking, UPI and login systems generate one-time passwords (real systems use the secure secrets module).
practice_11_1.py  PY
1import random
2
3def make_otp(length=6):
4 return "".join(str(random.randint(0, 9)) for _ in range(length))
5
6otp = 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.")
PracticePractice 2 of 5

Dice Game: First to 20

EasyScenario. Two players roll a dice in turns. The first to reach 20 points wins. Rolling a 6 gives an extra roll.

Your tasks

  1. Use random.randint(1, 6)
  2. Keep scores in a dict
  3. Loop until a player reaches 20
  4. Handle the extra roll for a 6
🏢 Used in real projects: Ludo King, board-game apps and simulations are built on random numbers and game loops.
practice_11_2.py  PY
1import random
2scores = {"Riya": 0, "Kunal": 0}
3winner = None
4round_no = 0
5while winner is None:
6 round_no += 1
7 for player in scores:
8 roll = random.randint(1, 6)
9 scores[player] += roll
10 extra = ""
11 if roll == 6:
12 bonus = random.randint(1, 6)
13 scores[player] += bonus
14 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 = player
18 break
19print(f"{winner} wins!")
PracticePractice 3 of 5

Age and Next Birthday Calculator

IntermediateScenario. An admission form calculates the exact age and the days left to the next birthday.

Your tasks

  1. Ask the date of birth as DD-MM-YYYY
  2. Convert with datetime.strptime(text, "%d-%m-%Y").date()
  3. Calculate age in years and the next birthday date
  4. Print the days left and the weekday
🏢 Used in real projects: Admission portals, HR systems and insurance apps calculate age and anniversaries from dates.
practice_11_3.py  PY
1from datetime import datetime, date
2
3today = date(2026, 10, 8) # date.today() in a real app
4dob = datetime.strptime(input("Date of birth (DD-MM-YYYY): "), "%d-%m-%Y").date()
5
6age = 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)
10
11print("Age:", age, "years")
12print("Next birthday:", next_bd.strftime("%d %B %Y, %A"))
13print("Days left:", (next_bd - today).days)
PracticePractice 4 of 5

Your Own Module: school_utils.py

ChallengingScenario. Create a module with school helper functions and use it from a main program, like a real project.

Your tasks

  1. In school_utils.py write percentage(), grade() and report_line()
  2. Add a self-test under if __name__ == "__main__":
  3. In main.py import the module and process 3 students
  4. Run main.py and check the self-test does not print
school_utils.py  PY
1SCHOOL = "DAV Public School, Ranchi"
2
3def percentage(marks, total=500):
4 return marks / total * 100
5
6def grade(pct):
7 return "A" if pct >= 80 else "B" if pct >= 60 else "C"
8
9def report_line(name, marks):
10 p = percentage(marks)
11 return f"{name:<6} {marks:>3} {p:5.1f}% {grade(p)}"
12
13if __name__ == "__main__":
14 print("Self-test:", report_line("Test", 400))
🏢 Used in real projects: Real projects are many modules: models.py, utils.py, views.py. Teams import each other's modules.
main.py  PY
1import school_utils as su
2
3students = {"Aman": 412, "Priya": 468, "Rahul": 301}
4print(su.SCHOOL)
5for name, marks in students.items():
6 print(su.report_line(name, marks))
PracticePractice 5 of 5

Pretty Report with a pip Package

AdvancedScenario. Use the third-party tabulate package to print a district-wise results table with totals.

Your tasks

  1. Install once: pip install tabulate
  2. Build a list of rows from a dict
  3. Add a total row
  4. Print with tablefmt="github" (Markdown-style)
🏢 Used in real projects: Data teams use packages like tabulate, rich and pandas to make readable reports quickly.
practice_11_5.py  PY
1from tabulate import tabulate
2
3results = {"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"))
Module 11Recap

Module 11 Recap & Quiz

What you learned

  • 1A module is a .py file; a package is a folder of modules
  • 2import math, from math import sqrt, import pandas as pd
  • 3Built-ins: math (sqrt, ceil), random (randint, choice), datetime (date, timedelta)
  • 4Your own module: put utils.py in the same folder and import utils
  • 5if __name__ == "__main__": runs only when the file is run directly
  • 6pip install name gets packages from PyPI

Quick quiz

Which gives the number of buses for 130 students, 40 per bus?

ceil rounds up: 4 buses.

Command to install the requests package?

pip installs from PyPI.

random.randint(1, 6) can return 6?

randint includes both ends.
PART 2 COMPLETE

Well done!

You finished Data Structures & Functions: 5 modules and 25 practice examples.

Before moving on

  • Re-type every practice example yourself without looking
  • Save your work in D:\python-practice\part2
  • Try the quizzes again until you get all of them right
  • Change one thing in each example and predict the output before you run it
print("Hi") >>> _
🐍 Python LabReady
Edit the code, then press Run. input() opens a small box to type your answer.
Terminal