Class XII Computer Science Board Preparation

🏠 Home Menu
🎓
Student
Level 1 · Beginner
0 / 100 XP
0
Day
Streak 🔥
CONTINUE WHERE YOU LEFT OFF
Start Learning →
Pick any topic from Class 11 or 12
0
Topics Visited
out of 34 total
0
Total XP Earned
keep going!
0
Exams Taken
Best: —
0
Badges Earned
collect them all!

🏅 Your Badges

📊 Topic Progress

Unit 1 · Computer Systems & Organisation
Basic Computer Organisation
Understand how a computer is structured — CPU, memory hierarchy, I/O devices, and how they all work together.
2
Marks

What is a Computer System?

1.1
Computer
An electronic device that accepts data (input), processes it, stores results, and produces output — following a set of instructions (program).
Hardware
Physical components you can touch — keyboard, monitor, CPU chip, RAM sticks, hard disk, printer.
Software
Set of instructions (programs) that tell hardware what to do. Intangible — exists as code stored on disk.
Data vs Information
Raw facts = Data. Processed meaningful result = Information.
e.g. 85, 90, 70 (data) → Average = 81.67 (information)

IPO Cycle & Block Diagram

1.2
INPUT Keyboard, Mouse Scanner, Camera CPU Central Processing Unit CU ALU Registers OUTPUT Monitor, Printer Speaker, Projector STORAGE Primary: RAM, ROM Secondary: HDD, SSD Cache, Registers IPO MODEL — Computer Block Diagram

Memory Hierarchy

1.3
Memory Hierarchy (Fastest → Slowest, Smallest → Largest) Registers Fastest • Most Expensive Few bytes • Inside CPU Cache Memory (L1/L2/L3) KB to few MB • Inside/near CPU SRAM • Nanoseconds Primary Memory (RAM / ROM) 4GB–64GB typical • DRAM Volatile (RAM) / Non-volatile (ROM) Microseconds Secondary Storage (HDD / SSD / Optical / USB) 100GB–Terabytes • Non-volatile • Permanent storage Slowest • Cheapest per GB ⬆ Speed ⬇ Cost/GB

Memory Units

1.4
UnitSymbolValueExample
BitbSmallest unit (0 or 1)1 binary digit
Nibble—4 bitsHalf a byte
ByteB8 bits1 character = 1 Byte
KilobyteKB1024 BytesSmall text file
MegabyteMB1024 KBA song (~4MB)
GigabyteGB1024 MBA movie (~2GB)
TerabyteTB1024 GBLaptop HDD
PetabytePB1024 TBGoogle stores ~15 Exabytes

Input & Output Devices

1.5
Input Devices
Keyboard, Mouse, Touchscreen, Scanner, Microphone, Webcam, Barcode Reader, Joystick, Light Pen, OCR/OMR.
Output Devices
Monitor (CRT/LCD/LED), Printer (Laser/Inkjet/Dot Matrix), Speaker, Plotter, Projector, Braille Display.
I/O Devices (Both)
Touch Screen, Network Card (NIC), Modem, CD/DVD Drive (reads and writes).
CPU Components
CU (Control Unit) — directs data flow.
ALU (Arithmetic Logic Unit) — does calculations & comparisons.
Registers — tiny ultra-fast storage in CPU.
📌 Remember for Exam
  • RAM is volatile — data lost on power off. ROM is non-volatile — holds BIOS permanently.
  • Cache is faster than RAM but smaller. Order: Registers > Cache > RAM > HDD
  • ALU performs arithmetic (+−×÷) and logical (> < = AND OR) operations.
  • CU does NOT process data — it only controls and coordinates.
  • 1 KB = 1024 B (not 1000 B) — computers use binary (powers of 2).
  • CPU speed is measured in GHz (Giga Hertz). 1 GHz = 10⁹ cycles/second.

Practice Paper — C1

PP

Topic Test: Basic Computer Organisation

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which component performs arithmetic and logic operations?
  • (a) Control Unit
  • (b) ALU
  • (c) Register
  • (d) Cache
[1 mark]
Q2.
1 Terabyte = ?
  • (a) 1000 GB
  • (b) 1024 GB
  • (c) 1024 MB
  • (d) 1000 MB
[1 mark]
Q3.
Which memory loses data when power is off?
  • (a) ROM
  • (b) Flash Drive
  • (c) RAM
  • (d) HDD
[1 mark]
Q4.
Cache memory is placed between:
  • (a) CPU and HDD
  • (b) RAM and HDD
  • (c) CPU and RAM
  • (d) ROM and RAM
[1 mark]
Q5.
Which is NOT an output device?
  • (a) Monitor
  • (b) Printer
  • (c) Keyboard
  • (d) Speaker
[1 mark]
Q6.
The full form of BIOS is:
  • (a) Binary Input Output System
  • (b) Basic Input Output System
  • (c) Base Integrated OS
  • (d) Built-in OS
[1 mark]
Q7.
Which unit controls the sequence of operations?
  • (a) ALU
  • (b) CU
  • (c) Memory
  • (d) Register
[1 mark]
Q8.
Secondary storage is:
  • (a) Volatile
  • (b) Non-volatile
  • (c) Part of CPU
  • (d) Faster than RAM
[1 mark]
Q9.
Register is located in:
  • (a) Hard Disk
  • (b) RAM
  • (c) CPU
  • (d) Cache
[1 mark]
Q10.
Which bus carries data between CPU and memory?
  • (a) Address bus
  • (b) Control bus
  • (c) Data bus
  • (d) System bus
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
What is the storage hierarchy from fastest to slowest?
[2 marks]
Q12.
What is the output of the following?
Convert 2 KB to bytes.
[2 marks]
Q13.
What is the output of the following?
Name the three buses in a computer system.
[2 marks]
Q14.
What is the output of the following?
What does the Control Unit NOT do?
[2 marks]
Q15.
What is the output of the following?
If RAM is 4 GB, how many bytes is that?
[2 marks]
Q16.
What is the output of the following?
What is the difference between primary and secondary memory?
[2 marks]
Q17.
What is the output of the following?
What is the role of the accumulator register?
[2 marks]
Q18.
What is the output of the following?
Name two input devices and two output devices.
[2 marks]
Q19.
What is the output of the following?
What is clock speed and its unit?
[2 marks]
Q20.
What is the output of the following?
Expand: ALU, CU, MAR, MDR.
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write a program to convert KB to bytes, MB, and GB.
[3 marks]
Q22.
Print a table showing storage units from Byte to Petabyte.
[3 marks]
Q23.
Simulate a register holding a value and performing addition.
[3 marks]
Q24.
Display computer specs using variables.
[3 marks]
Q25.
Convert bytes to all higher units.
[3 marks]
Q26.
Simulate a simple CPU fetch-execute cycle (text output).
[3 marks]
Q27.
Calculate total RAM in bytes given modules.
[3 marks]
Q28.
Display a bus width comparison.
[3 marks]
Q29.
Simulate cache hit/miss for a list of memory accesses.
[3 marks]
Q30.
Write a program to compare two storage sizes and say which is larger.
[3 marks]
A1: (b) — ALU (Arithmetic Logic Unit) handles all +−×÷ and comparison operations.
A2: (b) — 1 TB = 1024 GB (binary system uses powers of 2).
A3: (c) — RAM is volatile — contents are lost when power is removed.
A4: (c) — Cache sits between fast CPU and slower RAM to reduce access time.
A5: (c) — Keyboard is an input device, not output.
A6: (b) — BIOS = Basic Input Output System — firmware that initialises hardware.
A7: (b) — Control Unit (CU) directs data flow and sequences all CPU operations.
A8: (b) — Secondary storage (HDD/SSD) is non-volatile — retains data without power.
A9: (c) — Registers are the fastest, smallest storage units inside the CPU.
A10: (c) — Data bus carries actual data between CPU, memory and I/O devices.
A11: Registers → Cache → RAM → SSD/HDD → Optical/Tape
A12: 2 × 1024 = 2048 bytes
A13: Address bus, Data bus, Control bus
A14: It does not perform arithmetic or logic — that is done by the ALU.
A15: 4 × 1024³ = 4,294,967,296 bytes
A16: Primary (RAM/ROM): fast, directly accessible by CPU; Secondary (HDD/SSD): slow, permanent storage.
A17: Holds intermediate results of ALU operations.
A18: Input: Keyboard, Mouse; Output: Monitor, Printer
A19: Rate at which CPU executes instructions; measured in GHz (gigahertz).
A20: Arithmetic Logic Unit, Control Unit, Memory Address Register, Memory Data Register
A21:
kb=float(input("Enter KB: "))
print("Bytes:",kb*1024)
print("MB:",kb/1024)
print("GB:",kb/1024**2)
A22:
units=["Byte","KB","MB","GB","TB","PB"]
for i,u in enumerate(units):
    print(f"{u} = 2^{10*i} bytes = {2**(10*i):,}")
A23:
acc=0
for val in [10,20,30,40]:
    acc+=val
    print(f"ACC after adding {val}: {acc}")
A24:
cpu="Intel i5"
ram="8 GB"
hdd="512 GB SSD"
print(f"CPU: {cpu}\nRAM: {ram}\nStorage: {hdd}")
A25:
b=int(input("Bytes: "))
print(f"KB: {b/1024:.2f}\nMB: {b/1024**2:.4f}\nGB: {b/1024**3:.6f}")
A26:
instructions=["FETCH","DECODE","EXECUTE","STORE"]
for step in instructions:
    print(f"→ {step}")
A27:
modules=[4,8,4]
print("Total RAM:",sum(modules),"GB =",sum(modules)*1024**3,"bytes")
A28:
buses={"Address bus":32,"Data bus":64,"Control bus":8}
for b,w in buses.items():
    print(f"{b}: {w}-bit ({2**w:,} combinations)")
A29:
cache=[]
for addr in [100,200,100,300,200,100,400]:
    if addr in cache:
        print(f"{addr}: HIT")
    else:
        cache.append(addr)
        if len(cache)>3: cache.pop(0)
        print(f"{addr}: MISS")
A30:
a=int(input("Size A in MB: "))
b=int(input("Size B in MB: "))
if a>b: print("A is larger")
elif b>a: print("B is larger")
else: print("Equal")
Unit 1 · Computer Systems & Organisation
Types of Software
System software, application software, language translators — how software layers work together.
2
Marks

Software Classification

2.1
Software Classification Tree SOFTWARE System Software Application Software Language Translators OS Utilities Device Drivers General Specific Customised Compiler Interpreter Assembler Examples: Windows, Linux, Antivirus, Disk Formatter MS Office, VLC, Photoshop, Games, Tally, CAD Compiler=whole prog Interpreter=line by line Assembler=assembly→machine

Compiler vs Interpreter vs Assembler

2.2
FeatureCompilerInterpreterAssembler
Input LanguageHigh-level (C, C++)High-level (Python, BASIC)Assembly language
TranslationEntire program at onceLine by lineMnemonic → Machine code
SpeedFaster executionSlower executionVery fast (near hardware)
Error detectionShows all errors togetherStops at first errorShows errors after scan
OutputObject file (.exe)No separate object fileMachine code
Example useC, JavaPython, JavaScriptEmbedded systems
📌 Remember for Exam
  • System software manages hardware. Application software serves the user.
  • Compiler = translates WHOLE program first, then runs. Interpreter = translates & runs ONE LINE at a time.
  • Python uses an interpreter. That's why it stops at the first error found.
  • Firmware = software permanently stored in ROM (e.g. BIOS). Neither purely hardware nor software.
  • Open source software: source code is publicly available (e.g. Linux, Python, Firefox).
  • OS functions: process management, memory management, file management, device management, security.

Topic Test: Types of Software

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which is system software?
  • (a) MS Word
  • (b) VLC Player
  • (c) Operating System
  • (d) Tally
[1 mark]
Q2.
A compiler translates:
  • (a) One line at a time
  • (b) Entire program at once
  • (c) Only syntax
  • (d) Only semantics
[1 mark]
Q3.
Which is application software?
  • (a) Device Driver
  • (b) BIOS
  • (c) Antivirus
  • (d) MS Excel
[1 mark]
Q4.
An interpreter executes:
  • (a) After full compilation
  • (b) Line by line
  • (c) Only functions
  • (d) Binary directly
[1 mark]
Q5.
Which software bridges hardware and applications?
  • (a) Utility
  • (b) OS
  • (c) Assembler
  • (d) Compiler
[1 mark]
Q6.
Assembler converts:
  • (a) High-level to machine code
  • (b) Assembly to machine code
  • (c) Machine to assembly
  • (d) Object to exe
[1 mark]
Q7.
Which is NOT utility software?
  • (a) Disk Defragmenter
  • (b) Antivirus
  • (c) File Compressor
  • (d) Python IDE
[1 mark]
Q8.
Open source software means:
  • (a) Free software only
  • (b) Source code is publicly available
  • (c) No license needed
  • (d) Runs on any OS
[1 mark]
Q9.
Device driver is a type of:
  • (a) Application software
  • (b) System software
  • (c) Malware
  • (d) Firmware
[1 mark]
Q10.
Which has faster execution — compiler or interpreter?
  • (a) Interpreter
  • (b) Compiler
  • (c) Both same
  • (d) Depends on OS
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Name three types of system software.
[2 marks]
Q12.
What is the output of the following?
What is the difference between freeware and open source?
[2 marks]
Q13.
What is the output of the following?
Which translator is used for Python?
[2 marks]
Q14.
What is the output of the following?
Give two advantages of a compiler over an interpreter.
[2 marks]
Q15.
What is the output of the following?
Name two utility programs and their purposes.
[2 marks]
Q16.
What is the output of the following?
What is firmware? Give one example.
[2 marks]
Q17.
What is the output of the following?
Difference between system software and application software (two points).
[2 marks]
Q18.
What is the output of the following?
What is proprietary software?
[2 marks]
Q19.
What is the output of the following?
Name the translation process in an assembler.
[2 marks]
Q20.
What is the output of the following?
Give two examples each of system and application software.
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write a menu-driven program to identify software type based on user input.
[3 marks]
Q22.
Simulate a simple interpreter: execute 3 print statements one by one.
[3 marks]
Q23.
Display a table of software categories and examples.
[3 marks]
Q24.
Take a list of software and classify them as system/application.
[3 marks]
Q25.
Compare compiler vs interpreter in a formatted table.
[3 marks]
Q26.
Write a program to list all files in a folder and identify their software category by extension.
[3 marks]
Q27.
Simulate license check for proprietary software.
[3 marks]
Q28.
Count how many programs are system vs application from a list.
[3 marks]
Q29.
Print software version info in a structured way.
[3 marks]
Q30.
Write a program that simulates running a compiled vs interpreted program with timing.
[3 marks]
A1: (c) — OS manages hardware resources — it is system software.
A2: (b) — Compiler translates the entire source program before execution.
A3: (d) — MS Excel is an application — used by end-users for specific tasks.
A4: (b) — Interpreter translates and executes one line/statement at a time.
A5: (b) — OS acts as interface between hardware and application software.
A6: (b) — Assembler converts assembly language (mnemonics) to machine code.
A7: (d) — Python IDE is application/development software, not a utility.
A8: (b) — Open source: source code is available for viewing/modifying/distributing.
A9: (b) — Device drivers are system software that allow OS to communicate with hardware.
A10: (b) — Compiled programs run faster; interpretation has per-line overhead.
A11: Operating System, Device Drivers, Utility Software
A12: Freeware: free to use but source code is closed. Open source: source code available and modifiable.
A13: Python uses an interpreter (also has a bytecode compiler internally).
A14: 1. Faster execution. 2. Source code not needed at runtime.
A15: Antivirus: detects/removes malware. Disk Defragmenter: reorganises fragmented files.
A16: Firmware: software embedded in hardware ROM. Example: BIOS.
A17: System: manages hardware, runs at start; Application: serves user tasks, needs OS to run.
A18: Software owned by a company; source code is not available; requires license to use.
A19: Converts assembly language mnemonics (like MOV, ADD) to binary machine code.
A20: System: Linux, Windows; Application: MS Word, VLC Player
A21:
types={"OS":"System","Driver":"System","Word":"Application","Compiler":"System Tool"}
name=input("Enter software name: ")
print(types.get(name,"Unknown type"))
A22:
statements=["print(1+2)","print('Hello')","print(2**8)"]
for s in statements:
    print(f"Executing: {s}")
    exec(s)
A23:
data={"System":["OS","Driver","BIOS"],"Application":["Word","Excel","VLC"],"Utility":["Antivirus","Zip","Defrag"]}
for cat,exs in data.items():
    print(f"{cat}: {', '.join(exs)}")
A24:
sw={"Windows":"System","Photoshop":"Application","BIOS":"System","Chrome":"Application"}
for s,t in sw.items():
    print(f"{s} → {t}")
A25:
rows=[("Translation","Entire program","Line by line"),("Speed","Faster","Slower"),("Error report","After full scan","At first error")]
print(f"{"Feature":20} {"Compiler":15} {"Interpreter":15}")
for r in rows:
    print(f"{r[0]:20} {r[1]:15} {r[2]:15}")
A26:
files=["app.exe","driver.sys","notes.docx","game.dll"]
exts={"exe":"Application","sys":"System","dll":"System Library","docx":"Document"}
for f in files:
    ext=f.split(".")[-1]
    print(f"{f} → {exts.get(ext,"Unknown")}")
A27:
valid_keys=["ABC123","XYZ789","PRO456"]
key=input("Enter license key: ")
if key in valid_keys:
    print("License valid. Software activated.")
else:
    print("Invalid key. Please purchase.")
A28:
sw=[("OS","system"),("Word","app"),("Driver","system"),("Excel","app"),("BIOS","system")]
sys=sum(1 for _,t in sw if t=="system")
app=sum(1 for _,t in sw if t=="app")
print(f"System: {sys}, Application: {app}")
A29:
software={"name":"CBSEMOCK Suite","version":"2.5.1","type":"Application","license":"Freeware"}
for k,v in software.items():
    print(f"{k.capitalize():12}: {v}")
A30:
import time
code=[f"x={i}*{i}" for i in range(1000)]
t=time.time()
for line in code: exec(line)
print(f"Interpreted: {(time.time()-t)*1000:.2f} ms for {len(code)} lines")
Unit 1 · Computer Systems & Organisation
Operating System
The OS is the master program that manages all hardware resources and provides an environment for other programs to run.
2
Marks

Functions of Operating System

3.1
OS Kernel Process Management CPU scheduling, multitasking Memory Management RAM allocation, paging File Management Create/delete/organise files Device Management I/O device drivers Security Login, passwords, access control User Interface CLI (terminal) / GUI (windows)

Types of Operating Systems

3.2
TypeDescriptionExample
Batch OSJobs collected in batches, processed without interactionEarly IBM mainframes
Time-Sharing OSMultiple users share CPU time simultaneouslyUNIX, Linux servers
Real-Time OS (RTOS)Processes data instantly with strict time constraintsAir traffic control, pacemakers
Multi-User OSMultiple users access the same computer simultaneouslyLinux, Windows Server
Multi-Tasking OSMultiple programs run concurrentlyWindows 10/11, macOS
Distributed OSMultiple computers work together as one systemGoogle's infrastructure
Mobile OSDesigned for smartphones and tabletsAndroid, iOS
Embedded OSBuilt into devices, minimal, specific purposeSmart TV OS, ATM OS
📌 Remember for Exam
  • OS acts as an interface between user and hardware.
  • The kernel is the core part of the OS that manages hardware directly.
  • CLI (Command Line Interface) = text commands. GUI (Graphical User Interface) = icons & mouse.
  • Multitasking = multiple tasks on ONE CPU. Multiprocessing = multiple CPUs.
  • RTOS must respond within a guaranteed time — used in critical systems like aircraft, rockets.
  • Examples of OS: Windows, Linux, macOS, Android, iOS, Ubuntu, UNIX.

Topic Test: Network Concepts & Security

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Full form of LAN:
  • (a) Large Area Network
  • (b) Local Area Network
  • (c) Linked Area Network
  • (d) Light Area Network
[1 mark]
Q2.
Which topology connects all nodes to a central hub?
  • (a) Ring
  • (b) Bus
  • (c) Star
  • (d) Mesh
[1 mark]
Q3.
Which device connects two different networks?
  • (a) Hub
  • (b) Switch
  • (c) Router
  • (d) Repeater
[1 mark]
Q4.
HTTP stands for:
  • (a) HyperText Transfer Protocol
  • (b) HyperText Transmission Protocol
  • (c) High Transfer Protocol
  • (d) Hyper Terminal Protocol
[1 mark]
Q5.
Which is NOT a network protocol?
  • (a) FTP
  • (b) SMTP
  • (c) HTTP
  • (d) JPEG
[1 mark]
Q6.
Firewall is used for:
  • (a) Speeding up internet
  • (b) Blocking unauthorised access
  • (c) Compressing data
  • (d) Routing packets
[1 mark]
Q7.
Which network covers the largest area?
  • (a) LAN
  • (b) MAN
  • (c) WAN
  • (d) PAN
[1 mark]
Q8.
A cookie in web context is:
  • (a) A virus
  • (b) Small data stored by browser
  • (c) A network protocol
  • (d) A type of firewall
[1 mark]
Q9.
Which layer of OSI model handles routing?
  • (a) Physical
  • (b) Data Link
  • (c) Network
  • (d) Transport
[1 mark]
Q10.
Phishing is:
  • (a) A fishing game
  • (b) Fraudulent attempt to steal credentials
  • (c) A network protocol
  • (d) A type of encryption
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
What is the difference between LAN, MAN, and WAN?
[2 marks]
Q12.
What is the output of the following?
Name the 7 layers of the OSI model.
[2 marks]
Q13.
What is the output of the following?
What is an IP address? Give an example.
[2 marks]
Q14.
What is the output of the following?
Difference between hub and switch.
[2 marks]
Q15.
What is the output of the following?
What is a MAC address?
[2 marks]
Q16.
What is the output of the following?
What is the difference between HTTP and HTTPS?
[2 marks]
Q17.
What is the output of the following?
What is bandwidth?
[2 marks]
Q18.
What is the output of the following?
Name two types of network topology and their advantages.
[2 marks]
Q19.
What is the output of the following?
What is DNS?
[2 marks]
Q20.
What is the output of the following?
What is a VPN?
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write a program to validate an IPv4 address format.
[3 marks]
Q22.
Simulate a simple packet with source, destination, and data.
[3 marks]
Q23.
Check if a URL is HTTP or HTTPS.
[3 marks]
Q24.
Build a dictionary of protocols and their port numbers.
[3 marks]
Q25.
Simulate a simple firewall that blocks certain IPs.
[3 marks]
Q26.
Calculate data transfer time given file size and bandwidth.
[3 marks]
Q27.
Detect phishing keywords in an email subject.
[3 marks]
Q28.
Generate a simple network topology description.
[3 marks]
Q29.
Count packets sent and received in a simulation.
[3 marks]
Q30.
Write a basic port scanner simulation.
[3 marks]
A1: (b) — LAN = Local Area Network — covers a small area like a building.
A2: (c) — Star topology: all devices connect to a central switch/hub.
A3: (c) — Router connects different networks and routes packets between them.
A4: (a) — HTTP = HyperText Transfer Protocol — used for web communication.
A5: (d) — JPEG is an image format, not a network protocol.
A6: (b) — Firewall monitors and filters incoming/outgoing network traffic for security.
A7: (c) — WAN (Wide Area Network) covers the largest geographic area — e.g., the Internet.
A8: (b) — Cookies are small text files stored by browser to remember session data.
A9: (c) — Network layer (Layer 3) handles logical addressing and routing.
A10: (b) — Phishing: fake emails/sites that trick users into revealing passwords/data.
A11: LAN: local (building), MAN: city-wide, WAN: countrywide or global.
A12: Physical, Data Link, Network, Transport, Session, Presentation, Application
A13: Unique numerical label for a device on a network. Example: 192.168.1.1
A14: Hub broadcasts to all ports; Switch sends data only to the target port (more efficient).
A15: Media Access Control address — unique hardware identifier assigned to a network card (e.g., 00:1A:2B:3C:4D:5E).
A16: HTTP: unsecured; HTTPS: encrypted using SSL/TLS for secure communication.
A17: The maximum rate of data transfer across a network path; measured in bps, Kbps, Mbps.
A18: Star: easy fault detection. Bus: simple, low cable cost.
A19: Domain Name System — translates domain names (google.com) to IP addresses.
A20: Virtual Private Network — creates encrypted tunnel over public internet for secure remote access.
A21:
ip=input("Enter IP: ")
parts=ip.split(".")
if len(parts)==4 and all(p.isdigit() and 0<=int(p)<=255 for p in parts):
    print("Valid IPv4")
else:
    print("Invalid IPv4")
A22:
packet={"src":"192.168.1.1","dst":"10.0.0.1","port":80,"data":"GET /index.html"}
for k,v in packet.items():
    print(f"{k.upper():8}: {v}")
A23:
url=input("URL: ")
if url.startswith("https"): print("Secure (HTTPS)")
elif url.startswith("http"): print("Not secure (HTTP)")
else: print("Unknown protocol")
A24:
protocols={"HTTP":80,"HTTPS":443,"FTP":21,"SSH":22,"SMTP":25,"DNS":53}
for p,port in protocols.items():
    print(f"{p:8}: Port {port}")
A25:
blocked=["192.168.1.100","10.0.0.5"]
requests=["192.168.1.1","192.168.1.100","172.16.0.1","10.0.0.5"]
for ip in requests:
    status="BLOCKED" if ip in blocked else "ALLOWED"
    print(f"{ip:16} → {status}")
A26:
size_mb=float(input("File size in MB: "))
bw_mbps=float(input("Bandwidth in Mbps: "))
time_sec=(size_mb*8)/bw_mbps
print(f"Transfer time: {time_sec:.2f} seconds")
A27:
phishing=["urgent","verify","account suspended","click now","password"]
subject=input("Email subject: ").lower()
if any(w in subject for w in phishing):
    print("⚠ Possible phishing email!")
else:
    print("Looks safe.")
A28:
devices=["PC1","PC2","Laptop1","Printer"]
print("Star Topology:")
print("Hub")
for d in devices:
    print(f"  └─ {d}")
A29:
import random
packets=[(random.randint(1,3),random.randint(1,3)) for _ in range(10)]
sent=received=lost=0
for s,r in packets:
    sent+=s
    received+=r
    if s!=r: lost+=abs(s-r)
print(f"Sent:{sent} Received:{received} Lost:{lost}")
A30:
open_ports=[80,443,22,3306]
for port in range(20,90):
    status="OPEN" if port in open_ports else "closed"
    if status=="OPEN":
        print(f"Port {port}: {status}")
Unit 1 · Computer Systems & Organisation
Number Systems
Binary, Octal, Decimal, Hexadecimal — conversions and relationships. High weightage in exams.
4
Marks

The Four Number Systems

4.1
Number System Comparison Decimal Base 10 Digits: 0–9 42 in decimal = 4×10¹ + 2×10⁰ Human use everyday Subscript: (42)₁₀ Binary Base 2 Digits: 0, 1 42 = 101010 = 32+8+2 Computer language! Subscript: (101010)₂ Octal Base 8 Digits: 0–7 42 = (52)₈ = 5×8¹ + 2×8⁰ Used in Unix permissions chmod 755 = rwxr-xr-x Hexadecimal Base 16 Digits: 0–9, A–F 42 = (2A)₁₆ A=10, B=11…F=15 Used in colour codes #FF5733 = RGB colour

Conversion Methods — Step by Step

4.2
Decimal → Binary (Divide by 2)
Repeatedly divide by 2, record remainders, read bottom-up.

Example: 25 → Binary?
25÷2 = 12 R 1
12÷2 = 6 R 0
6÷2 = 3 R 0
3÷2 = 1 R 1
1÷2 = 0 R 1
Read upward: 11001
25₁₀ = 11001₂
Binary → Decimal (Positional)
Multiply each bit by 2^position (right to left from 0).

Example: 11001₂ → Decimal?
1×2⁴ + 1×2³ + 0×2² + 0×2¹ + 1×2⁰
= 16 + 8 + 0 + 0 + 1 = 25
11001₂ = 25₁₀
Decimal → Hex (Divide by 16)
Divide by 16, note remainders (10=A,11=B,12=C,13=D,14=E,15=F).

Example: 255 → Hex?
255÷16 = 15 R 15=F
15÷16 = 0 R 15=F
Read upward: FF
255₁₀ = FF₁₆
Hex → Binary (Each digit = 4 bits)
Convert each hex digit to its 4-bit binary equivalent.

Example: 2A₁₆ → Binary?
2 → 0010
A (=10) → 1010
Combine: 00101010
2A₁₆ = 00101010₂ = 42₁₀
Binary → Octal (Groups of 3)
Group bits from right in groups of 3, convert each group.

Example: 101010₂ → Octal?
101 | 010
5 | 2
Result: 52
101010₂ = 52₈
Binary → Hex (Groups of 4)
Group bits from right in groups of 4, convert each group.

Example: 11111111₂ → Hex?
1111 | 1111
F | F
Result: FF
11111111₂ = FF₁₆ = 255₁₀

Hexadecimal Digit Table

4.3
DecimalBinaryOctalHex
0000000
1000111
2001022
3001133
4010044
5010155
6011066
7011177
81000108
91001119
10101012A
11101113B
12110014C
13110115D
14111016E
15111117F
📌 Remember for Exam
  • Binary→Octal: group in 3s from right. Binary→Hex: group in 4s from right.
  • Hex digits beyond 9: A=10, B=11, C=12, D=13, E=14, F=15.
  • A=10, B=11, C=12, D=13, E=14, F=15 — memorise this for hex conversions.
  • 255₁₀ = FF₁₆ = 11111111₂ — most important conversion (max byte value).
  • Computers work only in binary (0 and 1). Other systems are used for human convenience.

Topic Test: Number Systems

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Decimal 10 in binary is:
  • (a) 1010
  • (b) 1100
  • (c) 1001
  • (d) 1011
[1 mark]
Q2.
Hexadecimal F equals decimal:
  • (a) 14
  • (b) 15
  • (c) 16
  • (d) 13
[1 mark]
Q3.
Binary 1111 in decimal is:
  • (a) 14
  • (b) 15
  • (c) 16
  • (d) 13
[1 mark]
Q4.
Octal 17 in decimal is:
  • (a) 14
  • (b) 15
  • (c) 16
  • (d) 17
[1 mark]
Q5.
Which base does hexadecimal use?
  • (a) 8
  • (b) 10
  • (c) 16
  • (d) 2
[1 mark]
Q6.
Decimal 255 in hexadecimal is:
  • (a) EF
  • (b) FF
  • (c) FE
  • (d) F0
[1 mark]
Q7.
Binary addition: 1011 + 0101 = ?
  • (a) 1111
  • (b) 10000
  • (c) 1010
  • (d) 10010
[1 mark]
Q8.
1 byte = ? bits
  • (a) 4
  • (b) 8
  • (c) 16
  • (d) 2
[1 mark]
Q9.
2's complement of 0110 is:
  • (a) 1010
  • (b) 1001
  • (c) 1010
  • (d) 1001
[1 mark]
Q10.
Decimal 0.5 in binary is:
  • (a) 0.01
  • (b) 0.1
  • (c) 0.11
  • (d) 0.001
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Convert 42 decimal to binary.
[2 marks]
Q12.
What is the output of the following?
Convert binary 11001101 to decimal.
[2 marks]
Q13.
What is the output of the following?
Convert hex 2A to decimal.
[2 marks]
Q14.
What is the output of the following?
Convert decimal 100 to octal.
[2 marks]
Q15.
What is the output of the following?
Add binary 1101 + 1011.
[2 marks]
Q16.
What is the output of the following?
Find 2's complement of 10110.
[2 marks]
Q17.
What is the output of the following?
Convert hex FF to binary.
[2 marks]
Q18.
What is the output of the following?
Convert octal 77 to decimal.
[2 marks]
Q19.
What is the output of the following?
Convert decimal 0.625 to binary.
[2 marks]
Q20.
What is the output of the following?
Subtract binary 1010 - 0011 using 2's complement.
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write a program to convert decimal to binary without using bin().
[3 marks]
Q22.
Convert decimal to octal without using oct().
[3 marks]
Q23.
Convert decimal to hexadecimal without using hex().
[3 marks]
Q24.
Convert binary string to decimal.
[3 marks]
Q25.
Write an all-in-one number system converter.
[3 marks]
Q26.
Add two binary numbers given as strings.
[3 marks]
Q27.
Find 1's complement of a binary number.
[3 marks]
Q28.
Find 2's complement of a binary number.
[3 marks]
Q29.
Convert hexadecimal to binary.
[3 marks]
Q30.
Print a conversion table for decimal 0-15.
[3 marks]
A1: (a) — 10 = 8+2 = 1010₂
A2: (b) — F in hex = 15 in decimal (A=10, B=11, C=12, D=13, E=14, F=15).
A3: (b) — 1111₂ = 8+4+2+1 = 15
A4: (b) — 17₈ = 1×8 + 7 = 15
A5: (c) — Hexadecimal uses base 16 with digits 0-9 and A-F.
A6: (b) — 255 = 15×16 + 15 = FF₁₆
A7: (b) — 1011+0101 = 1 0000 = 16 decimal
A8: (b) — 1 byte = 8 bits by definition.
A9: (c) — 1's complement of 0110 = 1001; add 1 → 1010
A10: (b) — 0.5 × 2 = 1.0 → binary 0.1
A11: 42 = 32+8+2 = 101010₂
A12: 128+64+8+4+1 = 205
A13: 2×16 + 10 = 42
A14: 100 ÷ 8 = 12 rem 4; 12 ÷ 8 = 1 rem 4; 1 ÷ 8 = 0 rem 1 → 144₈
A15: 1101 + 1011 = 11000 (carry: 1+1=10)
A16: 1's complement = 01001; add 1 → 01010
A17: F=1111; FF = 11111111₂
A18: 7×8 + 7 = 63
A19: 0.625×2=1.25→1; 0.25×2=0.5→0; 0.5×2=1.0→1 → 0.101₂
A20: 2's comp of 0011 = 1101; 1010+1101 = 10111 → ignore carry → 0111 = 7
A21:
n=int(input("Decimal: "))
b=""
while n>0:
    b=str(n%2)+b
    n//=2
print("Binary:",b or "0")
A22:
n=int(input("Decimal: "))
o=""
while n>0:
    o=str(n%8)+o
    n//=8
print("Octal:",o or "0")
A23:
n=int(input("Decimal: "))
h="0123456789ABCDEF"
s=""
while n>0:
    s=h[n%16]+s
    n//=16
print("Hex:",s or "0")
A24:
b=input("Binary: ")
d=0
for bit in b:
    d=d*2+int(bit)
print("Decimal:",d)
A25:
n=int(input("Enter decimal: "))
print(f"Binary : {bin(n)[2:]}")
print(f"Octal  : {oct(n)[2:]}")
print(f"Hex    : {hex(n)[2:].upper()}")
A26:
a=input("Binary 1: ")
b=input("Binary 2: ")
result=bin(int(a,2)+int(b,2))[2:]
print("Sum:",result)
A27:
b=input("Binary: ")
comp="".join("1" if c=="0" else "0" for c in b)
print("1's complement:",comp)
A28:
b=input("Binary: ")
ones="".join("1" if c=="0" else "0" for c in b)
two=bin(int(ones,2)+1)[2:]
print("2's complement:",two.zfill(len(b)))
A29:
h=input("Hex: ")
d=int(h,16)
b=bin(d)[2:]
print(f"Hex {h} = Binary {b}")
A30:
print(f"{"Dec":4} {"Bin":8} {"Oct":4} {"Hex":4}")
for i in range(16):
    print(f"{i:4} {bin(i)[2:]:>8} {oct(i)[2:]:4} {hex(i)[2:].upper():4}")
Unit 1 · Computer Systems & Organisation
Boolean Logic & Logic Gates
Boolean algebra, truth tables, logic gates (AND/OR/NOT/NAND/NOR/XOR), De Morgan's laws, and logic circuits.
4
Marks

Logic Gates — Symbols & Truth Tables

5.1
Logic Gates — Symbols and Truth Tables AND Gate AND A B | Out 0 0 | 0 0 1 | 0 1 0 | 0 1 1 | 1 Output=1 only if BOTH inputs=1 OR Gate OR A B | Out 0 0 | 0 0 1 | 1 1 0 | 1 1 1 | 1 Output=1 if ANY input=1 NOT Gate NOT A | Out 0 | 1 1 | 0 Inverts input (Complement) NAND Gate (NOT AND) A B | Out 0 0 | 1 0 1 | 1 1 0 | 1 1 1 | 0 Opposite of AND Universal gate NOR Gate (NOT OR) A B | Out 0 0 | 1 0 1 | 0 1 0 | 0 1 1 | 0 Opposite of OR Universal gate XOR Gate (Exclusive OR) A B | Out 0 0 | 0 0 1 | 1 1 0 | 1 1 1 | 0 Output=1 if inputs are DIFFERENT De Morgan's Laws (Very Important!) Law 1: NOT(A AND B) = (NOT A) OR (NOT B) NAND(A,B) = A̅ + B̅ Law 2: NOT(A OR B) = (NOT A) AND (NOT B) NOR(A,B) = A̅ · B̅ Memory trick: "Break the bar, change the operator" — when distributing NOT, flip AND↔OR NAND and NOR are called UNIVERSAL GATES — any circuit can be built using only NAND or only NOR gates.
📌 Remember for Exam
  • AND: output 1 ONLY when ALL inputs are 1 (like series circuit)
  • OR: output 1 if ANY input is 1 (like parallel circuit)
  • NOT: inverts the input. Only gate with ONE input.
  • NAND = NOT after AND. NOR = NOT after OR.
  • XOR: output 1 only when inputs are DIFFERENT (0,1 or 1,0).
  • De Morgan's Law 1: (A.B)' = A' + B'
  • De Morgan's Law 2: (A+B)' = A' . B'
  • NAND and NOR are universal gates (can implement any Boolean function).

Topic Test: Boolean Logic & Gates

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
AND gate output is 1 when:
  • (a) Any input is 1
  • (b) All inputs are 1
  • (c) All inputs are 0
  • (d) Any input is 0
[1 mark]
Q2.
De Morgan's law: (A·B)' = ?
  • (a) A'·B'
  • (b) A'+B'
  • (c) A'·B
  • (d) A+B'
[1 mark]
Q3.
NAND gate is NOT + ?
  • (a) OR
  • (b) AND
  • (c) XOR
  • (d) NOR
[1 mark]
Q4.
XOR gate output is 1 when:
  • (a) Both inputs same
  • (b) Both inputs different
  • (c) Both inputs 0
  • (d) Both inputs 1
[1 mark]
Q5.
A+A' = ?
  • (a) 0
  • (b) 1
  • (c) A
  • (d) A'
[1 mark]
Q6.
Which gate is called universal gate?
  • (a) AND
  • (b) OR
  • (c) NAND
  • (d) XOR
[1 mark]
Q7.
Boolean expression A·1 = ?
  • (a) 0
  • (b) 1
  • (c) A
  • (d) A'
[1 mark]
Q8.
NOR gate output is 1 when:
  • (a) Any input is 1
  • (b) All inputs are 0
  • (c) Both inputs differ
  • (d) All inputs 1
[1 mark]
Q9.
A+0 = ?
  • (a) 0
  • (b) 1
  • (c) A
  • (d) A'
[1 mark]
Q10.
The expression A·A = ?
  • (a) 0
  • (b) 1
  • (c) A
  • (d) A'
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Draw the truth table for XOR gate (2 inputs).
[2 marks]
Q12.
What is the output of the following?
Simplify: A·B + A·B'
[2 marks]
Q13.
What is the output of the following?
State De Morgan's theorems.
[2 marks]
Q14.
What is the output of the following?
What is a minterm? Give example for 2 variables.
[2 marks]
Q15.
What is the output of the following?
Simplify: (A+B)·(A+B')
[2 marks]
Q16.
What is the output of the following?
Name all Boolean laws.
[2 marks]
Q17.
What is the output of the following?
What is a canonical SOP form?
[2 marks]
Q18.
What is the output of the following?
Truth table for: F = A'B + AB'
[2 marks]
Q19.
What is the output of the following?
Convert F(A,B,C) = Σm(1,3,5,7) to SOP.
[2 marks]
Q20.
What is the output of the following?
What is the difference between SOP and POS?
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Generate truth table for AND, OR, NOT for 2 variables.
[3 marks]
Q22.
Generate truth table for XOR and XNOR.
[3 marks]
Q23.
Implement NAND and NOR using AND, OR, NOT.
[3 marks]
Q24.
Verify De Morgan's law for all input combinations.
[3 marks]
Q25.
Implement a half adder using gates.
[3 marks]
Q26.
Find all minterms of a 3-variable function F where output is 1.
[3 marks]
Q27.
Build a full adder from two half adders.
[3 marks]
Q28.
Verify Boolean absorption law: A + A·B = A.
[3 marks]
Q29.
Evaluate a Boolean expression given as string.
[3 marks]
Q30.
Implement a 2-to-1 multiplexer using Boolean logic.
[3 marks]
A1: (b) — AND gate: output 1 only when ALL inputs are 1.
A2: (b) — De Morgan: (A·B)' = A' + B'
A3: (b) — NAND = NOT-AND: inverted AND gate.
A4: (b) — XOR: output 1 when inputs are DIFFERENT (exclusive OR).
A5: (b) — Complement law: A + A' = 1 always.
A6: (c) — NAND and NOR are universal gates — any other gate can be made from them.
A7: (c) — Identity law: A·1 = A
A8: (b) — NOR = NOT-OR: output 1 only when ALL inputs are 0.
A9: (c) — Identity law: A+0 = A
A10: (c) — Idempotent law: A·A = A
A11: A B | Y 0 0 | 0 0 1 | 1 1 0 | 1 1 1 | 0
A12: A·B + A·B' = A·(B+B') = A·1 = A
A13: 1. (A+B)' = A'·B' 2. (A·B)' = A'+B'
A14: Minterm: product term where all variables appear; for A,B: m0=A'B', m1=A'B, m2=AB', m3=AB
A15: (A+B)·(A+B') = A+B·B' = A+0 = A
A16: Identity, Null, Idempotent, Complement, Commutative, Associative, Distributive, Absorption, De Morgan's
A17: Sum of minterms — each minterm has all variables in complemented or uncomplemented form. F = Σm(...)
A18: A=0,B=0→0; A=0,B=1→1; A=1,B=0→1; A=1,B=1→0 (same as XOR)
A19: F = A'B'C + A'BC + AB'C + ABC = C(A'B'+A'B+AB'+AB) = C·1 = C
A20: SOP: OR of AND terms (minterms); POS: AND of OR terms (maxterms)
A21:
print("A B AND OR NOT-A")
for a in [0,1]:
    for b in [0,1]:
        print(f"{a} {b}  {a&b}   {a|b}   {1-a}")
A22:
print("A B XOR XNOR")
for a in [0,1]:
    for b in [0,1]:
        xor=a^b
        print(f"{a} {b}  {xor}    {1-xor}")
A23:
def nand(a,b): return int(not(a and b))
def nor(a,b): return int(not(a or b))
for a in [0,1]:
    for b in [0,1]:
        print(f"A={a},B={b}: NAND={nand(a,b)}, NOR={nor(a,b)}")
A24:
print("A B (A+B)' A'·B' Match? (A·B)' A'+B' Match?")
for a in [0,1]:
    for b in [0,1]:
        lhs1=int(not(a or b))
        rhs1=(1-a)&(1-b)
        lhs2=int(not(a and b))
        rhs2=(1-a)|(1-b)
        print(f"{a} {b}    {lhs1}       {rhs1}       {lhs1==rhs1}    {lhs2}        {rhs2}       {lhs2==rhs2}")
A25:
def half_adder(a,b):
    s=a^b  # XOR
    c=a&b  # AND
    return s,c
print("A B | Sum Carry")
for a in [0,1]:
    for b in [0,1]:
        s,c=half_adder(a,b)
        print(f"{a} {b} |  {s}    {c}")
A26:
def F(a,b,c): return (not a and b) or (a and not b and c)
minterms=[]
for a in [0,1]:
    for b in [0,1]:
        for c in [0,1]:
            if F(a,b,c): minterms.append(4*a+2*b+c)
print("Minterms:",minterms)
A27:
def half_add(a,b): return a^b,a&b
def full_add(a,b,cin):
    s1,c1=half_add(a,b)
    s2,c2=half_add(s1,cin)
    return s2,c1|c2
print("A B Cin Sum Cout")
for a in [0,1]:
    for b in [0,1]:
        for c in [0,1]:
            s,co=full_add(a,b,c)
            print(f"{a} {b}  {c}   {s}   {co}")
A28:
print("A B | A+AB | A | Equal?")
for a in [0,1]:
    for b in [0,1]:
        lhs=a|(a&b)
        print(f"{a} {b} |   {lhs}   | {a} | {lhs==a}")
A29:
A,B,C=1,0,1
expr="A and not B or C"
result=eval(expr)
print(f"A={A},B={B},C={C}: {expr} = {int(result)}") 
A30:
def mux2to1(a,b,s):
    return (a and not s) or (b and s)
print("A B S | Out")
for a in [0,1]:
    for b in [0,1]:
        for s in [0,1]:
            print(f"{a} {b} {s} |  {int(mux2to1(a,b,s))}")
Unit 1 · Computer Systems & Organisation
Encoding Schemes
How text characters are stored as numbers — ASCII, ISCII, and Unicode (UTF-8, UTF-32).
2
Marks

Why Encoding?

6.1

Computers store everything as binary (0s and 1s). A character encoding scheme is a mapping — it assigns a unique number (code point) to every character so computers can store and exchange text consistently.

Character to Binary — How 'A' is Stored A Character you type → 65 ASCII code Decimal number assigned to 'A' ASCII: A=65, a=97 → 01000001 8-bit binary = 64 + 1 = 65 Stored in memory 1 byte per character → U+0041 Unicode point UTF-8 encoding: 0x41 (1 byte) Supports all languages!

ASCII, ISCII, and Unicode

6.2
FeatureASCIIISCIIUnicode (UTF-8/UTF-32)
Full nameAmerican Standard Code for Information InterchangeIndian Script Code for Information InterchangeUniversal Character Set
Bits7-bit (128 chars) or 8-bit (256 chars)8-bit (256 chars)UTF-8: 1–4 bytes; UTF-32: 4 bytes
LanguagesEnglish onlyIndian scripts (Hindi, Bengali, Tamil...)All languages + emoji (143,000+ chars)
A (uppercase)65 (01000001)Same as ASCII for EnglishU+0041
a (lowercase)97 (01100001)SameU+0061
Space3232U+0020
0 (digit)4848U+0030
Use todayLegacy systemsLimited — replaced by Unicode✅ Standard for the web (HTML, Python, etc.)
Key ASCII Values (Memorise!)
A–Z : 65–90
a–z : 97–122
0–9 : 48–57
Space: 32
Enter: 13
Difference (A to a): 32
ord('A') = 65 in Python
chr(65) = 'A'
Unicode UTF-8 vs UTF-32
UTF-8: Variable width (1–4 bytes). English chars = 1 byte only. Backward compatible with ASCII. Most used on web.

UTF-32: Fixed 4 bytes per character. Simpler to process but wastes memory for English.
Python Encoding Functions
ord('A') → 65 (char to number)
chr(65) → 'A' (number to char)
ord('a') - ord('A') → 32
Python 3 uses Unicode (UTF-8) by default for all strings.
📌 Remember for Exam
  • ASCII: 7-bit = 128 characters. Extended ASCII: 8-bit = 256 characters.
  • Capital letters start at 65 (A), lowercase at 97 (a). Difference = 32.
  • Digits 0–9 have ASCII codes 48–57 (not 0–9).
  • Unicode is the modern universal standard — Python 3, HTML, Java all use it.
  • UTF-8 is variable length (efficient). UTF-32 is fixed length (simple but wasteful).
  • ISCII was developed by CDAC (India) for Indian language scripts.

Topic Test: Problem Solving & Algorithms

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
An algorithm must be:
  • (a) Infinite
  • (b) Finite
  • (c) Hardware-specific
  • (d) In Python
[1 mark]
Q2.
Which symbol represents a decision in a flowchart?
  • (a) Rectangle
  • (b) Oval
  • (c) Diamond
  • (d) Parallelogram
[1 mark]
Q3.
Which is NOT a characteristic of an algorithm?
  • (a) Definiteness
  • (b) Finiteness
  • (c) Ambiguity
  • (d) Input
[1 mark]
Q4.
The starting/ending oval in a flowchart is called:
  • (a) Process
  • (b) Decision
  • (c) Terminal
  • (d) I/O
[1 mark]
Q5.
Pseudocode is:
  • (a) Actual programming code
  • (b) Machine code
  • (c) Informal high-level description
  • (d) Assembly language
[1 mark]
Q6.
Which sorting algorithm has O(n²) worst case?
  • (a) Merge Sort
  • (b) Quick Sort
  • (c) Bubble Sort
  • (d) All of these
[1 mark]
Q7.
Linear search worst case complexity:
  • (a) O(1)
  • (b) O(log n)
  • (c) O(n)
  • (d) O(n²)
[1 mark]
Q8.
Binary search works on:
  • (a) Any list
  • (b) Sorted list only
  • (c) Unsorted list only
  • (d) Linked list
[1 mark]
Q9.
A flowchart is:
  • (a) Programming language
  • (b) Graphical algorithm representation
  • (c) Only for loops
  • (d) Only for decisions
[1 mark]
Q10.
Which arrow symbol in flowchart shows flow direction?
  • (a) Rectangle
  • (b) Oval
  • (c) Arrow/Line
  • (d) Diamond
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Write an algorithm to find the largest of three numbers.
[2 marks]
Q12.
What is the output of the following?
List 5 characteristics of a good algorithm.
[2 marks]
Q13.
What is the output of the following?
Trace bubble sort on: [5,3,1,4,2]
[2 marks]
Q14.
What is the output of the following?
What is time complexity? Why does it matter?
[2 marks]
Q15.
What is the output of the following?
Write pseudocode to check if a number is prime.
[2 marks]
Q16.
What is the output of the following?
Describe binary search algorithm step by step.
[2 marks]
Q17.
What is the output of the following?
Name flowchart symbols and their meanings.
[2 marks]
Q18.
What is the output of the following?
Trace linear search for key=4 in [2,7,4,1,9].
[2 marks]
Q19.
What is the output of the following?
Write algorithm for factorial of N.
[2 marks]
Q20.
What is the output of the following?
What is the difference between algorithm and program?
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Implement bubble sort and show each pass.
[3 marks]
Q22.
Implement linear search with step-by-step output.
[3 marks]
Q23.
Implement binary search on a sorted list.
[3 marks]
Q24.
Find maximum and minimum in a list without built-in functions.
[3 marks]
Q25.
Count steps taken in linear vs binary search and compare.
[3 marks]
Q26.
Implement insertion sort.
[3 marks]
Q27.
Implement selection sort.
[3 marks]
Q28.
Check if an array is sorted.
[3 marks]
Q29.
Find second largest element.
[3 marks]
Q30.
Count comparisons in bubble sort.
[3 marks]
A1: (b) — An algorithm must be finite — it must terminate after a fixed number of steps.
A2: (c) — Diamond (rhombus) represents a decision/condition in a flowchart.
A3: (c) — Algorithms must be unambiguous — each step must be clear and precise.
A4: (c) — Oval/rounded rectangle is the Terminal symbol (Start/Stop).
A5: (c) — Pseudocode: informal, human-readable description of an algorithm.
A6: (d) — Bubble Sort is always O(n²); Merge is O(n log n); Quick worst-case is O(n²).
A7: (c) — Linear search checks each element — worst case visits all n elements.
A8: (b) — Binary search requires a sorted list to work correctly.
A9: (b) — Flowchart: diagrammatic representation of an algorithm using symbols.
A10: (c) — Flow lines/arrows show the direction of flow between steps.
A11: Step 1: Input A,B,C Step 2: If A>B and A>C then Largest=A Step 3: Else if B>C then Largest=B Step 4: Else Largest=C Step 5: Print Largest
A12: 1.Input 2.Output 3.Definiteness 4.Finiteness 5.Effectiveness
A13: Pass1:[3,1,4,2,5] Pass2:[1,3,2,4,5] Pass3:[1,2,3,4,5] Pass4:[1,2,3,4,5] Done
A14: Measure of how runtime grows with input size. Matters for efficiency with large data.
A15: Input N If N<2: Not prime For i=2 to √N: If N mod i=0: Not prime Print Prime
A16: low=0,high=n-1; While low≤high: mid=(low+high)//2; If arr[mid]==key: found; elif key<arr[mid]: high=mid-1; else: low=mid+1
A17: Oval=Start/Stop, Rectangle=Process, Diamond=Decision, Parallelogram=I/O, Arrow=Flow
A18: Check 2: No; Check 7: No; Check 4: Found at index 2
A19: Input N; fact=1; For i=1 to N: fact=fact×i; Print fact
A20: Algorithm: language-independent, logical steps. Program: algorithm written in a specific programming language.
A21:
arr=[64,34,25,12,22,11,90]
n=len(arr)
for i in range(n-1):
    for j in range(n-i-1):
        if arr[j]>arr[j+1]:
            arr[j],arr[j+1]=arr[j+1],arr[j]
    print(f"Pass {i+1}: {arr}")
A22:
arr=[10,25,3,47,8,15]
key=int(input("Search: "))
for i,v in enumerate(arr):
    print(f"Checking index {i}: {v}")
    if v==key:
        print(f"Found at index {i}")
        break
else:
    print("Not found")
A23:
arr=sorted([10,25,3,47,8,15,55,2])
key=int(input("Search: "))
lo,hi=0,len(arr)-1
while lo<=hi:
    mid=(lo+hi)//2
    print(f"Checking mid={mid}: {arr[mid]}")
    if arr[mid]==key: print("Found!"); break
    elif key<arr[mid]: hi=mid-1
    else: lo=mid+1
else: print("Not found")
A24:
arr=[3,1,4,1,5,9,2,6]
max_v=min_v=arr[0]
for x in arr[1:]:
    if x>max_v: max_v=x
    if x<min_v: min_v=x
print(f"Max:{max_v} Min:{min_v}")
A25:
import math
arr=list(range(1,101))
key=int(input("Search (1-100): "))
linear_steps=next(i+1 for i,v in enumerate(arr) if v==key)
binary_steps=math.floor(math.log2(len(arr)))+1
print(f"Linear steps: {linear_steps}\nBinary max steps: {binary_steps}")
A26:
arr=[12,11,13,5,6]
for i in range(1,len(arr)):
    key=arr[i]
    j=i-1
    while j>=0 and arr[j]>key:
        arr[j+1]=arr[j]
        j-=1
    arr[j+1]=key
    print(f"Step {i}: {arr}")
A27:
arr=[64,25,12,22,11]
for i in range(len(arr)):
    min_idx=i
    for j in range(i+1,len(arr)):
        if arr[j]<arr[min_idx]: min_idx=j
    arr[i],arr[min_idx]=arr[min_idx],arr[i]
    print(f"Step {i+1}: {arr}")
A28:
arr=[1,2,3,5,4]
is_sorted=all(arr[i]<=arr[i+1] for i in range(len(arr)-1))
print("Sorted" if is_sorted else "Not sorted")
A29:
arr=[10,5,8,20,3,15]
uniq=sorted(set(arr),reverse=True)
print("Second largest:",uniq[1] if len(uniq)>1 else "N/A")
A30:
arr=[5,1,4,2,8]
comparisons=0
n=len(arr)
for i in range(n-1):
    for j in range(n-i-1):
        comparisons+=1
        if arr[j]>arr[j+1]: arr[j],arr[j+1]=arr[j+1],arr[j]
print(f"Sorted: {arr}\nComparisons: {comparisons}")
Unit 2 · Programming in Python
Problem Solving & Algorithms
Steps of problem solving, algorithms, flowcharts, pseudocode — how to think before you code.
5
Marks

Steps in Problem Solving

7.1
1. AnalyseUnderstandthe problem 2. DesignAlgorithm &Flowchart 3. CodeWrite Pythonprogram 4. Test & DebugFind & fixerrors 5. MaintainUpdate &improve Document(throughout)

Algorithm Properties & Flowchart Symbols

7.2
Algorithm
A finite, step-by-step set of instructions to solve a problem. Every algorithm must be:

• Finite — must terminate
• Definite — each step is clear
• Input — zero or more inputs
• Output — at least one output
• Effective — steps are feasible
Flowchart Symbols
⬭ Oval — Start / Stop (Terminal)
▱ Parallelogram — Input / Output
▭ Rectangle — Process / Calculation
◇ Diamond — Decision (Yes/No)
○ Circle — Connector
→ Arrow — Flow direction
Pseudocode
English-like structured description of an algorithm. Not a real language, but uses programming concepts.

BEGIN
INPUT num
IF num > 0 THEN
  PRINT "Positive"
ELSE
  PRINT "Non-positive"
END IF
END

Flowchart: Sum of N Numbers

7.3
START INPUT N sum=0   i=1 i <= N ? Decision YES sum = sum + i i = i + 1 NO PRINT sum STOP ← loop back
📌 Remember for Exam
  • Algorithm must be finite — a program that runs forever is NOT an algorithm.
  • Flowchart diamond shape = decision. Always has YES and NO branches.
  • Pseudocode uses BEGIN/END, IF/ELSE/END IF, WHILE/DO/END WHILE, FOR/END FOR.
  • Three control structures: Sequence (one after another), Selection (if-else), Iteration (loops).
  • Debugging = finding and fixing errors. Syntax errors vs. Logic errors vs. Runtime errors.

Topic Test: Introduction to Python

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which keyword is used to define a function in Python?
  • (a) function
  • (b) def
  • (c) define
  • (d) fun
[1 mark]
Q2.
What is the output of type(3.14)?
  • (a) <class 'int'>
  • (b) <class 'float'>
  • (c) <class 'str'>
  • (d) <class 'double'>
[1 mark]
Q3.
Which is a valid variable name?
  • (a) 2name
  • (b) my_name
  • (c) my-name
  • (d) class
[1 mark]
Q4.
Python is:
  • (a) Compiled only
  • (b) Interpreted only
  • (c) Both compiled and interpreted
  • (d) Neither
[1 mark]
Q5.
What does // operator do?
  • (a) Division
  • (b) Floor division
  • (c) Modulo
  • (d) Power
[1 mark]
Q6.
Which function converts string to integer?
  • (a) str()
  • (b) float()
  • (c) int()
  • (d) chr()
[1 mark]
Q7.
Indentation in Python is:
  • (a) Optional
  • (b) For readability only
  • (c) Mandatory — defines blocks
  • (d) Only for comments
[1 mark]
Q8.
What is the output of 10 % 3?
  • (a) 3
  • (b) 1
  • (c) 3.33
  • (d) 0
[1 mark]
Q9.
Which comment syntax is correct in Python?
  • (a) // comment
  • (b) /* comment */
  • (c) # comment
  • (d) <!-- comment -->
[1 mark]
Q10.
What does print("Hello"*3) output?
  • (a) Hello3
  • (b) Hello Hello Hello
  • (c) HelloHelloHello
  • (d) Error
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
What is the output?
a = 5
b = 2
print(a**b, a//b, a%b)
[2 marks]
Q12.
What is the output of the following?
Find the output:
x = "Python"
print(x[0], x[-1], x[1:4])
[2 marks]
Q13.
What is the output of the following?
What is printed?
for i in range(2,10,3):
    print(i, end=" ")
[2 marks]
Q14.
What is the output of the following?
Predict output:
a,b = 10,3
print(a/b, a//b)
[2 marks]
Q15.
What is the output of the following?
What is the output?
print(bool(0), bool(""), bool([]))
[2 marks]
Q16.
What is the output of the following?
Find the output:
x = 5
if x > 3:
    print("A")
elif x > 1:
    print("B")
[2 marks]
Q17.
What is the output of the following?
Output?
n = 4
result = 1
while n > 0:
    result *= n
    n -= 1
print(result)
[2 marks]
Q18.
What is the output of the following?
What does this print?
print(type(10), type(10.0), type("10"))
[2 marks]
Q19.
What is the output of the following?
Output?
for i in range(3):
    for j in range(3):
        if i == j:
            print(i, end=" ")
[2 marks]
Q20.
What is the output of the following?
Find the output:
x = [1,2,3]
x.append(4)
print(len(x), x[-1])
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write a program to swap two numbers without a temp variable.
[3 marks]
Q22.
Check if a year is a leap year.
[3 marks]
Q23.
Print the Fibonacci sequence up to N terms.
[3 marks]
Q24.
Find GCD of two numbers using Euclidean algorithm.
[3 marks]
Q25.
Check if a string is a palindrome.
[3 marks]
Q26.
Calculate simple interest and compound interest.
[3 marks]
Q27.
Print multiplication table for a given number.
[3 marks]
Q28.
Count vowels and consonants in a string.
[3 marks]
Q29.
Find all prime numbers up to N using Sieve of Eratosthenes.
[3 marks]
Q30.
Build a simple calculator with +, -, *, /.
[3 marks]
A1: (b) — def keyword defines a function in Python.
A2: (b) — 3.14 is a float literal.
A3: (b) — my_name is valid; starts with letter, uses underscore.
A4: (c) — Python compiles to bytecode then interprets it (CPython).
A5: (b) — // is floor division — divides and rounds down to integer.
A6: (c) — int() converts a string or float to an integer.
A7: (c) — Python uses indentation to define code blocks (no braces).
A8: (b) — 10 mod 3 = 1 (remainder when 10 is divided by 3).
A9: (c) — Python uses # for single-line comments.
A10: (c) — String repetition: "Hello"*3 = "HelloHelloHello"
A11: 25 2 1
A12: P n yth
A13: 2 5 8
A14: 3.3333333333333335 3
A15: False False False
A16: A
A17: 24
A18: <class 'int'> <class 'float'> <class 'str'>
A19: 0 1 2
A20: 4 4
A21:
a=int(input("a: "))
b=int(input("b: "))
a,b=b,a
print(f"a={a}, b={b}")
A22:
y=int(input("Year: "))
if (y%4==0 and y%100!=0) or y%400==0:
    print("Leap year")
else:
    print("Not a leap year")
A23:
n=int(input("Terms: "))
a,b=0,1
for _ in range(n):
    print(a,end=" ")
    a,b=b,a+b
A24:
def gcd(a,b):
    while b: a,b=b,a%b
    return a
a=int(input("a: "))
b=int(input("b: "))
print("GCD:",gcd(a,b))
A25:
s=input("String: ")
if s==s[::-1]:
    print("Palindrome")
else:
    print("Not a palindrome")
A26:
p=float(input("Principal: "))
r=float(input("Rate%: "))
t=float(input("Time(yrs): "))
si=p*r*t/100
ci=p*(1+r/100)**t-p
print(f"SI: {si:.2f}  CI: {ci:.2f}")
A27:
n=int(input("Table of: "))
for i in range(1,11):
    print(f"{n} x {i:2} = {n*i:3}")
A28:
s=input("String: ").lower()
vowels="aeiou"
v=sum(1 for c in s if c in vowels)
k=sum(1 for c in s if c.isalpha() and c not in vowels)
print(f"Vowels:{v} Consonants:{k}")
A29:
n=int(input("N: "))
sieve=[True]*(n+1)
sieve[0]=sieve[1]=False
for i in range(2,int(n**0.5)+1):
    if sieve[i]:
        for j in range(i*i,n+1,i): sieve[j]=False
print([i for i in range(n+1) if sieve[i]])
A30:
a=float(input("a: "))
op=input("Operator: ")
b=float(input("b: "))
if op=="+": print(a+b)
elif op=="-": print(a-b)
elif op=="*": print(a*b)
elif op=="/" and b!=0: print(a/b)
else: print("Invalid")
Unit 2 · Programming in Python
Python Basics
Variables, data types, operators, input/output, type conversion — the building blocks of every Python program.
8
Marks

Python Data Types

8.1
Python Built-in Data Types int Integer Whole numbers 42 -7 0 float Floating Point Decimal numbers 3.14 -2.5 1.0e5 str String Text data "Hello" 'Python' """doc""" bool Boolean True/False only True False 5 > 3 → True complex Complex Number Real + Imaginary 3+4j 2-1j j = √(-1)

Variables, Keywords, Operators

8.2
Variables & Naming Rules
Variable = named memory location.

Rules: start with letter/underscore, only letters/digits/underscore, case-sensitive, cannot be a keyword.

Valid: name, _age, num1
Invalid: 2num, my-var, for
Python Keywords (33)
False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield
Type Conversion
Implicit: Python does it automatically
x = 5 + 2.0 → 7.0 (int→float)

Explicit: You convert manually
int("42") → 42
float(5) → 5.0
str(99) → "99"
bool(0) → False
input() and print()
name = input("Enter name: ")
input() always returns a STRING

n = int(input("Enter num: "))

print("Hello", name)
print(f"Age: {age}")
print(x, y, sep=", ")
print("Hi", end="")

Operators in Python

8.3
TypeOperatorsExampleResult
Arithmetic+ - * / // % **17 // 5   17 % 5   2**33   2   8
Comparison== != > < >= <=5 != 3   4 >= 4True   True
Logicaland or notTrue and False   not TrueFalse   False
Assignment= += -= *= /= //= %= **=x=5; x+=3x becomes 8
Bitwise& | ^ ~ << >>5 & 3   5 | 31   7
Identityis   is notx is NoneTrue/False
Membershipin   not in'a' in 'cat'True
⚡ Key distinction: / always gives float. // gives integer (floor division). Example: 7/2 = 3.5, 7//2 = 3, -7//2 = -4 (floors down).

🐍 Python Runner — Python Basics Programs

8.4
P1: Hello World
P2: Variables & Types
P3: Arithmetic Ops
P4: Type Conversion
P5: print() options
P6: Area Calculator
P7: Swap Variables
P8: Comparison Ops
P9: String Intro
P10: Multiple Assign
P1: Simple Interest
P2: Temperature Conv
P3: Speed & Time
P4: Bitwise Ops
P5: Division Types
P6: Circle Maths
P7: Type Inspector
P8: f-string Format
P9: is & in Ops
P10: Precedence
P1: EMI Calculator
P2: Base Conversion
P3: Walrus & Advanced
P4: Grade Report
P5: Number Classifier
P6: String Ops
P7: Compound Interest
P8: Unpacking
P9: Identity & Memory
P10: Expression Lab
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • input() always returns a string. Use int(input()) for numbers.
  • / = float division. // = integer (floor) division. % = remainder.
  • ** is power. 2**10 = 1024.
  • Operator precedence (high to low): ** → * / // % → + - → comparison → not → and → or
  • bool(0) = False. bool("")= False. bool(None) = False. Everything else is True.

Topic Test: Python Operators & Expressions

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
What is the result of not (5 > 3)?
  • (a) True
  • (b) False
  • (c) Error
  • (d) None
[1 mark]
Q2.
Which operator checks identity (same object)?
  • (a) ==
  • (b) is
  • (c) !=
  • (d) in
[1 mark]
Q3.
Operator precedence: 2 + 3 * 4 = ?
  • (a) 20
  • (b) 14
  • (c) 24
  • (d) 9
[1 mark]
Q4.
What does "in" operator check?
  • (a) Identity
  • (b) Membership
  • (c) Arithmetic
  • (d) Assignment
[1 mark]
Q5.
Result of 5 != 5:
  • (a) True
  • (b) False
  • (c) None
  • (d) Error
[1 mark]
Q6.
What is 2**10?
  • (a) 20
  • (b) 100
  • (c) 1024
  • (d) 512
[1 mark]
Q7.
Evaluate: (4>2) and (3<1)
  • (a) True
  • (b) False
  • (c) Error
  • (d) None
[1 mark]
Q8.
x = 10; x += 5; print(x)
  • (a) 5
  • (b) 10
  • (c) 15
  • (d) Error
[1 mark]
Q9.
Which has highest precedence?
  • (a) +
  • (b) -
  • (c) **
  • (d) *
[1 mark]
Q10.
Result of 15 // 4:
  • (a) 3
  • (b) 3.75
  • (c) 4
  • (d) 3.5
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Evaluate: 3 + 4 * 2 - 1 ** 2 / 1
[2 marks]
Q12.
What is the output of the following?
What is (True and False) or (not False)?
[2 marks]
Q13.
What is the output of the following?
Output: x=5; print(x>3, x==5, x!=4)
[2 marks]
Q14.
What is the output of the following?
Evaluate: 17 % 5 + 2 ** 3 // 3
[2 marks]
Q15.
What is the output of the following?
What is the result?
a = [1,2,3]
print(2 in a, 4 not in a)
[2 marks]
Q16.
What is the output of the following?
Find: x=10; y=3; print(x&y, x|y, x^y)
[2 marks]
Q17.
What is the output of the following?
Evaluate: bool(0) or bool("hello") and bool([])
[2 marks]
Q18.
What is the output of the following?
Output? x=7; x//=2; x**=2; print(x)
[2 marks]
Q19.
What is the output of the following?
What does x is y return when x=y=[]?
[2 marks]
Q20.
What is the output of the following?
Operator precedence order (highest to lowest) for: **, *, +, //, %, -, comparisons
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Demonstrate all arithmetic operators on two numbers.
[3 marks]
Q22.
Show operator precedence by evaluating with and without parentheses.
[3 marks]
Q23.
Use all comparison operators on two numbers.
[3 marks]
Q24.
Demonstrate all logical operators with truth table.
[3 marks]
Q25.
Demonstrate all bitwise operators.
[3 marks]
Q26.
Use augmented assignment operators.
[3 marks]
Q27.
Demonstrate membership operators with list, tuple, string.
[3 marks]
Q28.
Show identity operators with examples.
[3 marks]
Q29.
Write a program using all types of operators in one expression.
[3 marks]
Q30.
Calculate BODMAS step by step for a complex expression.
[3 marks]
A1: (b) — 5>3 is True; not True = False
A2: (b) — "is" checks if two names refer to the same object in memory.
A3: (b) — Multiplication before addition: 3*4=12, 12+2=14
A4: (b) — "in" checks membership — whether an item is in a sequence.
A5: (b) — 5 is equal to 5, so 5!=5 is False.
A6: (c) — 2**10 = 2^10 = 1024
A7: (b) — 4>2 is True, 3<1 is False; True AND False = False
A8: (c) — x+=5 means x=x+5=10+5=15
A9: (c) — ** (exponent) has highest precedence among arithmetic operators.
A10: (a) — 15//4 = 3 (floor division discards remainder).
A11: 3 + 8 - 1 = 10.0
A12: (False) or (True) = True
A13: True True True
A14: 2 + 8//3 = 2 + 2 = 4
A15: True True
A16: 10&3=2, 10|3=11, 10^3=9 → 2 11 9
A17: False or (True and False) = False or False = False
A18: x=7//2=3; x=3**2=9 → 9
A19: True — same object in memory (assignment makes them point to same list).
A20: ** > * > // > % > / > + > - > comparisons > not > and > or
A21:
a,b=int(input("a: ")),int(input("b: "))
print(f"+ {a+b}\n- {a-b}\n* {a*b}\n/ {a/b:.2f}\n// {a//b}\n% {a%b}\n** {a**b}")
A22:
expr1=2+3*4-1
expr2=(2+3)*(4-1)
expr3=2+(3*(4-1))
print(f"2+3*4-1 = {expr1}")
print(f"(2+3)*(4-1) = {expr2}")
print(f"2+(3*(4-1)) = {expr3}")
A23:
a,b=5,3
for op,res in [("==",a==b),(">",a>b),("<",a<b),(">=",a>=b),("<=",a<=b),("!=",a!=b)]:
    print(f"{a} {op} {b} = {res}")
A24:
for a in [True,False]:
    for b in [True,False]:
        print(f"{str(a):5} AND {str(b):5} = {a and b}; OR = {a or b}; NOT a = {not a}")
A25:
a,b=12,10
print(f"a={a} ({bin(a)})  b={b} ({bin(b)})")
print(f"AND: {a&b} ({bin(a&b)})")
print(f"OR:  {a|b} ({bin(a|b)})")
print(f"XOR: {a^b} ({bin(a^b)})")
print(f"NOT: {~a}")
print(f"<<1: {a<<1}  >>1: {a>>1}")
A26:
x=10
for op,val in [("+",3),("-",2),("*",4),("//",5),("%",3),("**",2)]:
    old=x
    if op=="+": x+=val
    elif op=="-": x-=val
    elif op=="*": x*=val
    elif op=="//": x//=val
    elif op=="%": x%=val
    elif op=="**": x**=val
    print(f"x{op}={val}: {old} → {x}")
A27:
lst=[1,2,3,4]
tup=(10,20,30)
s="Hello Python"
print(3 in lst, 5 not in lst)
print(20 in tup, 40 not in tup)
print("Python" in s, "Java" not in s)
A28:
a=[1,2,3]
b=a
c=[1,2,3]
print("b=a, so a is b:",a is b)
print("c=[1,2,3], a is c:",a is c)
print("a == c:",a==c)
A29:
a,b,c=10,3,True
result=((a+b*2)//5 >= 3) and c or (a%b != 0)
print(f"((10+3*2)//5 >= 3) and True or (10%3 != 0) = {result}")
A30:
expr="4 + 8 * (6 - 2) ** 2 / 16"
print(f"Expression: {expr}")
print(f"Step1: 6-2 = 4")
print(f"Step2: 4**2 = 16")
print(f"Step3: 8*16 = 128")
print(f"Step4: 128/16 = 8.0")
print(f"Step5: 4+8.0 = 12.0")
print(f"Result: {eval(expr)}")
Unit 2 · Programming in Python
Control Flow
if/elif/else, for loops, while loops, break, continue, pass, range() — directing the flow of your program.
10
Marks

if / elif / else

9.1
Syntax
if condition1:
    # block 1
elif condition2:
    # block 2
else:
    # block 3


Indentation (4 spaces) is mandatory in Python — it defines the block.
Nested if
if x > 0:
    if x % 2 == 0:
        print("Positive Even")
    else:
        print("Positive Odd")
else:
    print("Non-positive")
Ternary / One-liner
result = "Even" if n%2==0 else "Odd"

Equivalent to:
if n%2==0: result="Even"
else: result="Odd"

for Loop & range()

9.2
for Loop Flow Start More items in sequence? YES Get next item Execute loop body NO else block (optional) range(): range(5)→0,1,2,3,4     range(2,8)→2,3,4,5,6,7     range(1,10,2)→1,3,5,7,9     range(10,0,-2)→10,8,6,4,2

while Loop, break, continue, pass

9.3
StatementPurposeExample
while cond:Repeats while condition is Truewhile n > 0: n -= 1
breakExits the loop immediatelyExit when found
continueSkips rest of current iterationSkip even numbers
passDo nothing placeholderEmpty function/if body
for...elseelse runs if loop NOT broken by breakSearch and report if not found
while...elseelse runs if condition becomes False normallyCountdown then launch

🐍 Python Runner — Control Flow Programs

9.4
P1: Pos/Neg/Zero
P2: for range loop
P3: Countdown while
P4: Even Numbers
P5: Times Table
P6: Grade System
P7: break & continue
P8: Star Patterns
P9: List iteration
P10: while + list
P1: Prime Numbers
P2: Fibonacci
P3: Armstrong Nums
P4: for...else search
P5: Number Pyramid
P6: Digit Operations
P7: GCD and LCM
P8: Matrix Multiply
P9: Factorials
P10: Guessing Game
P1: Sieve Primes
P2: Collatz Sequence
P3: Digital Root
P4: Prime Factors
P5: Diamond Pattern
P6: Hailstone Stats
P7: FizzBuzz+
P8: Perfect Numbers
P9: Spiral Matrix
P10: Traffic Light
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • Python uses indentation (not braces) to define blocks. Wrong indent = IndentationError.
  • range(start, stop, step) — stop is EXCLUDED. range(1,6) → 1,2,3,4,5.
  • break = exit loop. continue = skip to next iteration. pass = do nothing.
  • for...else: the else runs only if the loop finished WITHOUT a break.
  • Infinite loop: while True: — must have a break somewhere to exit.

🔁 Loops & Nested Loops — Deep Dive

9.3
for Loop
Iterates over a sequence (list, string, range).
Loop variable takes each value one by one.
for i in range(1, 6):
    print(i)  # 1 2 3 4 5
while Loop
Runs as long as condition is True. Use when iteration count is unknown.
i = 1
while i <= 5:
    print(i)
    i += 1
Nested Loops
Loop inside a loop. Outer runs once, inner completes fully for each outer iteration.
for i in range(3):
    for j in range(3):
        print(i, j)
range() variations
range(5) → 0–4
range(1,6) → 1–5
range(1,10,2) → 1,3,5,7,9
range(10,0,-1) → 10 down to 1
Pattern Printing Logic
Outer loop = rows. Inner loop = columns. Use print(end=' ') to stay on same line. print() moves to next row.
for i in range(1,4):
    for j in range(i):
        print('*', end=' ')
    print()
Flow: Nested Loop Trace
i=0: j goes 0,1,2 → i=1: j goes 0,1,2 → i=2: j goes 0,1,2
Total iterations = outer × inner
3×3 nested → 9 total print()s
Nested Loop Flow of Execution — for i in range(3): for j in range(3): print(i,j) i = 0 (outer loop) j=0 → print(0,0) j=1 → print(0,1) j=2 → print(0,2) inner loop ends → i increments i = 1 (outer loop) j=0 → print(1,0) j=1 → print(1,1) j=2 → print(1,2) inner loop ends → i increments i = 2 (outer loop) j=0 → print(2,0) j=1 → print(2,1) j=2 → print(2,2) outer loop ends — program continues

Loops Programs

9.4
🔁 Loops & Patterns — Live Python Runner
Loading Python…
P1: Count 1 to 10
P2: Sum 1 to N
P3: Multiplication Table
P4: Countdown
P5: Factorial
P6: Even Numbers
P7: Star Triangle
P8: Number Triangle
P9: Digit Sum
P10: Powers Table
P1: Right Triangle
P2: Inverted Triangle
P3: Pyramid
P4: Diamond
P5: Floyd's Triangle
P6: Pascal's Triangle
P7: Primes with Nested Loop
P8: Times Table Grid
P9: Border Pattern
P10: Fibonacci Loop
P1: Hourglass
P2: Matrix Fill
P3: Armstrong Numbers
P4: Palindrome Range
P5: Sieve of Eratosthenes
P6: Collatz Sequence
P7: Number Staircase
P8: Perfect Numbers
P9: Anagram Checker
P10: Matrix Addition
OUTPUT
▶ Press "Run Code" to execute…
Loading Python…

Topic Test: Control Flow & Loops

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which statement skips the rest of the loop body?
  • (a) break
  • (b) continue
  • (c) pass
  • (d) return
[1 mark]
Q2.
What does "break" do in a loop?
  • (a) Skips current iteration
  • (b) Exits the loop
  • (c) Pauses loop
  • (d) Does nothing
[1 mark]
Q3.
Output of range(1,10,2):
  • (a) 1,3,5,7,9
  • (b) 1,2,3...9
  • (c) 2,4,6,8
  • (d) 1,3,5,7
[1 mark]
Q4.
Which loop is used when number of iterations is unknown?
  • (a) for
  • (b) while
  • (c) do-while
  • (d) for-else
[1 mark]
Q5.
What is the output of for i in range(3): pass?
  • (a) 0 1 2
  • (b) 1 2 3
  • (c) Nothing
  • (d) Error
[1 mark]
Q6.
for i in range(5): if i==3: break → last i printed?
  • (a) 4
  • (b) 3
  • (c) 2
  • (d) 5
[1 mark]
Q7.
What does for-else mean in Python?
  • (a) else only if for fails
  • (b) else runs if loop completes without break
  • (c) Always runs else
  • (d) else runs on error
[1 mark]
Q8.
Infinite loop condition:
  • (a) while True
  • (b) while False
  • (c) for i in []
  • (d) for i in range(0)
[1 mark]
Q9.
Range function: range(5) generates:
  • (a) 1 to 5
  • (b) 0 to 5
  • (c) 0 to 4
  • (d) 1 to 4
[1 mark]
Q10.
Nested loop: how many times does inner run for 3×3?
  • (a) 3
  • (b) 6
  • (c) 9
  • (d) 12
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Trace: for i in range(1,6): print(i*i, end=" ")
[2 marks]
Q12.
What is the output of the following?
Output?
i=10
while i>0:
    print(i,end=" ")
    i-=3
[2 marks]
Q13.
What is the output of the following?
What prints?
for i in range(5):
    if i%2==0: continue
    print(i,end=" ")
[2 marks]
Q14.
What is the output of the following?
Output?
for i in range(3):
    for j in range(3):
        print(i*j,end=" ")
    print()
[2 marks]
Q15.
What is the output of the following?
Trace?
n=1
while n<100:
    n*=2
print(n)
[2 marks]
Q16.
What is the output of the following?
Output?
for i in range(1,6):
    if i==3: break
else:
    print("Done")
print(i)
[2 marks]
Q17.
What is the output of the following?
What prints?
for i in range(5):
    pass
print(i)
[2 marks]
Q18.
What is the output of the following?
Count: how many times does this loop run?
for i in range(2,20,3): pass
[2 marks]
Q19.
What is the output of the following?
Output?
sum=0
for i in range(1,11):
    if i%2!=0: sum+=i
print(sum)
[2 marks]
Q20.
What is the output of the following?
Trace nested loop?
for i in "AB":
    for j in "12":
        print(i+j,end=" ")
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Print all prime numbers between 1 and 50.
[3 marks]
Q22.
Print the following pattern: * ** *** **** *****
[3 marks]
Q23.
Find the sum of all digits of a number.
[3 marks]
Q24.
Print multiplication table from 1 to 5 using nested loops.
[3 marks]
Q25.
Find Armstrong numbers between 1 and 1000.
[3 marks]
Q26.
Print a diamond pattern of stars (size 5).
[3 marks]
Q27.
Count occurrences of each digit in a number.
[3 marks]
Q28.
Print Floyd's triangle.
[3 marks]
Q29.
Guess the number game using while loop.
[3 marks]
Q30.
Print the following number pattern: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
[3 marks]
A1: (b) — continue skips the current iteration and moves to the next.
A2: (b) — break immediately exits the loop.
A3: (a) — range(1,10,2) starts at 1, ends before 10, step 2 → 1,3,5,7,9
A4: (b) — while loop continues as long as condition is True — used for unknown iterations.
A5: (c) — pass does nothing; loop runs but produces no output.
A6: (c) — Loop breaks when i==3, so last printed before break would be i=2.
A7: (b) — for-else: else block runs only if the loop finished without hitting break.
A8: (a) — while True creates an infinite loop — condition never becomes False.
A9: (c) — range(5) generates 0,1,2,3,4 — stops before 5.
A10: (c) — Outer runs 3 times, inner runs 3 times each → 3×3=9 total iterations.
A11: 1 4 9 16 25
A12: 10 7 4 1
A13: 1 3
A14: 0 0 0 0 1 2 0 2 4
A15: 128
A16: 3
A17: 4
A18: 6 times (2,5,8,11,14,17)
A19: 25 (sum of odd numbers 1-9)
A20: A1 A2 B1 B2
A21:
for n in range(2,51):
    for i in range(2,int(n**0.5)+1):
        if n%i==0: break
    else:
        print(n,end=" ")
A22:
for i in range(1,6):
    print("*"*i)
A23:
n=int(input("Number: "))
print(sum(int(d) for d in str(abs(n))))
A24:
print("  "*2,end="")
for j in range(1,6): print(f"{j:4}",end="")
print()
for i in range(1,6):
    print(f"{i:2}|",end="")
    for j in range(1,6):
        print(f"{i*j:4}",end="")
    print()
A25:
for n in range(1,1001):
    digits=str(n)
    p=len(digits)
    if sum(int(d)**p for d in digits)==n:
        print(n,end=" ")
A26:
n=5
for i in range(1,n+1):
    print(" "*(n-i)+"*"*(2*i-1))
for i in range(n-1,0,-1):
    print(" "*(n-i)+"*"*(2*i-1))
A27:
n=input("Number: ")
for d in "0123456789":
    c=n.count(d)
    if c: print(f"Digit {d}: {c} time(s)")
A28:
n=5
num=1
for i in range(1,n+1):
    for j in range(i):
        print(num,end=" ")
        num+=1
    print()
A29:
import random
secret=random.randint(1,10)
guess=0
attempts=0
while guess!=secret:
    guess=int(input("Guess (1-10): "))
    attempts+=1
    if guess<secret: print("Too low")
    elif guess>secret: print("Too high")
print(f"Correct in {attempts} attempts!")
A30:
for i in range(1,6):
    print(*range(1,i+1))
Unit 2 · Programming in Python
Strings
String creation, indexing, slicing, methods, string operations, formatting — everything about Python strings.
8
Marks

String Basics — Indexing & Slicing

10.1
String Indexing: s = "CBSEMOCK" Char Pos (+) Pos (−) C o m p u K i d s 0 1 2 3 4 5 6 7 8 -9 -8 -7 -6 -5 -4 -3 -2 -1 Slicing examples: s[0:5] = 'Compu'     s[5:] = 'Kids'     s[:5] = 'Compu'     s[-4:] = 'Kids'     s[::2] = 'CmuKd'     s[::-1] = 'sdiKupmoC' len(s) = 9    s[5] = 'K'    s[-1] = 's'    s[2:7:2] = 'muK'

String Methods — Quick Reference

10.2
MethodWhat it doesExample → Result
upper()All uppercase'hello'.upper() → 'HELLO'
lower()All lowercase'HELLO'.lower() → 'hello'
title()Title case (first letter cap)'hello world'.title() → 'Hello World'
capitalize()First letter upper only'hello WORLD'.capitalize() → 'Hello world'
strip()Remove leading/trailing whitespace' hi '.strip() → 'hi'
lstrip() / rstrip()Remove left/right whitespace' hi'.lstrip() → 'hi'
replace(old,new)Replace substring'cat'.replace('c','b') → 'bat'
find(sub)First index of sub (-1 if not found)'hello'.find('ll') → 2
count(sub)Count occurrences'banana'.count('a') → 3
split(sep)Split into list'a,b,c'.split(',') → ['a','b','c']
join(iterable)Join list with separator'-'.join(['a','b']) → 'a-b'
startswith(s)True if starts with s'Python'.startswith('Py') → True
endswith(s)True if ends with s'file.py'.endswith('.py') → True
isdigit()True if all digits'123'.isdigit() → True
isalpha()True if all letters'abc'.isalpha() → True
isalnum()True if letters or digits'abc12'.isalnum() → True
isupper() / islower()Check case'ABC'.isupper() → True
len(s)Length of stringlen('hello') → 5
in / not inMembership check'py' in 'python' → True
ord(c) / chr(n)Char ↔ ASCIIord('A')=65, chr(65)='A'

▶ String Methods — Click to Run

10.3

Click any method row to see it execute live:

Method What it does Example Run
.upper() .lower() Case conversion 'hello'.upper() → 'HELLO'
.strip() Remove leading/trailing spaces ' hi '.strip() → 'hi'
.replace() Replace substring 'abc'.replace('b','X') → 'aXc'
.split() .join() Split string / join list into string 'a,b'.split(',') → ['a','b']
.find() .index() .count() Search within string find returns -1 if not found
.startswith() .endswith() .is*() Boolean checks on string Returns True/False
.center() .ljust() .rjust() Alignment & padding 'hi'.center(8,'=') → '===hi==='
f-string .format() String formatting f'{x:.2f}' → 2 decimal places
Slicing [start:stop:step] Extract substring s[::-1] reverses the string
String operators +, *, in, not in, ord/chr 'ha'*3 → 'hahaha'
LIVE OUTPUT
▶ Click a row above to run it…

🐍 Python Runner — String Programs

10.4
P1: String Basics
P2: String Slicing
P3: Count Vowels
P4: Palindrome Check
P5: String Methods
P6: Split & Join
P7: ASCII Values
P8: String Formatting
P9: String Testing
P10: String Building
P1: Caesar Cipher
P2: Word Frequency
P3: Anagram Check
P4: Title Formatter
P5: Run-Length Encode
P6: Pig Latin
P7: String Compress
P8: Tokeniser
P9: Text Statistics
P10: Receipt Maker
P1: Wildcard Matcher
P2: Edit Distance
P3: Password Analyser
P4: Morse Code
P5: DNA Analyser
P6: Palindrome Subs
P7: Roman Numerals
P8: Substitution Cipher
P9: Longest Common Substr
P10: Text Justifier
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • Strings are immutable — you cannot change individual characters. You must create a new string.
  • Negative indexing: s[-1] = last, s[-2] = second-last, etc.
  • Slice: s[start:stop:step]. Reverse: s[::-1].
  • split() → list. join() → string. These are inverses of each other.
  • 'a' in 'banana' → True. Strings support in operator.
  • ord('A')=65, ord('a')=97, difference = 32. Used to convert case manually.

Topic Test: Python Strings

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Strings in Python are:
  • (a) Mutable
  • (b) Immutable
  • (c) Both
  • (d) Neither
[1 mark]
Q2.
"Hello"[1:4] gives:
  • (a) Hel
  • (b) ell
  • (c) ello
  • (d) Hell
[1 mark]
Q3.
Which method converts string to uppercase?
  • (a) up()
  • (b) upper()
  • (c) toUpper()
  • (d) capitalize()
[1 mark]
Q4.
"Python".find("th") returns:
  • (a) 2
  • (b) 3
  • (c) 4
  • (d) -1
[1 mark]
Q5.
What does split() do by default?
  • (a) Splits at comma
  • (b) Splits at space/whitespace
  • (c) Splits each character
  • (d) Splits at tab only
[1 mark]
Q6.
"hello".capitalize() gives:
  • (a) HELLO
  • (b) Hello
  • (c) hello
  • (d) hELLO
[1 mark]
Q7.
f"2+2={2+2}" outputs:
  • (a) 2+2=2+2
  • (b) 2+2={4}
  • (c) 2+2=4
  • (d) Error
[1 mark]
Q8.
Which operator repeats a string?
  • (a) +
  • (b) *
  • (c) **
  • (d) //
[1 mark]
Q9.
" hello ".strip() gives:
  • (a) " hello "
  • (b) hello
  • (c) hello
  • (d) hello
[1 mark]
Q10.
len("Python") returns:
  • (a) 5
  • (b) 6
  • (c) 7
  • (d) Error
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Output?
s="CBSEMOCK"
print(s[0],s[-1],s[5:])
[2 marks]
Q12.
What is the output of the following?
What prints?
s="hello world"
print(s.title(), s.upper())
[2 marks]
Q13.
What is the output of the following?
Find the output:
s="banana"
print(s.count("a"), s.index("n"))
[2 marks]
Q14.
What is the output of the following?
Output?
print(",".join(["a","b","c"]))
print("a,b,c".split(","))
[2 marks]
Q15.
What is the output of the following?
What prints?
s="Python 3.11"
print(s.replace("3.11","3.12"))
[2 marks]
Q16.
What is the output of the following?
Output?
for ch in "abc":
    print(ch.upper(),end="-")
[2 marks]
Q17.
What is the output of the following?
Find:
print("hello".center(11,"*"))
[2 marks]
Q18.
What is the output of the following?
Output?
s="abcdef"
print(s[::-1], s[::2])
[2 marks]
Q19.
What is the output of the following?
What prints?
print("is" in "This is Python")
[2 marks]
Q20.
What is the output of the following?
Output?
n=42
print(f"Number: {n:05d}, Hex: {n:#x}")
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Count vowels, consonants, digits, spaces in a string.
[3 marks]
Q22.
Reverse each word in a sentence.
[3 marks]
Q23.
Check if two strings are anagrams.
[3 marks]
Q24.
Find the most frequent character in a string.
[3 marks]
Q25.
Remove duplicate characters from a string.
[3 marks]
Q26.
Caesar cipher: encrypt a message.
[3 marks]
Q27.
Count words, sentences and average word length.
[3 marks]
Q28.
Extract all numbers from a mixed string.
[3 marks]
Q29.
Title case converter that handles apostrophes.
[3 marks]
Q30.
Build a simple password strength checker.
[3 marks]
A1: (b) — Strings are immutable — you cannot change characters in place.
A2: (b) — Slicing [1:4] gives characters at index 1,2,3 → "ell"
A3: (b) — str.upper() converts all characters to uppercase.
A4: (b) — "th" starts at index 3 in "Python".
A5: (b) — split() without arguments splits at any whitespace.
A6: (b) — capitalize(): first letter upper, rest lower.
A7: (c) — f-string evaluates expressions inside {}.
A8: (b) — "Hi"*3 = "HiHiHi"
A9: (b) — strip() removes leading and trailing whitespace.
A10: (b) — "Python" has 6 characters.
A11: C s Kids
A12: Hello World HELLO WORLD
A13: 3 2
A14: a,b,c ['a', 'b', 'c']
A15: Python 3.12
A16: A-B-C-
A17: ***hello***
A18: fedcba ace
A19: True
A20: Number: 00042, Hex: 0x2a
A21:
s=input("String: ")
v=sum(1 for c in s if c.lower() in "aeiou")
k=sum(1 for c in s if c.isalpha() and c.lower() not in "aeiou")
d=sum(1 for c in s if c.isdigit())
sp=s.count(" ")
print(f"Vowels:{v} Consonants:{k} Digits:{d} Spaces:{sp}")
A22:
s=input("Sentence: ")
result=" ".join(w[::-1] for w in s.split())
print(result)
A23:
a=input("String 1: ").lower().replace(" ","")
b=input("String 2: ").lower().replace(" ","")
print("Anagram" if sorted(a)==sorted(b) else "Not anagram")
A24:
s=input("String: ").replace(" ","")
freq={c:s.count(c) for c in set(s)}
max_c=max(freq,key=freq.get)
print(f"Most frequent: {max_c} ({freq[max_c]} times)")
A25:
s=input("String: ")
seen=set()
result="".join(c for c in s if c not in seen and not seen.add(c))
print(result)
A26:
msg=input("Message: ").lower()
shift=int(input("Shift: "))
result="".join(chr((ord(c)-97+shift)%26+97) if c.isalpha() else c for c in msg)
print("Encrypted:",result)
A27:
s=input("Text: ")
words=s.split()
sentences=s.count(".")+s.count("!")+s.count("?")
avg=sum(len(w.strip(".,!?")) for w in words)/len(words) if words else 0
print(f"Words:{len(words)} Sentences:{sentences} Avg length:{avg:.1f}")
A28:
import re
s=input("String: ")
nums=re.findall(r"\d+",s)
print("Numbers found:",[int(n) for n in nums])
A29:
s=input("String: ")
result=" ".join(w[0].upper()+w[1:].lower() if w else "" for w in s.split())
print(result)
A30:
import re
pwd=input("Password: ")
score=0
if len(pwd)>=8: score+=1
if re.search(r"[A-Z]",pwd): score+=1
if re.search(r"[a-z]",pwd): score+=1
if re.search(r"\d",pwd): score+=1
if re.search(r"[!@#$%]",pwd): score+=1
strength=["Very Weak","Weak","Fair","Strong","Very Strong","Excellent"][score]
print(f"Strength: {strength} ({score}/5)")
Unit 2 · Programming in Python
Lists
Mutable ordered sequences — creation, indexing, slicing, list methods, nested lists, list comprehensions.
10
Marks

List Structure & Indexing

11.1
marks = [85, 92, 78, 95, 88] 85 92 78 95 88 Index (+) 0 1 2 3 4 Index (−) -5 -4 -3 -2 -1 Slicing examples: marks[1:4] → [92,78,95]    marks[-2:] → [95,88]    marks[::2] → [85,78,88]    marks[::-1] → [88,95,78,92,85] len(marks)=5    marks[0]=85    marks[-1]=88    marks[1:3]=[92,78] (MUTABLE — marks[0]=99 is valid)

List Methods

11.2
MethodWhat it doesExample
append(x)Add x to end[1,2].append(3) → [1,2,3]
insert(i,x)Insert x at index i[1,3].insert(1,2) → [1,2,3]
extend(lst)Add all items of lst[1].extend([2,3]) → [1,2,3]
remove(x)Remove first occurrence of x[1,2,2,3].remove(2) → [1,2,3]
pop(i)Remove & return item at i (default last)[1,2,3].pop() → 3; list=[1,2]
sort()Sort in place (ascending by default)[3,1,2].sort() → [1,2,3]
sort(reverse=True)Sort descending[3,1,2].sort(reverse=True) → [3,2,1]
reverse()Reverse in place[1,2,3].reverse() → [3,2,1]
index(x)Index of first occurrence of x[10,20,30].index(20) → 1
count(x)Count occurrences of x[1,2,2,3].count(2) → 2
copy()Shallow copy of listb = a.copy()
clear()Remove all elements[1,2,3].clear() → []
del lst[i]Delete element at index idel a[0]
len(lst)Number of elementslen([1,2,3]) → 3
min/max/sumMin, max, sum of listmin([3,1,2])=1, sum([1,2,3])=6
💡 List Comprehension: [expr for item in iterable if condition]
e.g., squares = [x**2 for x in range(1,6)] → [1,4,9,16,25]
evens = [x for x in range(20) if x%2==0] → [0,2,4,6,8,10,12,14,16,18]

▶ List Methods — Click to Run

11.3
Method What it does Live Example Run
.append(x) Add item at end [1,2].append(3) → [1,2,3]
.insert(i, x) Insert at index i [1,3].insert(1,2)→[1,2,3]
.remove(x) .pop(i) Remove by value / by index pop() returns removed item
.sort() sorted() Sort in-place / return new sort() modifies original
.index() .count() Search & count in list index() raises ValueError if not found
.extend() + * Combine lists extend() vs append(): no nesting
.reverse() .copy() Reverse & copy list [::-1] returns new reversed
LIVE OUTPUT
▶ Click a row above to run it…

📊 2D Lists & Nested Lists

11.4
What is a 2D List?
A list of lists. Each element is itself a list (a row). Used to represent matrices, tables, grids.
matrix = [[1,2,3],[4,5,6],[7,8,9]]
matrix[0] → [1, 2, 3]
matrix[1][2] → 6
Creating 2D Lists
Hard-coded, or use nested list comprehension for dynamic creation.
# 3×3 zeros
m = [[0]*3 for _ in range(3)]
# ⚠️ [[0]*3]*3 is WRONG
# (all rows same object!)
Access & Modify
Use [row][col] indexing. Negative indices work on both dimensions.
m[1][2] = 99 # set row1, col2
m[-1][-1] # last element
m[0][:] # entire first row
Traversal
Nested for loops: outer = rows, inner = columns.
for row in matrix:
for val in row:
print(val, end=' ')
print()
▶ 2D LIST PROGRAMS — Click to Run
Matrix Addition
A=[[1,2],[3,4]]
B=[[5,6],[7,8]]
C=[[A[i][j]+B[i][j] for j in range(2)]
   for i in range(2)]
for row in C: print(row)  ▶ Run
Matrix Transpose
m=[[1,2,3],[4,5,6]]
# Transpose
t=[[m[i][j] for i in range(2)]
   for j in range(3)]
for r in t: print(r)  ▶ Run
Row & Column Sum
m=[[1,2,3],[4,5,6],[7,8,9]]
for i,row in enumerate(m):
    print(f'Row {i} sum:',sum(row))
for j in range(3):
    print(f'Col {j} sum:',
      sum(m[i][j] for i in range(3))) ▶ Run
Student Marks Table
students=[['Alice',85,90,78],
          ['Bob',72,68,95],
          ['Carol',91,88,84]]
for s in students:
    avg=sum(s[1:])/3
    print(s[0], avg)  ▶ Run
OUTPUT
▶ Click any code block above…

🐍 Python Runner — List Programs

11.5
P1: List Basics
P2: List Operations
P3: List Slicing
P4: Sorting
P5: List Search
P6: List Comprehension
P7: Nested Lists
P8: List Copy
P9: extend vs append
P10: Marks Analysis
P1: Bubble Sort
P2: Selection Sort
P3: Search Algorithms
P4: Matrix Operations
P5: Stack with List
P6: Flatten & Deep Copy
P7: Remove Duplicates
P8: Merge Sorted Lists
P9: Advanced Comprehension
P10: Inventory System
P1: Insertion Sort Trace
P2: Quicksort & Mergesort
P3: Spiral Traversal
P4: Sliding Window Max
P5: Kadane's Algorithm
P6: Two-Pointer
P7: List Rotation
P8: Count Inversions
P9: Polynomial Arithmetic
P10: Conway's Game of Life
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • Lists are mutable — elements can be changed after creation. Strings/tuples are immutable.
  • append() adds one item. extend() adds all items of an iterable. insert(i,x) adds at index.
  • pop() removes last. pop(0) removes first. remove(x) removes by value.
  • sort() changes list in-place; sorted(lst) returns a new sorted list.
  • Aliasing trap: b = a makes b point to same list. Use b = a.copy() or b = a[:] for independent copy.
  • List comprehension: [expr for x in lst if cond] — concise and Pythonic.

Topic Test: Python Lists

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Lists in Python are:
  • (a) Immutable
  • (b) Mutable
  • (c) Fixed size
  • (d) Only integers
[1 mark]
Q2.
[1,2,3].append(4) makes it:
  • (a) [1,2,3]
  • (b) [4,1,2,3]
  • (c) [1,2,3,4]
  • (d) Error
[1 mark]
Q3.
Which removes element by value?
  • (a) del
  • (b) pop()
  • (c) remove()
  • (d) discard()
[1 mark]
Q4.
list1 = [1,2]; list2 = list1; list2.append(3) → list1?
  • (a) [1,2]
  • (b) [1,2,3]
  • (c) Error
  • (d) [1,2,3,1,2,3]
[1 mark]
Q5.
"sorted()" vs "list.sort()":
  • (a) Same
  • (b) sorted() returns new list
  • (c) sort() returns new list
  • (d) Both modify in place
[1 mark]
Q6.
lst = [1,2,3,4,5]; lst[1:3] = [9,8] → lst?
  • (a) [1,9,8,4,5]
  • (b) [1,9,8,3,4,5]
  • (c) [9,8,1,4,5]
  • (d) Error
[1 mark]
Q7.
[1,2]*3 gives:
  • (a) [1,2,3]
  • (b) [1,2,1,2,1,2]
  • (c) Error
  • (d) 6
[1 mark]
Q8.
Which creates a shallow copy?
  • (a) list2=list1
  • (b) list2=list1.copy()
  • (c) list2=list1[:]
  • (d) Both b and c
[1 mark]
Q9.
[].append(1) returns:
  • (a) [1]
  • (b) None
  • (c) 1
  • (d) Error
[1 mark]
Q10.
List comprehension [x**2 for x in range(4)]:
  • (a) [0,1,4,9]
  • (b) [1,4,9,16]
  • (c) [0,1,2,3]
  • (d) Error
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Output?
lst=[10,20,30,40,50]
print(lst[1:4], lst[-2:])
[2 marks]
Q12.
What is the output of the following?
What prints?
lst=[1,2,3]
lst.insert(1,99)
print(lst)
[2 marks]
Q13.
What is the output of the following?
Find:
lst=[3,1,4,1,5,9,2,6]
print(lst.count(1), lst.index(4))
[2 marks]
Q14.
What is the output of the following?
Output?
lst=list(range(0,10,2))
lst.reverse()
print(lst)
[2 marks]
Q15.
What is the output of the following?
What prints?
a=[1,2,3]
b=[4,5,6]
a.extend(b)
print(a,b)
[2 marks]
Q16.
What is the output of the following?
Find the output:
lst=[5,3,1,4,2]
print(sorted(lst),lst)
[2 marks]
Q17.
What is the output of the following?
Output?
m=[[1,2],[3,4],[5,6]]
print(m[1][0], m[2][1])
[2 marks]
Q18.
What is the output of the following?
What prints?
lst=[1,2,3,4,5]
print([x*2 for x in lst if x%2!=0])
[2 marks]
Q19.
What is the output of the following?
Output?
nested=[[1,2,3],[4,5,6]]
for row in nested:
    print(sum(row))
[2 marks]
Q20.
What is the output of the following?
Find:
lst=[10,20,30]
lst[1]=99
del lst[0]
print(lst)
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Find second largest in a list without sorting.
[3 marks]
Q22.
Remove all duplicates from a list preserving order.
[3 marks]
Q23.
Flatten a 2D list into 1D.
[3 marks]
Q24.
Rotate a list by k positions.
[3 marks]
Q25.
Find intersection and union of two lists.
[3 marks]
Q26.
Matrix multiplication of two 2×2 matrices.
[3 marks]
Q27.
Sort a list of strings by length.
[3 marks]
Q28.
Find all pairs in a list that sum to a target.
[3 marks]
Q29.
Split a list into chunks of size n.
[3 marks]
Q30.
Transpose a matrix.
[3 marks]
A1: (b) — Lists are mutable — elements can be changed, added, or removed.
A2: (c) — append() adds element to the END of the list.
A3: (c) — remove(val) removes first occurrence of the given value.
A4: (b) — list2=list1 creates a reference, not a copy. Both point to same object.
A5: (b) — sorted() returns a new sorted list; sort() modifies in place and returns None.
A6: (a) — Slice assignment replaces indices 1,2 with 9,8.
A7: (b) — List repetition: [1,2]*3 = [1,2,1,2,1,2]
A8: (d) — .copy() and [:] both create shallow copies.
A9: (b) — append() modifies in place and returns None.
A10: (a) — [x**2 for x in range(4)] = [0,1,4,9]
A11: [20, 30, 40] [40, 50]
A12: [1, 99, 2, 3]
A13: 2 2
A14: [8, 6, 4, 2, 0]
A15: [1, 2, 3, 4, 5, 6] [4, 5, 6]
A16: [1, 2, 3, 4, 5] [5, 3, 1, 4, 2]
A17: 3 6
A18: [2, 6, 10]
A19: 6 15
A20: [99, 30]
A21:
lst=list(map(int,input("Numbers: ").split()))
max1=max2=float("-inf")
for x in lst:
    if x>max1: max2=max1;max1=x
    elif x>max2: max2=x
print("2nd largest:",max2)
A22:
lst=list(map(int,input("Numbers: ").split()))
seen=set()
result=[x for x in lst if x not in seen and not seen.add(x)]
print(result)
A23:
matrix=[[1,2,3],[4,5,6],[7,8,9]]
flat=[x for row in matrix for x in row]
print(flat)
A24:
lst=[1,2,3,4,5]
k=int(input("Rotate by: "))%len(lst)
print(lst[k:]+lst[:k])
A25:
a=list(map(int,input("List A: ").split()))
b=list(map(int,input("List B: ").split()))
print("Union:",list(set(a)|set(b)))
print("Intersection:",list(set(a)&set(b)))
A26:
A=[[1,2],[3,4]]
B=[[5,6],[7,8]]
C=[[sum(A[i][k]*B[k][j] for k in range(2)) for j in range(2)] for i in range(2)]
for row in C: print(row)
A27:
words=input("Words: ").split()
words.sort(key=len)
print(words)
A28:
lst=[1,2,3,4,5,6,7,8]
target=int(input("Target sum: "))
pairs=[(lst[i],lst[j]) for i in range(len(lst)) for j in range(i+1,len(lst)) if lst[i]+lst[j]==target]
print("Pairs:",pairs)
A29:
lst=list(range(1,11))
n=int(input("Chunk size: "))
chunks=[lst[i:i+n] for i in range(0,len(lst),n)]
print(chunks)
A30:
matrix=[[1,2,3],[4,5,6],[7,8,9]]
transposed=[[matrix[j][i] for j in range(3)] for i in range(3)]
for row in transposed: print(row)
Unit 2 · Programming in Python
Tuples
Immutable ordered sequences — creation, packing/unpacking, tuple methods, use cases vs lists, named tuples.
7
Marks

Tuple vs List — Key Comparison

12.1
FeatureTupleList
Syntax(1, 2, 3)[1, 2, 3]
Mutability❌ Immutable (cannot change)✅ Mutable (can change)
SpeedFaster (fixed size)Slower
MemoryLess memoryMore memory
Use as dict key✅ Yes (hashable)❌ No
MethodsOnly count(), index()Full set of methods
Use whenData should not change (coordinates, RGB)Data changes (shopping cart)

Tuple Operations

12.2
Creation
t1 = (1, 2, 3)
t2 = 1, 2, 3 (packing)
t3 = (5,) ← singleton (comma needed!)
t4 = tuple([1,2,3])
t5 = () ← empty tuple

⚠ (5) is just int 5, NOT a tuple!
✅ (5,) is a tuple with one element.
Packing & Unpacking
Packing:
point = 3, 4 → tuple (3,4)

Unpacking:
x, y = point → x=3, y=4

Extended unpacking:
a, *b, c = (1,2,3,4,5)
→ a=1, b=[2,3,4], c=5

Swap with tuple:
a, b = b, a ← Python idiom
Tuple Methods & Functions
t.count(x) → count x in t
t.index(x) → first index of x
len(t) → number of elements
min(t) → minimum value
max(t) → maximum value
sum(t) → sum of elements
sorted(t) → returns sorted list
t1 + t2 → concatenation
t * 3 → repetition
x in t → membership

🐍 Python Runner — Tuple Programs

12.3
P1: Tuple Basics
P2: Singleton Tuples
P3: Pack & Unpack
P4: Tuple Methods
P5: Concat & Repeat
P6: Tuple as Dict Key
P7: Convert List↔Tuple
P8: Points & RGB
P9: Tuple Iteration
P10: Tuple Sorting
P1: Student Records
P2: Multiple Returns
P3: zip() with Tuples
P4: Mutability Trap
P5: Cartesian Product
P6: Named Tuples
P7: Items as Tuples
P8: Fibonacci Unpacking
P9: Hashing & Frozenset
P10: Grade Statistics
P1: LRU Cache
P2: State Machine
P3: Interval Merging
P4: Functional Programming
P5: Graph with Tuples
P6: Memo with Tuple Keys
P7: Bisection Method
P8: Pipeline Processing
P9: Chess Board
P10: Event Scheduler
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • Tuples are immutable — once created, elements cannot be added, removed, or changed.
  • A singleton tuple must have a trailing comma: (5,). Writing (5) is just 5 (integer).
  • Tuples have only 2 methods: count() and index().
  • Tuple unpacking: a, b, c = (1, 2, 3) — very useful and Pythonic.
  • Tuples can be used as dictionary keys; lists cannot (lists are not hashable).
  • Use tuples for fixed data (coordinates, RGB, config values, function return multiple values).

Topic Test: Python Tuples

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Tuples are:
  • (a) Mutable
  • (b) Immutable
  • (c) Ordered and mutable
  • (d) Unordered
[1 mark]
Q2.
Which creates an empty tuple?
  • (a) ()
  • (b) tuple
  • (c) (,)
  • (d) {}
[1 mark]
Q3.
How to create a single-element tuple?
  • (a) (1)
  • (b) (1,)
  • (c) [1]
  • (d) {1}
[1 mark]
Q4.
tuple.count(x) returns:
  • (a) Index of x
  • (b) Number of x occurrences
  • (c) Removes x
  • (d) Error if not found
[1 mark]
Q5.
Which is NOT a tuple operation?
  • (a) Indexing
  • (b) Slicing
  • (c) append()
  • (d) Concatenation
[1 mark]
Q6.
t = (1,2,3); t[0] = 10 gives:
  • (a) (10,2,3)
  • (b) Error
  • (c) (1,2,3)
  • (d) (10,10,10)
[1 mark]
Q7.
Tuple unpacking: a,b,c = (1,2,3) → b = ?
  • (a) 1
  • (b) 2
  • (c) 3
  • (d) Error
[1 mark]
Q8.
(1,2,3) + (4,5) gives:
  • (a) (1,2,3,4,5)
  • (b) Error
  • (c) (5,7)
  • (d) (1,2,3)(4,5)
[1 mark]
Q9.
Tuples are faster than lists because:
  • (a) More features
  • (b) Less memory + immutable
  • (c) Larger size
  • (d) No reason
[1 mark]
Q10.
Which converts list to tuple?
  • (a) list()
  • (b) tuple()
  • (c) (list)
  • (d) toTuple()
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Output?
t=(10,20,30,40,50)
print(t[1:3], t[-1], t[::-1])
[2 marks]
Q12.
What is the output of the following?
What prints?
t=(1,2,3,2,4,2)
print(t.count(2), t.index(3))
[2 marks]
Q13.
What is the output of the following?
Find the output:
a,b,*c=(1,2,3,4,5)
print(a,b,c)
[2 marks]
Q14.
What is the output of the following?
Output?
t=(3,1,4,1,5,9)
print(min(t), max(t), sum(t), sorted(t))
[2 marks]
Q15.
What is the output of the following?
What prints?
t=(1,2)
t=t+(3,)
print(t)
[2 marks]
Q16.
What is the output of the following?
Output?
coords=[(1,2),(3,4),(5,6)]
for x,y in coords:
    print(x+y,end=" ")
[2 marks]
Q17.
What is the output of the following?
Find:
t1=(1,2,3)
t2=(3,4,5)
print(set(t1)&set(t2))
[2 marks]
Q18.
What is the output of the following?
Output?
t=((1,2),(3,4),(5,6))
print(t[1][1])
[2 marks]
Q19.
What is the output of the following?
What prints?
x=(1,2,3)
print(list(enumerate(x)))
[2 marks]
Q20.
What is the output of the following?
Output?
t=(5,3,8,1,9,2)
print(sorted(t)[:3])
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Create a tuple of squares of 1-10 using a generator.
[3 marks]
Q22.
Find the element with maximum frequency in a tuple.
[3 marks]
Q23.
Convert list of tuples to a dictionary.
[3 marks]
Q24.
Write a function returning multiple values as a tuple.
[3 marks]
Q25.
Zip two tuples and display as key-value pairs.
[3 marks]
Q26.
Sort a list of tuples by second element.
[3 marks]
Q27.
Unpack a nested tuple.
[3 marks]
Q28.
Find common elements between two tuples.
[3 marks]
Q29.
Build a tuple from user input of n numbers.
[3 marks]
Q30.
Swap values using tuple unpacking.
[3 marks]
A1: (b) — Tuples are immutable — cannot be modified after creation.
A2: (a) — () creates an empty tuple.
A3: (b) — Trailing comma is required: (1,) — without it, (1) is just an integer.
A4: (b) — count(x) returns number of times x appears in the tuple.
A5: (c) — append() is a list method; tuples are immutable.
A6: (b) — TypeError: tuples do not support item assignment.
A7: (b) — Tuple unpacking assigns positionally: a=1, b=2, c=3
A8: (a) — Tuple concatenation creates a new tuple.
A9: (b) — Tuples use less memory and CPython can optimise them as constants.
A10: (b) — tuple(lst) converts a list to a tuple.
A11: (20, 30) 50 (50, 40, 30, 20, 10)
A12: 3 2
A13: 1 2 [3, 4, 5]
A14: 1 9 23 [1, 1, 3, 4, 5, 9]
A15: (1, 2, 3)
A16: 3 7 11
A17: {3}
A18: 4
A19: [(0, 1), (1, 2), (2, 3)]
A20: [1, 2, 3]
A21:
t=tuple(x**2 for x in range(1,11))
print(t)
A22:
t=(1,2,3,2,4,2,5,1,1)
max_elem=max(set(t),key=t.count)
print(f"{max_elem} appears {t.count(max_elem)} times")
A23:
data=[("name","Alice"),("age",16),("grade","A")]
d=dict(data)
print(d)
A24:
def stats(lst):
    return min(lst),max(lst),sum(lst)/len(lst)
data=[10,25,3,47,8,15]
mi,mx,av=stats(data)
print(f"Min:{mi} Max:{mx} Avg:{av:.1f}")
A25:
keys=("name","age","city")
vals=("Alice",16,"Durgapur")
for k,v in zip(keys,vals):
    print(f"{k}: {v}")
A26:
data=[(3,"banana"),(1,"apple"),(2,"cherry")]
data.sort(key=lambda x:x[1])
for item in data:
    print(item)
A27:
t=((1,2),(3,4),(5,6))
for a,b in t:
    print(f"{a}+{b}={a+b}")
A28:
t1=(1,2,3,4,5)
t2=(3,4,5,6,7)
common=tuple(set(t1)&set(t2))
print("Common:",common)
A29:
n=int(input("How many numbers: "))
t=tuple(int(input(f"Number {i+1}: ")) for i in range(n))
print("Tuple:",t)
print("Sum:",sum(t))
A30:
a=int(input("a: "))
b=int(input("b: "))
print(f"Before: a={a}, b={b}")
a,b=b,a
print(f"After:  a={a}, b={b}")
Unit 2 · Programming in Python
Dictionaries
Key-value mappings — creation, access, methods, iteration, nested dicts, dict comprehensions.
10
Marks

Dictionary Structure

13.1
student = {'name':'Priya', 'roll':101, 'marks':92, 'grade':'A+'} Key Hash Value 'name' hash('name') 'Priya' 'roll' hash('roll') 101 'marks' hash('marks') 92 'grade' hash('grade') 'A+' Access: student['name'] → 'Priya'    student.get('roll') → 101    student.get('age','N/A') → 'N/A' Keys: student.keys() → dict_keys(['name','roll','marks','grade']) Values: student.values() → dict_values(['Priya', 101, 92, 'A+'])

Dictionary Methods

13.2
MethodWhat it doesExample → Result
keys()Returns all keys (view object)d.keys() → dict_keys([...])
values()Returns all values (view object)d.values() → dict_values([...])
items()Returns (key,value) pairsd.items() → dict_items([...])
get(key,default)Returns value; default if key missingd.get('age',0) → 0
update(d2)Add/overwrite from another dictd.update({'age':17})
pop(key)Remove key and return valued.pop('age') → 17
popitem()Remove and return last (k,v) paird.popitem() → ('grade','A+')
setdefault(k,v)Get value; set default if key missingd.setdefault('age',16) → 16
copy()Shallow copy of dictd2 = d.copy()
clear()Remove all itemsd.clear() → {}
del d[key]Delete a key-value pairdel d['name']
key in dCheck membership (checks KEYS)'name' in d → True
len(d)Number of key-value pairslen({'a':1,'b':2}) → 2
dict.fromkeys(seq,v)Create dict from sequence of keysdict.fromkeys(['a','b'],0) → {'a':0,'b':0}

▶ Dictionary Methods — Click to Run

13.3
Method What it does Live Example Run
.keys() .values() .items() View all keys / values / pairs Returns dict_view objects
.get(key, default) Safe access — no KeyError d.get('x',0) → 0 if not found
.pop() .popitem() .clear() Remove items pop() returns the removed value
.update() Merge another dict in Overwrites existing keys
Frequency Counter Classic dict use-case d.get(k,0)+1 pattern
Dict Comprehension Create dict from expression {k:v for k,v in ... if cond}
LIVE OUTPUT
▶ Click a row above to run it…

📦 Nested Dictionaries

13.4
What is a Nested Dict?
A dictionary where values are themselves dictionaries. Used to represent records, JSON-like data, grouped information.
student = {
  'name': 'Alice',
  'marks': {'Maths':90,'Sci':85},
  'address': {'city':'Durgapur'}
}
Accessing Nested Values
Chain [] operators. Use .get() at each level to avoid KeyError.
student['marks']['Maths'] # 90
student.get('marks',{}).get('Sci',0)
Modifying Nested Dict
Access inner dict then assign, or use update().
student['marks']['Eng'] = 88
student['address'].update({'state':'WB'})
Iterating Nested Dict
Outer loop over keys, inner loop over nested dict items.
for sub, mark in student['marks'].items():
  print(sub, ':', mark)
▶ NESTED DICT EXAMPLES — Click to Run
Student Record System
students={'S001':{'name':'Alice',
    'marks':{'M':90,'S':85}},
  'S002':{'name':'Bob',
    'marks':{'M':72,'S':68}}}
for sid,info in students.items():
    avg=sum(info['marks'].values())/2
    print(sid,info['name'],avg)  ▶ Run
School Departments
school={
  'Science':{'students':120,'teachers':8},
  'Commerce':{'students':90,'teachers':6}
}
for dept,info in school.items():
    r=info['students']//info['teachers']
    print(dept,'ratio 1:'+str(r))  ▶ Run
Update Nested Values
emp={'E01':{'name':'Ravi','sal':50000},
    'E02':{'name':'Priya','sal':60000}}
for v in emp.values():
    v['sal']=int(v['sal']*1.1)
for k,v in emp.items():
    print(k,v)  ▶ Run
Nested Dict Comprehension
table={i:{j:i*j for j in range(1,6)}
       for i in range(1,6)}
print('3x4 =',table[3][4])
print('5x5 =',table[5][5])
for i in range(1,4):
    print(f'Row {i}:',
      {j:table[i][j] for j in range(1,4)})  ▶ Run
OUTPUT
▶ Click any code block above…

🐍 Python Runner — Dictionary Programs

13.5
P1: Dict Basics
P2: Modify Dict
P3: Dict Iteration
P4: Frequency Counter
P5: Dict Comprehension
P6: Nested Dicts
P7: Membership
P8: Phone Book
P9: fromkeys & copy
P10: Merge Dicts
P1: Invert Dict
P2: Grouping Data
P3: Cipher with Dict
P4: Memoization
P5: Grade Book
P6: Word Index
P7: Nested Marksheet
P8: Sparse Matrix
P9: Trie (Dict-based)
P10: Election Counter
P1: LRU Cache
P2: Graph BFS/DFS
P3: Dijkstra's Algorithm
P4: Custom Counter
P5: Config Parser
P6: Symbol Table
P7: Huffman Encoding
P8: Hash-based Search
P9: Keyword Dispatcher
P10: TF-IDF Keywords
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • Dictionary is unordered (Python 3.7+ maintains insertion order but it's not like a list).
  • Keys must be immutable (strings, numbers, tuples). Lists cannot be keys!
  • d[key] raises KeyError if key is absent. d.get(key, default) is safer.
  • in operator checks keys only: 'name' in d → True (for key 'name').
  • Dict comprehension: {k:v for k,v in d.items() if condition}.
  • To iterate key-value pairs: for k, v in d.items(): — use items(), not just the dict.

Topic Test: Python Dictionaries

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Dictionaries store data as:
  • (a) Index-value
  • (b) Key-value
  • (c) Position-element
  • (d) Tag-content
[1 mark]
Q2.
What does dict.get("x") return if "x" not in dict?
  • (a) 0
  • (b) Error
  • (c) None
  • (d) False
[1 mark]
Q3.
Which creates an empty dictionary?
  • (a) {}
  • (b) dict
  • (c) []
  • (d) ()
[1 mark]
Q4.
dict.keys() returns:
  • (a) A list
  • (b) A tuple
  • (c) A dict_keys view
  • (d) A set
[1 mark]
Q5.
d = {"a":1}; d["b"] = 2 → d?
  • (a) {"a":1}
  • (b) {"a":1,"b":2}
  • (c) {"b":2}
  • (d) Error
[1 mark]
Q6.
Which method removes and returns a value by key?
  • (a) .remove()
  • (b) del
  • (c) .pop()
  • (d) discard()
[1 mark]
Q7.
Dictionaries (Python 3.7+) are:
  • (a) Unordered
  • (b) Ordered by insertion
  • (c) Sorted by key
  • (d) Random order
[1 mark]
Q8.
d.update({"x":10}) does:
  • (a) Replaces d
  • (b) Adds/updates keys in d
  • (c) Returns new dict
  • (d) Deletes old keys
[1 mark]
Q9.
Which is a valid dict key?
  • (a) [1,2]
  • (b) (1,2)
  • (c) {"a":1}
  • (d) All
[1 mark]
Q10.
len({"a":1,"b":2,"c":3}) returns:
  • (a) 3
  • (b) 6
  • (c) 2
  • (d) Error
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Output?
d={"x":10,"y":20,"z":30}
print(d["y"], d.get("w",0))
[2 marks]
Q12.
What is the output of the following?
What prints?
d={}
for i in range(3):
    d[i]=i**2
print(d)
[2 marks]
Q13.
What is the output of the following?
Find:
d={"a":1,"b":2,"c":3}
for k,v in d.items():
    print(k,v,end="|")
[2 marks]
Q14.
What is the output of the following?
Output?
d={"a":1,"b":2,"c":3}
d.pop("b")
print(sorted(d.keys()))
[2 marks]
Q15.
What is the output of the following?
What prints?
d={"one":1,"two":2,"three":3}
print({v:k for k,v in d.items()})
[2 marks]
Q16.
What is the output of the following?
Find the output:
d1={"a":1,"b":2}
d2={"b":3,"c":4}
d1.update(d2)
print(d1)
[2 marks]
Q17.
What is the output of the following?
Output?
d={"marks":[85,90,78]}
d["marks"].append(92)
print(d)
[2 marks]
Q18.
What is the output of the following?
What prints?
d={"a":1,"b":2,"c":3}
print(max(d, key=d.get))
[2 marks]
Q19.
What is the output of the following?
Find:
words="hello world hello python"
freq={}
for w in words.split():
    freq[w]=freq.get(w,0)+1
print(freq)
[2 marks]
Q20.
What is the output of the following?
Output?
d={i:i**2 for i in range(1,6)}
print(sum(d.values()))
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Word frequency counter for a paragraph.
[3 marks]
Q22.
Invert a dictionary (swap keys and values).
[3 marks]
Q23.
Student grade report using nested dictionary.
[3 marks]
Q24.
Group words by their first letter.
[3 marks]
Q25.
Merge two dictionaries and sum values of common keys.
[3 marks]
Q26.
Build a phone book application.
[3 marks]
Q27.
Count the frequency of each character in a string.
[3 marks]
Q28.
Find common keys in two dictionaries and show their values.
[3 marks]
Q29.
Sort a dictionary by value.
[3 marks]
Q30.
Build a simple inventory system using a nested dictionary.
[3 marks]
A1: (b) — Dictionary: stores key-value pairs; keys must be unique and immutable.
A2: (c) — .get() returns None by default if key is not found (no KeyError).
A3: (a) — {} creates an empty dictionary.
A4: (c) — dict.keys() returns a dict_keys view object.
A5: (b) — Adding a new key-value pair to dictionary.
A6: (c) — .pop(key) removes and returns the value; raises KeyError if key missing.
A7: (b) — Since Python 3.7, dicts maintain insertion order.
A8: (b) — update() merges key-value pairs into the dictionary.
A9: (b) — Keys must be immutable; tuples are immutable, lists and dicts are not.
A10: (a) — len() returns number of key-value pairs = 3.
A11: 20 0
A12: {0: 0, 1: 1, 2: 4}
A13: a 1|b 2|c 3|
A14: ['a', 'c']
A15: {1: "one", 2: "two", 3: "three"}
A16: {"a": 1, "b": 3, "c": 4}
A17: {"marks": [85, 90, 78, 92]}
A18: c
A19: {"hello": 2, "world": 1, "python": 1}
A20: 55
A21:
text=input("Enter text: ").lower()
freq={}
for w in text.split():
    freq[w]=freq.get(w,0)+1
for k,v in sorted(freq.items(),key=lambda x:-x[1]):
    print(f"{k}: {v}")
A22:
d={"a":1,"b":2,"c":3}
inverted={v:k for k,v in d.items()}
print(inverted)
A23:
students={"Alice":{"Math":90,"Sci":85},"Bob":{"Math":72,"Sci":68}}
for name,marks in students.items():
    avg=sum(marks.values())/len(marks)
    print(f"{name}: Avg={avg:.1f} Grade={"A" if avg>=80 else "B"}")
A24:
words=["apple","ant","ball","cat","cherry","banana"]
groups={}
for w in words:
    key=w[0]
    groups.setdefault(key,[]).append(w)
for k,v in sorted(groups.items()):
    print(f"{k}: {v}")
A25:
d1={"a":1,"b":2,"c":3}
d2={"b":10,"c":20,"d":30}
merged={**d1}
for k,v in d2.items():
    merged[k]=merged.get(k,0)+v
print(merged)
A26:
book={}
while True:
    cmd=input("add/search/quit: ")
    if cmd=="add":
        n=input("Name: ");p=input("Phone: ");book[n]=p
    elif cmd=="search":
        n=input("Name: ");print(book.get(n,"Not found"))
    elif cmd=="quit": break
print("Contacts:",len(book))
A27:
s=input("String: ")
freq={}
for c in s:
    freq[c]=freq.get(c,0)+1
for k,v in sorted(freq.items()):
    print(f"{repr(k)}: {v}")
A28:
d1={"a":1,"b":2,"c":3,"d":4}
d2={"b":20,"c":30,"e":50}
common=set(d1)&set(d2)
for k in common:
    print(f"Key {k}: d1={d1[k]}, d2={d2[k]}")
A29:
d={"banana":3,"apple":1,"cherry":2}
for k,v in sorted(d.items(),key=lambda x:x[1]):
    print(f"{k}: {v}")
A30:
inv={"Pen":{"qty":100,"price":5},"Book":{"qty":50,"price":80}}
for item,info in inv.items():
    total=info["qty"]*info["price"]
    print(f"{item:10} Qty:{info["qty"]:5} Price:{info["price"]:6} Total:{total:7}")
Unit 2 · Programming in Python
Modules in Python
Using Python's built-in modules — math, random, statistics, time, os, sys — and understanding import mechanisms.
8
Marks

Import Mechanisms

14.1
Import Syntax
import math → use as math.sqrt()

from math import sqrt → use as sqrt()

from math import sqrt, pi → multiple

from math import * → all (avoid!)

import math as m → alias: m.sqrt()

from math import sqrt as sq → aliased function
math module
math.pi = 3.14159…
math.e = 2.71828…
math.sqrt(x) → √x
math.ceil(x) → ⌈x⌉
math.floor(x) → ⌊x⌋
math.factorial(n) → n!
math.pow(x,y) → x^y (float)
math.log(x) → ln x
math.log10(x) → log₁₀ x
math.sin/cos/tan(x) → trig (radians)
math.degrees(r) / math.radians(d)
random module
random.random() → [0.0, 1.0)
random.randint(a,b) → int [a,b]
random.randrange(start,stop,step)
random.choice(seq) → random item
random.choices(seq,k=n) → n items (with replacement)
random.sample(seq,k) → k unique items
random.shuffle(lst) → in-place shuffle
random.seed(n) → reproducible results
random.uniform(a,b) → float [a,b]

statistics & Other Key Modules

14.2
ModuleKey Functions/AttributesUse case
statisticsmean(), median(), mode(), stdev(), variance()Statistical analysis
osgetcwd(), listdir(), mkdir(), path.exists(), path.join()File system operations
sysargv, path, version, exit(), stdin, stdoutSystem information
datetimedate.today(), datetime.now(), timedeltaDate/time operations
stringascii_letters, digits, punctuation, ascii_uppercaseString constants
timetime(), sleep(), strftime(), localtime()Time operations
collectionsCounter, defaultdict, OrderedDict, deque, namedtupleSpecialised containers
💡 __name__ == '__main__':
When a Python file is run directly, __name__ = '__main__'.
When imported as a module, __name__ = the module's filename.
Use if __name__ == '__main__': ... to write code that runs ONLY when the file is executed directly, not when imported.

🐍 Python Runner — Module Programs

14.3
P1: math Basics
P2: random Basics
P3: Trigonometry
P4: statistics Module
P5: Dice Simulator
P6: Import Styles
P7: string Module
P8: Lottery Generator
P9: Geometry with math
P10: collections.Counter
P1: Newton's Method
P2: Combinations & Permutations
P3: Monte Carlo Pi
P4: Random Walk
P5: defaultdict
P6: deque Operations
P7: Exam Analysis
P8: Card Game
P9: Custom Namespace
P10: Quadratic Solver
P1: Mandelbrot Fractal
P2: PRNG Implementation
P3: DFT (Discrete Fourier)
P4: Secure Password Generator
P5: T-Test Statistics
P6: Birthday Paradox
P7: Genetic Algorithm
P8: Number Theory
P9: Monty Hall Simulation
P10: Numerical Integration
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • import math then use math.sqrt(); OR from math import sqrt then use sqrt() directly.
  • Key constants: math.pi, math.e, math.inf.
  • math.ceil(3.2)=4 (rounds up); math.floor(3.9)=3 (rounds down).
  • random.randint(a,b) includes BOTH a and b. range(a,b) excludes b — different!
  • random.seed(n) makes results reproducible. Useful for testing.
  • if __name__ == '__main__': runs code only when the file is executed directly, not when imported.

Topic Test: Python Functions

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which keyword defines a function?
  • (a) func
  • (b) define
  • (c) def
  • (d) function
[1 mark]
Q2.
Default argument must be:
  • (a) First parameter
  • (b) Last parameter
  • (c) After non-defaults
  • (d) Before non-defaults
[1 mark]
Q3.
What does *args allow?
  • (a) Keyword arguments
  • (b) Variable positional arguments
  • (c) Only one arg
  • (d) Dictionary args
[1 mark]
Q4.
A function with no return statement returns:
  • (a) 0
  • (b) None
  • (c) Error
  • (d) False
[1 mark]
Q5.
Lambda functions:
  • (a) Can have multiple statements
  • (b) Are anonymous one-liners
  • (c) Require def keyword
  • (d) Cannot take arguments
[1 mark]
Q6.
Scope: a variable defined inside a function is:
  • (a) Global
  • (b) Local
  • (c) Both
  • (d) Class-level
[1 mark]
Q7.
Recursion requires:
  • (a) A loop
  • (b) A base case
  • (c) Two functions
  • (d) Global variables
[1 mark]
Q8.
What does **kwargs allow?
  • (a) Positional args
  • (b) Keyword arguments as dict
  • (c) One keyword arg
  • (d) Variable loops
[1 mark]
Q9.
global keyword is used to:
  • (a) Create global var
  • (b) Access/modify global var inside function
  • (c) Delete global var
  • (d) Pass global to function
[1 mark]
Q10.
Which is a pure function?
  • (a) Modifies global state
  • (b) Has side effects
  • (c) Returns same output for same input
  • (d) Reads from file
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Output?
def f(a,b=10):
    return a+b
print(f(5), f(5,3))
[2 marks]
Q12.
What is the output of the following?
What prints?
def f(*args):
    return sum(args)
print(f(1,2,3,4,5))
[2 marks]
Q13.
What is the output of the following?
Find the output:
def f(n):
    if n<=1: return n
    return f(n-1)+f(n-2)
print(f(6))
[2 marks]
Q14.
What is the output of the following?
Output?
x=10
def f():
    x=20
    print(x)
f()
print(x)
[2 marks]
Q15.
What is the output of the following?
What prints?
fn=lambda x,y: x if x>y else y
print(fn(5,8), fn(10,3))
[2 marks]
Q16.
What is the output of the following?
Find:
def f(lst=[]):
    lst.append(1)
    return lst
print(f(), f(), f())
[2 marks]
Q17.
What is the output of the following?
Output?
def outer(x):
    def inner(y):
        return x+y
    return inner
add5=outer(5)
print(add5(3))
[2 marks]
Q18.
What is the output of the following?
What prints?
def f(a,b,*c,**d):
    print(a,b,c,d)
f(1,2,3,4,x=5,y=6)
[2 marks]
Q19.
What is the output of the following?
Output?
def fact(n):
    return 1 if n==0 else n*fact(n-1)
print([fact(i) for i in range(6)])
[2 marks]
Q20.
What is the output of the following?
Find:
fns=[lambda x:x+i for i in range(3)]
print([f(0) for f in fns])
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write a recursive function for factorial.
[3 marks]
Q22.
Write a function with *args that computes statistics.
[3 marks]
Q23.
Implement a recursive binary search.
[3 marks]
Q24.
Create a function decorator that logs function calls.
[3 marks]
Q25.
Write a function that returns another function (closure).
[3 marks]
Q26.
Implement Tower of Hanoi recursively.
[3 marks]
Q27.
Write a memoized Fibonacci function.
[3 marks]
Q28.
Create a function with **kwargs for a student profile.
[3 marks]
Q29.
Implement a generator function for Fibonacci.
[3 marks]
Q30.
Write a higher-order function: apply a function n times.
[3 marks]
A1: (c) — "def" is the keyword to define a function in Python.
A2: (c) — Default arguments must come after all non-default arguments.
A3: (b) — *args allows a function to accept any number of positional arguments.
A4: (b) — Python functions return None implicitly if no return statement.
A5: (b) — Lambda: anonymous function with a single expression.
A6: (b) — Variables defined inside functions are local — not accessible outside.
A7: (b) — Recursive functions must have a base case to stop recursion.
A8: (b) — **kwargs collects keyword arguments into a dictionary.
A9: (b) — "global x" inside a function allows modifying x at module level.
A10: (c) — Pure function: same input always gives same output; no side effects.
A11: 15 8
A12: 15
A13: 8 (Fibonacci)
A14: 20 10
A15: 8 10
A16: [1] [1, 1] [1, 1, 1] (mutable default arg trap)
A17: 8
A18: 1 2 (3, 4) {'x': 5, 'y': 6}
A19: [1, 1, 2, 6, 24, 120]
A20: [2, 2, 2] (closure captures i by reference — final value is 2)
A21:
def factorial(n):
    if n==0 or n==1: return 1
    return n*factorial(n-1)
n=int(input("N: "))
print(f"{n}! = {factorial(n)}")
A22:
def stats(*nums):
    return min(nums),max(nums),sum(nums)/len(nums)
result=stats(10,25,3,47,8,15)
print(f"Min:{result[0]} Max:{result[1]} Avg:{result[2]:.1f}")
A23:
def bsearch(arr,key,lo,hi):
    if lo>hi: return -1
    mid=(lo+hi)//2
    if arr[mid]==key: return mid
    elif key<arr[mid]: return bsearch(arr,key,lo,mid-1)
    else: return bsearch(arr,key,mid+1,hi)
arr=sorted([10,25,3,47,8,15,55,2])
key=int(input("Search: "))
print("Found at index:",bsearch(arr,key,0,len(arr)-1))
A24:
def logger(fn):
    def wrapper(*args,**kwargs):
        print(f"Calling {fn.__name__} with {args}")
        result=fn(*args,**kwargs)
        print(f"Result: {result}")
        return result
    return wrapper
@logger
def add(a,b): return a+b
add(3,4)
A25:
def make_multiplier(n):
    def multiply(x):
        return x*n
    return multiply
double=make_multiplier(2)
triple=make_multiplier(3)
print(double(5), triple(5))
A26:
def hanoi(n,src,dst,aux):
    if n==1:
        print(f"Move disk 1: {src} → {dst}")
        return
    hanoi(n-1,src,aux,dst)
    print(f"Move disk {n}: {src} → {dst}")
    hanoi(n-1,aux,dst,src)
hanoi(3,"A","C","B")
A27:
memo={}
def fib(n):
    if n in memo: return memo[n]
    if n<=1: return n
    memo[n]=fib(n-1)+fib(n-2)
    return memo[n]
print([fib(i) for i in range(11)])
A28:
def profile(**kwargs):
    print("Student Profile:")
    for k,v in kwargs.items():
        print(f"  {k.capitalize():12}: {v}")
profile(name="Alice",age=16,grade="A",city="Durgapur")
A29:
def fib_gen(n):
    a,b=0,1
    for _ in range(n):
        yield a
        a,b=b,a+b
print(list(fib_gen(10)))
A30:
def apply_n(fn,n,x):
    for _ in range(n): x=fn(x)
    return x
double=lambda x:x*2
print(apply_n(double,5,1))  # 32
Unit 3 · Societal Impacts
Digital Society & Netiquette
Impact of computing on society, digital divide, e-waste, netiquette rules, and responsible digital citizenship.
6
Marks

Digital Society — Key Concepts

15.1
Digital Divide
Gap between people who have access to modern IT and those who do not.

Types:
• Social divide: rich vs. poor access
• Gender divide: men vs. women tech access
• Rural-urban divide: infrastructure gaps
• Age divide: elderly vs. youth digital literacy

Causes: poverty, illiteracy, lack of infrastructure, cost of devices, language barriers
Impact of Computing
Positive impacts:
• Better communication (email, video calls)
• E-commerce, online banking, e-governance
• E-learning, digital libraries, MOOCs
• Healthcare: telemedicine, medical records
• Agriculture: crop advisory, weather data

Negative impacts:
• Privacy invasion, data theft
• Job displacement by automation
• Internet addiction, screen time issues
• Spread of misinformation (fake news)
• Cyberbullying, online harassment
Netiquette
Net + Etiquette = rules for polite, responsible online behaviour.

Core rules:
1. Be respectful; no flaming or trolling
2. Use proper language (no ALL CAPS)
3. Protect others' privacy; don't share personal info
4. Give credit for shared content
5. Don't spam — send relevant messages only
6. Think before you post (permanent record)
7. Respect others' time and bandwidth
8. Share expert knowledge; help others learn
9. Respect others' beliefs and opinions
10. Forgive others' mistakes (especially newbies)

E-Waste & Digital Health

15.2
ConceptDefinitionExamples / Facts
E-WasteDiscarded electronic devices/componentsOld phones, batteries, CRTs, printers, keyboards
Toxic materialsHazardous substances in electronicsLead (CRT glass), Mercury (LCD), Cadmium (batteries), Arsenic
E-Waste disposalSafe recycling and disposal methodsAuthorised recyclers, take-back programmes, refurbishment
Digital healthMaintaining wellbeing in digital lifeScreen time limits, eye care, posture, digital detox
TechnomaniaExcessive dependence on technologyFOMO, nomophobia (fear of no phone), internet addiction
📌 Remember for Exam
  • Digital divide is the gap in access to information technology between different groups.
  • Netiquette = net + etiquette. Core rule: Treat others online as you would in real life.
  • Flaming = sending hostile messages online. Trolling = deliberately provoking others.
  • Spam = unsolicited bulk email. Never forward chain letters or click unknown links.
  • E-waste contains toxic heavy metals — must be disposed through authorised channels ONLY.
  • ALL CAPS in online communication = SHOUTING. Avoid it in messages and emails.

Topic Test: Exception Handling

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which block handles exceptions in Python?
  • (a) try
  • (b) except
  • (c) finally
  • (d) raise
[1 mark]
Q2.
Which exception is raised on dividing by zero?
  • (a) ValueError
  • (b) TypeError
  • (c) ZeroDivisionError
  • (d) ArithmeticError
[1 mark]
Q3.
What does "finally" block do?
  • (a) Runs only on error
  • (b) Runs only on success
  • (c) Always runs
  • (d) Skips on error
[1 mark]
Q4.
Which keyword raises an exception manually?
  • (a) throw
  • (b) raise
  • (c) except
  • (d) error
[1 mark]
Q5.
KeyError is raised when:
  • (a) Key not found in dict
  • (b) Wrong key type
  • (c) Empty dict
  • (d) List index out of range
[1 mark]
Q6.
Which is the base class for all exceptions?
  • (a) Error
  • (b) Exception
  • (c) BaseException
  • (d) RuntimeError
[1 mark]
Q7.
What does "except Exception as e" do?
  • (a) Ignores exception
  • (b) Catches and stores exception in e
  • (c) Raises e
  • (d) Renames exception
[1 mark]
Q8.
IndexError occurs when:
  • (a) Wrong type index
  • (b) Index out of range
  • (c) Empty list
  • (d) Negative index
[1 mark]
Q9.
try-except-else: else runs when:
  • (a) Exception occurs
  • (b) No exception occurs
  • (c) Always
  • (d) finally runs
[1 mark]
Q10.
TypeError is raised when:
  • (a) Wrong operation on type
  • (b) Division by zero
  • (c) Missing key
  • (d) File not found
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
What is output?
try:
    print(10/0)
except ZeroDivisionError:
    print("Cannot divide")
[2 marks]
Q12.
What is the output of the following?
Output?
try:
    x=int("abc")
except ValueError as e:
    print("Error:",e)
[2 marks]
Q13.
What is the output of the following?
What prints?
try:
    print("try")
finally:
    print("finally")
[2 marks]
Q14.
What is the output of the following?
Output?
try:
    lst=[1,2,3]
    print(lst[5])
except IndexError:
    print("Out of range")
else:
    print("OK")
[2 marks]
Q15.
What is the output of the following?
What is printed?
try:
    raise ValueError("bad value")
except ValueError as e:
    print(type(e).__name__, str(e))
[2 marks]
Q16.
What is the output of the following?
Output?
def safe_div(a,b):
    try:
        return a/b
    except ZeroDivisionError:
        return None
print(safe_div(10,2), safe_div(5,0))
[2 marks]
Q17.
What is the output of the following?
What prints?
try:
    d={"a":1}
    print(d["b"])
except KeyError as e:
    print(f"Key {e} missing")
[2 marks]
Q18.
What is the output of the following?
Output?
try:
    print("A")
except:
    print("B")
else:
    print("C")
finally:
    print("D")
[2 marks]
Q19.
What is the output of the following?
What is output?
for i in [2,1,0]:
    try:
        print(10//i,end=" ")
    except ZeroDivisionError:
        print("Err",end=" ")
[2 marks]
Q20.
What is the output of the following?
Output?
class CustomError(Exception): pass
try:
    raise CustomError("oops")
except CustomError as e:
    print("Custom:",e)
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write a safe division function using exception handling.
[3 marks]
Q22.
Handle multiple exceptions: convert user input to integer and access list index.
[3 marks]
Q23.
Create a custom exception class for invalid age.
[3 marks]
Q24.
Demonstrate try-except-else-finally.
[3 marks]
Q25.
Write a program to safely open and read a file.
[3 marks]
Q26.
Chain exceptions with raise from.
[3 marks]
Q27.
Retry logic: ask user for input up to 3 times.
[3 marks]
Q28.
Validate a dictionary lookup safely.
[3 marks]
Q29.
Exception hierarchy demo.
[3 marks]
Q30.
Log exceptions to a string buffer.
[3 marks]
A1: (b) — except block catches and handles the raised exception.
A2: (c) — ZeroDivisionError is raised when any number is divided by zero.
A3: (c) — finally block always executes regardless of whether an exception occurred.
A4: (b) — raise keyword is used to manually trigger/raise an exception.
A5: (a) — KeyError occurs when you access a dictionary key that does not exist.
A6: (c) — BaseException is the root class; Exception inherits from it.
A7: (b) — "as e" binds the caught exception object to variable e.
A8: (b) — IndexError: sequence index is out of the valid range.
A9: (b) — else block runs only when the try block completes without any exception.
A10: (a) — TypeError: operation applied to wrong type (e.g. "hello"+5).
A11: Cannot divide
A12: Error: invalid literal for int() with base 10: 'abc'
A13: try finally
A14: Out of range
A15: ValueError bad value
A16: 5.0 None
A17: Key 'b' missing
A18: A C D
A19: 5 10 Err
A20: Custom: oops
A21:
def safe_div(a,b):
    try:
        return a/b
    except ZeroDivisionError:
        return "Cannot divide by zero"
    except TypeError:
        return "Invalid types"
print(safe_div(10,2))
print(safe_div(10,0))
A22:
lst=[10,20,30]
try:
    i=int(input("Index: "))
    print(lst[i])
except ValueError:
    print("Enter a valid integer")
except IndexError:
    print(f"Index out of range (0-{len(lst)-1})")
A23:
class InvalidAgeError(Exception):
    def __init__(self,age):
        super().__init__(f"Age {age} is invalid (must be 0-120)")
        self.age=age
def set_age(a):
    if not 0<=a<=120: raise InvalidAgeError(a)
    return a
try:
    print(set_age(int(input("Age: "))))
except InvalidAgeError as e:
    print(e)
A24:
def read_number():
    try:
        n=int(input("Enter number: "))
    except ValueError:
        print("Not a number!")
    else:
        print(f"Square: {n**2}")
    finally:
        print("Attempt complete.")
read_number()
A25:
filename=input("Filename: ")
try:
    with open(filename) as f:
        print(f.read())
except FileNotFoundError:
    print(f"File '{filename}' not found")
except PermissionError:
    print("Permission denied")
A26:
def load_data(filename):
    try:
        with open(filename) as f: return f.read()
    except FileNotFoundError as e:
        raise RuntimeError(f"Could not load {filename}") from e
try:
    load_data("missing.txt")
except RuntimeError as e:
    print(e)
    print("Caused by:", e.__cause__)
A27:
for attempt in range(3):
    try:
        n=int(input(f"Attempt {attempt+1}: Enter number: "))
        print(f"You entered: {n}")
        break
    except ValueError:
        print("Invalid! Try again.")
else:
    print("3 failed attempts. Giving up.")
A28:
data={"name":"Alice","age":16,"city":"Durgapur"}
for key in ["name","age","school","city"]:
    try:
        print(f"{key}: {data[key]}")
    except KeyError:
        print(f"{key}: NOT FOUND")
A29:
exceptions=[ZeroDivisionError,ValueError,TypeError,IndexError,KeyError]
print("Exception hierarchy:")
for exc in exceptions:
    chain=[]
    cls=exc
    while cls:
        chain.append(cls.__name__)
        cls=cls.__bases__[0] if cls.__bases__ else None
    print(" -> ".join(chain))
A30:
import io
log=io.StringIO()
operations=[(10,2),(5,0),(int,"abc"),(["a"],1)]
for op in operations:
    try:
        if len(op)==2 and isinstance(op[0],int):
            result=op[0]/op[1]
            print(f"{op[0]}/{op[1]}={result}")
    except Exception as e:
        msg=f"ERROR: {type(e).__name__}: {e}"
        log.write(msg+"\n")
        print(msg)
print("\nLog:",log.getvalue())
Unit 3 · Societal Impacts
Intellectual Property Rights & Open Source
Copyright, patent, trademark, software licensing, freeware, shareware, open source and Creative Commons.
5
Marks

Types of Intellectual Property

16.1
TypeProtectsDurationExample
CopyrightOriginal creative works (books, music, code)Author's life + 60 years (India)A novel, a song, software code
PatentNew inventions and innovations20 yearsA new algorithm, a hardware device
TrademarkBrand names, logos, symbols10 years (renewable)Apple™, Microsoft™
Trade SecretConfidential business processesAs long as kept secretCoca-Cola formula, Google's algorithm

Software Licensing Categories

16.2
Proprietary Software
Source code NOT available publicly.
Cannot copy, modify, or distribute without permission.

Types:
• Commercial: buy to use (MS Office, Adobe)
• Freeware: free but no source code (Adobe Reader)
• Shareware: free trial, pay for full version (WinRAR)
• Adware: free but shows ads
• Abandonware: no longer supported/sold
Open Source Software
Source code IS publicly available.
Can be studied, modified, and distributed.

Popular licenses:
• GPL (GNU General Public License): derivatives must also be open source
• MIT License: very permissive; just keep the copyright notice
• Apache 2.0: permissive; allows patent use
• BSD: permissive; few restrictions

Examples: Linux, Python, Firefox, VLC, LibreOffice
Creative Commons
Licensing framework for creative works (art, photos, text, music — not software).

CC Licences:
• CC BY: credit the author
• CC BY-SA: credit + share alike
• CC BY-NC: credit + non-commercial
• CC BY-ND: credit + no derivatives
• CC0: public domain (no restrictions)

Used by Wikipedia, Flickr, many YouTube creators
💡 FOSS vs FLOSS:
FOSS = Free and Open Source Software (free as in freedom, not free of cost).
FLOSS = Free/Libre/Open Source Software (Libre emphasises freedom more strongly).
Free software's "Four Freedoms" (defined by GNU/FSF): run, study, redistribute, improve.
📌 Remember for Exam
  • Copyright protects creative works automatically at creation. No registration needed.
  • Freeware ≠ Free software. Freeware = free of cost. Free software = freedom to modify/share.
  • Shareware = try before you buy (WinRAR, WinZip are classic examples).
  • GPL is "copyleft" — if you modify GPL software, your version MUST also be GPL.
  • Open source means source code is available; it does NOT always mean free of cost.
  • Software piracy = using copyrighted software without proper license. It is ILLEGAL.

Topic Test: File Handling

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which mode opens a file for reading?
  • (a) "w"
  • (b) "r"
  • (c) "a"
  • (d) "x"
[1 mark]
Q2.
What does open(file,"a") do?
  • (a) Overwrites file
  • (b) Appends to file
  • (c) Reads file
  • (d) Creates only
[1 mark]
Q3.
Which method reads all lines into a list?
  • (a) read()
  • (b) readline()
  • (c) readlines()
  • (d) readall()
[1 mark]
Q4.
What does seek(0) do?
  • (a) Deletes file
  • (b) Moves to start
  • (c) Moves to end
  • (d) Closes file
[1 mark]
Q5.
Which closes a file automatically?
  • (a) open()
  • (b) close()
  • (c) with open()
  • (d) end()
[1 mark]
Q6.
"w" mode on existing file:
  • (a) Appends to it
  • (b) Raises error
  • (c) Overwrites (truncates) it
  • (d) Opens read-only
[1 mark]
Q7.
tell() method returns:
  • (a) File size
  • (b) Current pointer position
  • (c) Number of lines
  • (d) File name
[1 mark]
Q8.
Which opens file for both read and write?
  • (a) "rw"
  • (b) "r+"
  • (c) "ra"
  • (d) "rx"
[1 mark]
Q9.
What is binary mode?
  • (a) "b" suffix like "rb","wb"
  • (b) Only for images
  • (c) Only for exe files
  • (d) Default mode
[1 mark]
Q10.
File not found error type:
  • (a) IOError
  • (b) OSError
  • (c) FileNotFoundError
  • (d) NotFoundError
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Write code to write "Hello
World" to a file.
[2 marks]
Q12.
What is the output of the following?
How do you read a file line by line?
[2 marks]
Q13.
What is the output of the following?
What is the difference between read() and readlines()?
[2 marks]
Q14.
What is the output of the following?
What does tell() and seek() do?
[2 marks]
Q15.
What is the output of the following?
What happens when you open a file with "x" mode?
[2 marks]
Q16.
What is the output of the following?
Output?
with open("t.txt","w") as f:
    f.write("line1\nline2\nline3")
with open("t.txt") as f:
    print(len(f.readlines()))
[2 marks]
Q17.
What is the output of the following?
Difference between "w" and "a" mode.
[2 marks]
Q18.
What is the output of the following?
What is "rb" mode used for?
[2 marks]
Q19.
What is the output of the following?
How do you copy contents of one file to another?
[2 marks]
Q20.
What is the output of the following?
What does writelines() do?
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write a program to count words, lines, and characters in a file.
[3 marks]
Q22.
Write and read student records to/from a text file.
[3 marks]
Q23.
Append new entries to an existing file.
[3 marks]
Q24.
Search for a keyword in a file and print matching lines.
[3 marks]
Q25.
Copy a text file and show both contents.
[3 marks]
Q26.
Count frequency of each word in a file.
[3 marks]
Q27.
Merge two files into one.
[3 marks]
Q28.
Write a simple CSV without the csv module.
[3 marks]
Q29.
Find the longest line in a file.
[3 marks]
Q30.
Create a simple diary program (append entries).
[3 marks]
A1: (b) — "r" opens a file in read mode (default). FileNotFoundError if not found.
A2: (b) — "a" mode: opens for appending; creates file if it does not exist.
A3: (c) — readlines() returns all lines as a list of strings including newlines.
A4: (b) — seek(0) moves the file pointer to position 0 (beginning of file).
A5: (c) — "with open(...) as f:" automatically closes the file on exit.
A6: (c) — "w" mode truncates (erases) and overwrites an existing file.
A7: (b) — tell() returns the current position of the file pointer in bytes.
A8: (b) — "r+" opens an existing file for both reading and writing.
A9: (a) — Binary mode: "rb","wb","ab" — reads/writes raw bytes, no newline translation.
A10: (c) — FileNotFoundError (subclass of OSError) when file does not exist in read mode.
A11: with open("out.txt","w") as f: f.write("Hello\nWorld")
A12: with open("file.txt") as f: for line in f: print(line.strip())
A13: read(): returns entire file as one string. readlines(): returns list of lines (each ending with \n).
A14: tell(): returns current file pointer position (bytes from start). seek(n): moves file pointer to byte position n.
A15: "x" creates a new file; raises FileExistsError if the file already exists.
A16: 3
A17: "w": truncates file, writes from start (existing content lost). "a": preserves existing content, writes at end.
A18: Reading binary files (images, PDFs, executables) as bytes, no encoding conversion.
A19: with open("src.txt") as src, open("dst.txt","w") as dst: dst.write(src.read())
A20: Writes a list of strings to the file. Does NOT add newlines automatically.
A21:
filename=input("Filename: ")
try:
    with open(filename) as f:
        content=f.read()
    lines=content.splitlines()
    words=content.split()
    print(f"Lines: {len(lines)}")
    print(f"Words: {len(words)}")
    print(f"Chars: {len(content)}")
except FileNotFoundError:
    print("File not found")
A22:
students=[("Alice",90),("Bob",75),("Carol",88)]
with open("students.txt","w") as f:
    for name,marks in students:
        f.write(f"{name},{marks}\n")
print("Records written. Reading back:")
with open("students.txt") as f:
    for line in f:
        name,marks=line.strip().split(",")
        print(f"{name}: {marks}")
A23:
with open("log.txt","a") as f:
    import datetime
    f.write(f"{datetime.datetime.now()}: Program started\n")
with open("log.txt") as f:
    print(f.read())
A24:
keyword=input("Search keyword: ")
try:
    with open("data.txt") as f:
        matches=[l for l in f if keyword.lower() in l.lower()]
    if matches:
        for i,l in enumerate(matches,1): print(f"{i}: {l.strip()}")
    else:
        print("Not found")
except FileNotFoundError:
    print("File not found")
A25:
src="source.txt"
dst="copy.txt"
with open(src,"w") as f: f.write("Hello\nWorld\nPython")
with open(src) as f, open(dst,"w") as g:
    content=f.read()
    g.write(content)
print("Source:",open(src).read())
print("Copy:",open(dst).read())
A26:
with open("essay.txt","w") as f:
    f.write("the cat sat on the mat the cat")
with open("essay.txt") as f:
    words=f.read().split()
freq={}
for w in words: freq[w]=freq.get(w,0)+1
for k,v in sorted(freq.items(),key=lambda x:-x[1]):
    print(f"{k:15}: {v}")
A27:
for name,content in [("a.txt","File A\n"),("b.txt","File B\n")]:
    with open(name,"w") as f: f.write(content)
with open("merged.txt","w") as out:
    for name in ["a.txt","b.txt"]:
        with open(name) as f:
            out.write(f.read())
print(open("merged.txt").read())
A28:
data=[("Name","Age","City"),("Alice",16,"Delhi"),("Bob",17,"Mumbai")]
with open("data.csv","w") as f:
    for row in data:
        f.write(",".join(str(x) for x in row)+"\n")
with open("data.csv") as f:
    for line in f:
        print(line.strip().split(","))
A29:
with open("sample.txt","w") as f:
    f.write("Hello\nThis is a longer line\nShort")
with open("sample.txt") as f:
    lines=f.readlines()
longest=max(lines,key=len)
print(f"Longest line ({len(longest.strip())} chars):",longest.strip())
A30:
import datetime
entry=input("Diary entry: ")
with open("diary.txt","a") as f:
    f.write(f"[{datetime.date.today()}] {entry}\n")
print("Saved. All entries:")
with open("diary.txt") as f:
    print(f.read())
Unit 3 · Societal Impacts
Cybercrime & Cyber Safety
Types of cybercrime, cyber threats, malware types, identity theft, phishing, cyberbullying, and staying safe online.
6
Marks

Types of Cybercrime

17.1
CrimeDescriptionExample
HackingUnauthorised access to systemsBreaking into a server to steal data
PhishingFake emails/websites to steal credentialsFake bank email asking for password
VishingVoice phishing via phone callsFake bank customer care call
SmishingSMS phishingFake prize SMS with malicious link
Identity theftStealing someone's personal informationUsing stolen Aadhaar/PAN for fraud
CyberstalkingOnline harassment of an individualRepeatedly messaging/tracking someone
CyberbullyingBullying using digital technologySpreading rumours on social media
RansomwareEncrypts files, demands ransomWannaCry attack (2017)
DoS/DDoSOverwhelming server to make it unavailableFlooding a website with fake requests
PiracyIllegal copying and distribution of softwareDownloading paid software for free

Malware Types & Cyber Safety

17.2
Types of Malware
Virus: Attaches to files; spreads when file is shared

Worm: Self-replicates across networks without user action

Trojan: Disguised as legitimate software; opens backdoor

Spyware: Secretly monitors activity and steals info

Adware: Displays unwanted ads

Ransomware: Encrypts files, demands payment

Rootkit: Hides malware from antivirus; gives root access

Keylogger: Records keystrokes (captures passwords)
Cyber Safety Measures
✅ Use strong, unique passwords (mix of letters, digits, symbols)
✅ Enable two-factor authentication (2FA)
✅ Keep OS and software updated (patch vulnerabilities)
✅ Install reputable antivirus and keep it updated
✅ Use HTTPS websites (padlock in browser)
✅ Never click unknown links or attachments in email
✅ Back up data regularly (3-2-1 rule)
✅ Use VPN on public Wi-Fi
✅ Check privacy settings on social media
✅ Log out from accounts on shared computers
Password Best Practices
Strong password: min. 12 chars, upper + lower + digits + symbols

Avoid: name, DOB, dictionary words, sequential keys (123456, qwerty)

Passphrase: "My!Cat$Jumps@9" — easy to remember, hard to crack

Never:
• Reuse passwords across sites
• Share passwords with anyone
• Save in browser on shared PC

Use: Password manager (Bitwarden, 1Password) to generate and store complex passwords
📌 Remember for Exam
  • Phishing = email trick; Vishing = voice call trick; Smishing = SMS trick. All steal your data.
  • Virus needs a host file; Worm is self-replicating — spreads without user action.
  • Trojan appears useful but is harmful — like the Trojan Horse story.
  • DoS = one source floods server. DDoS = Distributed DoS (multiple sources — harder to stop).
  • Cyberbullying report channels in India: cybercrime.gov.in or National helpline 1930.
  • Firewall = hardware/software barrier that filters incoming/outgoing network traffic based on rules.

Topic Test: Object Oriented Programming

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which keyword defines a class?
  • (a) object
  • (b) class
  • (c) def
  • (d) struct
[1 mark]
Q2.
__init__ method is called:
  • (a) Manually only
  • (b) When object is created
  • (c) When class is defined
  • (d) When object is deleted
[1 mark]
Q3.
self refers to:
  • (a) The class
  • (b) Current instance
  • (c) Parent class
  • (d) None
[1 mark]
Q4.
Inheritance allows:
  • (a) One class to use methods of another
  • (b) Multiple returns
  • (c) Static typing
  • (d) Automatic documentation
[1 mark]
Q5.
Which is NOT an OOP principle?
  • (a) Encapsulation
  • (b) Polymorphism
  • (c) Compilation
  • (d) Abstraction
[1 mark]
Q6.
Name mangling (__attr) makes attribute:
  • (a) Public
  • (b) Protected
  • (c) Private (name-mangled)
  • (d) Static
[1 mark]
Q7.
super() is used to:
  • (a) Delete parent
  • (b) Call parent class method
  • (c) Create child
  • (d) Override only
[1 mark]
Q8.
Polymorphism means:
  • (a) Many classes
  • (b) One interface multiple implementations
  • (c) Multiple inheritance
  • (d) Many files
[1 mark]
Q9.
@classmethod receives as first argument:
  • (a) self
  • (b) cls
  • (c) None
  • (d) class
[1 mark]
Q10.
Which stores class-level data (shared by all instances)?
  • (a) Instance variable
  • (b) Local variable
  • (c) Class variable
  • (d) Global variable
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Output?
class Dog:
    def __init__(self,name):
        self.name=name
    def speak(self):
        return f"{self.name} says Woof!"
d=Dog("Rex")
print(d.speak())
[2 marks]
Q12.
What is the output of the following?
What prints?
class A:
    x=10
a=A()
b=A()
a.x=20
print(a.x, b.x, A.x)
[2 marks]
Q13.
What is the output of the following?
Find output:
class Animal:
    def sound(self):
        return "..."
class Cat(Animal):
    def sound(self):
        return "Meow"
print(Cat().sound())
[2 marks]
Q14.
What is the output of the following?
Output?
class Counter:
    count=0
    def __init__(self):
        Counter.count+=1
Counter()
Counter()
Counter()
print(Counter.count)
[2 marks]
Q15.
What is the output of the following?
What prints?
class Shape:
    def __init__(self,color="red"):
        self.color=color
    def __str__(self):
        return f"Shape({self.color})"
print(Shape(), Shape("blue"))
[2 marks]
Q16.
What is the output of the following?
Output?
class Num:
    def __init__(self,n): self.n=n
    def __add__(self,other): return Num(self.n+other.n)
    def __str__(self): return str(self.n)
print(Num(3)+Num(4))
[2 marks]
Q17.
What is the output of the following?
Find:
class Base:
    def hello(self): return "Base"
class Child(Base):
    def hello(self): return super().hello()+" Child"
print(Child().hello())
[2 marks]
Q18.
What is the output of the following?
Output?
class A:
    def __init__(self):
        self.__x=10
    def get(self): return self.__x
a=A()
print(a.get())
print(hasattr(a,"__x"), hasattr(a,"_A__x"))
[2 marks]
Q19.
What is the output of the following?
What prints?
for cls in [int,float,str,list]:
    print(cls.__name__, cls.__bases__[0].__name__)
[2 marks]
Q20.
What is the output of the following?
Output?
class Stack:
    def __init__(self): self.data=[]
    def push(self,x): self.data.append(x)
    def pop(self): return self.data.pop()
s=Stack()
for i in [1,2,3]: s.push(i)
print(s.pop(), s.pop())
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Create a BankAccount class with deposit, withdraw, balance.
[3 marks]
Q22.
Create a Shape hierarchy with area/perimeter.
[3 marks]
Q23.
Implement operator overloading for a Vector class.
[3 marks]
Q24.
Student class with classmethod to count students.
[3 marks]
Q25.
Multi-level inheritance: Animal > Mammal > Dog.
[3 marks]
Q26.
Implement a simple linked list using OOP.
[3 marks]
Q27.
Abstract base class for payments.
[3 marks]
Q28.
Property decorator for temperature conversion.
[3 marks]
Q29.
Magic methods: __len__, __contains__, __iter__.
[3 marks]
Q30.
Multiple inheritance with MRO.
[3 marks]
A1: (b) — "class" keyword is used to define a class in Python.
A2: (b) — __init__ is the constructor — called automatically when an object is created.
A3: (b) — self refers to the current instance of the class calling the method.
A4: (a) — Inheritance: a child class inherits attributes and methods from parent.
A5: (c) — Compilation is not an OOP principle. The four are: Encapsulation, Polymorphism, Inheritance, Abstraction.
A6: (c) — __attr is name-mangled to _ClassName__attr, making it harder to access externally.
A7: (b) — super() returns a proxy to the parent class, allowing you to call its methods.
A8: (b) — Polymorphism: same method name behaves differently for different classes.
A9: (b) — @classmethod receives cls (the class itself) as its first argument.
A10: (c) — Class variables are defined at class level and shared by all instances.
A11: Rex says Woof!
A12: 20 10 10
A13: Meow
A14: 3
A15: Shape(red) Shape(blue)
A16: 7
A17: Base Child
A18: 10 False True
A19: int object float object str object list object
A20: 3 2
A21:
class BankAccount:
    def __init__(self,owner,balance=0):
        self.owner=owner
        self.__balance=balance
    def deposit(self,amt):
        if amt>0: self.__balance+=amt
    def withdraw(self,amt):
        if 0<amt<=self.__balance: self.__balance-=amt
        else: print("Insufficient funds")
    def balance(self): return self.__balance
acc=BankAccount("Alice",1000)
acc.deposit(500)
acc.withdraw(200)
print(f"Balance: {acc.balance()}")
A22:
import math
class Shape:
    def area(self): return 0
    def perimeter(self): return 0
class Circle(Shape):
    def __init__(self,r): self.r=r
    def area(self): return math.pi*self.r**2
    def perimeter(self): return 2*math.pi*self.r
class Rectangle(Shape):
    def __init__(self,w,h): self.w=w; self.h=h
    def area(self): return self.w*self.h
    def perimeter(self): return 2*(self.w+self.h)
for s in [Circle(5),Rectangle(4,6)]:
    print(f"{s.__class__.__name__}: Area={s.area():.2f}, Perimeter={s.perimeter():.2f}")
A23:
class Vector:
    def __init__(self,x,y): self.x=x; self.y=y
    def __add__(self,o): return Vector(self.x+o.x,self.y+o.y)
    def __sub__(self,o): return Vector(self.x-o.x,self.y-o.y)
    def __mul__(self,n): return Vector(self.x*n,self.y*n)
    def __str__(self): return f"({self.x},{self.y})"
v1=Vector(1,2)
v2=Vector(3,4)
print(v1+v2, v1-v2, v1*3)
A24:
class Student:
    count=0
    def __init__(self,name,marks):
        self.name=name
        self.marks=marks
        Student.count+=1
    @classmethod
    def total(cls): return cls.count
    @staticmethod
    def grade(m): return "A" if m>=80 else "B" if m>=60 else "C"
students=[Student("Alice",90),Student("Bob",72),Student("Carol",55)]
for s in students:
    print(f"{s.name}: {Student.grade(s.marks)}")
print("Total students:",Student.total())
A25:
class Animal:
    def __init__(self,name): self.name=name
    def eat(self): return f"{self.name} eats"
class Mammal(Animal):
    def breathe(self): return f"{self.name} breathes air"
class Dog(Mammal):
    def speak(self): return f"{self.name} barks"
d=Dog("Rex")
print(d.eat())
print(d.breathe())
print(d.speak())
A26:
class Node:
    def __init__(self,data): self.data=data; self.next=None
class LinkedList:
    def __init__(self): self.head=None
    def append(self,data):
        node=Node(data)
        if not self.head: self.head=node; return
        cur=self.head
        while cur.next: cur=cur.next
        cur.next=node
    def display(self):
        cur=self.head
        while cur: print(cur.data,end="->"); cur=cur.next
        print("None")
ll=LinkedList()
for x in [1,2,3,4,5]: ll.append(x)
ll.display()
A27:
from abc import ABC, abstractmethod
class Payment(ABC):
    @abstractmethod
    def pay(self,amount): pass
class CashPayment(Payment):
    def pay(self,amount): print(f"Paid ₹{amount} in cash")
class UPIPayment(Payment):
    def pay(self,amount): print(f"Paid ₹{amount} via UPI")
for method in [CashPayment(),UPIPayment()]:
    method.pay(500)
A28:
class Temperature:
    def __init__(self,celsius=0): self._c=celsius
    @property
    def celsius(self): return self._c
    @celsius.setter
    def celsius(self,val):
        if val<-273.15: raise ValueError("Below absolute zero")
        self._c=val
    @property
    def fahrenheit(self): return self._c*9/5+32
    @property
    def kelvin(self): return self._c+273.15
t=Temperature(100)
print(f"{t.celsius}°C = {t.fahrenheit}°F = {t.kelvin}K")
A29:
class NumberBag:
    def __init__(self,*nums): self.nums=list(nums)
    def __len__(self): return len(self.nums)
    def __contains__(self,item): return item in self.nums
    def __iter__(self): return iter(self.nums)
bag=NumberBag(1,2,3,4,5)
print(len(bag))
print(3 in bag, 9 in bag)
print([x**2 for x in bag])
A30:
class A:
    def hello(self): return "Hello from A"
class B(A):
    def hello(self): return "Hello from B"
class C(A):
    def hello(self): return "Hello from C"
class D(B,C):
    pass
d=D()
print(d.hello())  # B (MRO: D->B->C->A)
print(D.__mro__)
Unit 3 · Societal Impacts
IT Act & E-Waste Management
Indian IT Act 2000 (amended 2008), key sections, cybercrimes and penalties, e-waste rules and responsible disposal.
5
Marks

Information Technology Act, 2000

18.1
💡 IT Act 2000 was India's first law to deal with cybercrime and e-commerce. It was significantly amended in 2008 to cover new offences. The Act gives legal recognition to electronic records and digital signatures.
SectionOffencePunishment
Sec 43Unauthorised access to computer/network; downloading data; introducing virusCivil penalty — compensation up to ₹1 crore
Sec 65Tampering with computer source code (altering/destroying)Imprisonment up to 3 years OR fine up to ₹2 lakh OR both
Sec 66Computer-related offences (hacking, stealing data)Imprisonment up to 3 years AND/OR fine up to ₹5 lakh
Sec 66ASending offensive/false messages online (struck down by SC in 2015)— (no longer in force)
Sec 66BReceiving stolen computer resourceImprisonment up to 3 years AND/OR fine ₹1 lakh
Sec 66CIdentity theft (using others' password, digital signature)Imprisonment up to 3 years AND fine up to ₹1 lakh
Sec 66DCheating by impersonating using computer resourceImprisonment up to 3 years AND fine up to ₹1 lakh
Sec 66EViolation of privacy (publishing private images)Imprisonment up to 3 years OR fine up to ₹2 lakh OR both
Sec 66FCyber terrorism (targeting critical infrastructure)Life imprisonment
Sec 67Publishing obscene material electronicallyImprisonment up to 5 years AND fine up to ₹10 lakh
Sec 72Breach of confidentiality and privacyImprisonment up to 2 years OR fine up to ₹1 lakh OR both
Sec 79Intermediary not liable if follows due diligence (safe harbour)Protection for ISPs/platforms

E-Waste Management

18.2
E-Waste Rules 2016
India's E-Waste (Management) Rules, 2016 (amended 2018) govern e-waste.

Extended Producer Responsibility (EPR): Manufacturers must collect back and recycle their own products at end of life.

What consumers must do:
• Deposit e-waste at collection centres
• Don't mix e-waste with household garbage
• Return old devices to authorised recyclers
• Use manufacturer take-back schemes
Reduce, Reuse, Recycle
Reduce: Buy only what you need; choose long-lasting devices

Reuse: Donate working devices; refurbish for new use

Recycle: Send to authorised e-waste recycler

Toxic materials in e-waste:
• Lead → nerve damage
• Mercury → kidney/brain damage
• Cadmium → lung disease
• Chromium → skin problems
• Beryllium → lung cancer
• Arsenic → cancer risk
Digital Footprint
Digital Footprint = trail of data you leave when using the internet.

Active footprint: Data you deliberately share (social media posts, emails)

Passive footprint: Data collected without your knowledge (browsing history, location, cookies)

Why it matters:
• Employers search your digital footprint
• Hackers can exploit it
• Advertisers use it for targeting

Minimise: Use private browsing; review app permissions; delete unused accounts
📌 Remember for Exam
  • IT Act 2000 was amended in 2008. Sec 66 (hacking), Sec 66C (identity theft), Sec 66F (cyber terrorism).
  • Sec 66F (cyber terrorism) carries the HIGHEST penalty — life imprisonment.
  • Sec 66A was struck down by Supreme Court in 2015 (Shreya Singhal case) as unconstitutional.
  • E-Waste Rules 2016: Extended Producer Responsibility — manufacturers must take back old products.
  • Digital footprint = active (you post) + passive (tracked without your knowledge).
  • Never dispose of batteries or electronics in regular trash — toxic materials contaminate soil and water.

Topic Test: Data Structures (Stack & Queue)

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Stack follows which principle?
  • (a) FIFO
  • (b) LIFO
  • (c) LILO
  • (d) FILO
[1 mark]
Q2.
Queue follows which principle?
  • (a) LIFO
  • (b) FIFO
  • (c) FILO
  • (d) LILO
[1 mark]
Q3.
Which operation adds element to stack?
  • (a) enqueue
  • (b) push
  • (c) insert
  • (d) add
[1 mark]
Q4.
Which removes from queue?
  • (a) pop
  • (b) dequeue
  • (c) remove
  • (d) delete
[1 mark]
Q5.
Stack overflow occurs when:
  • (a) Pop from empty
  • (b) Push to full
  • (c) Access middle
  • (d) Dequeue from empty
[1 mark]
Q6.
Which Python structure is used to implement stack?
  • (a) tuple
  • (b) dict
  • (c) list
  • (d) set
[1 mark]
Q7.
Infix a+b*c in postfix is:
  • (a) ab+c*
  • (b) abc*+
  • (c) ab*c+
  • (d) abc+*
[1 mark]
Q8.
Which data structure uses FIFO?
  • (a) Stack
  • (b) Queue
  • (c) Tree
  • (d) Graph
[1 mark]
Q9.
Peek in a stack:
  • (a) Removes top
  • (b) Shows top without removing
  • (c) Inserts at top
  • (d) Clears stack
[1 mark]
Q10.
collections.deque is used for:
  • (a) Only queues
  • (b) Only stacks
  • (c) Both stack and queue (efficient)
  • (d) Sorting
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Trace: push 1,2,3 then pop twice from stack.
[2 marks]
Q12.
What is the output of the following?
Enqueue 5,10,15 then dequeue twice. What remains?
[2 marks]
Q13.
What is the output of the following?
Convert infix A+B*C to postfix.
[2 marks]
Q14.
What is the output of the following?
Output?
stack=[]
for x in [1,2,3,4]: stack.append(x)
while stack: print(stack.pop(),end=" ")
[2 marks]
Q15.
What is the output of the following?
Output?
from collections import deque
q=deque()
for x in [10,20,30]: q.append(x)
print(q.popleft(), q.popleft())
[2 marks]
Q16.
What is the output of the following?
Evaluate postfix: 5 3 2 * +
[2 marks]
Q17.
What is the output of the following?
Output?
stack=[]
for c in "({[": stack.append(c)
print(len(stack), stack[-1])
[2 marks]
Q18.
What is the output of the following?
What is the use of stack in function calls?
[2 marks]
Q19.
What is the output of the following?
Output?
from collections import deque
dq=deque([1,2,3])
dq.appendleft(0)
dq.append(4)
print(list(dq))
[2 marks]
Q20.
What is the output of the following?
Trace balanced parentheses check on "({[]})".
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Implement a stack using a list.
[3 marks]
Q22.
Implement a queue using a list.
[3 marks]
Q23.
Check balanced parentheses using a stack.
[3 marks]
Q24.
Convert infix to postfix using a stack.
[3 marks]
Q25.
Evaluate postfix expression.
[3 marks]
Q26.
Reverse a string using a stack.
[3 marks]
Q27.
Implement queue using two stacks.
[3 marks]
Q28.
Simulate undo functionality using a stack.
[3 marks]
Q29.
Implement priority queue using sorted list.
[3 marks]
Q30.
Implement circular queue.
[3 marks]
A1: (b) — Stack: Last In First Out — last element pushed is first popped.
A2: (b) — Queue: First In First Out — first element enqueued is first dequeued.
A3: (b) — push() adds element to top of stack.
A4: (b) — dequeue() removes element from front of queue.
A5: (b) — Stack overflow: attempting to push to a full/bounded stack.
A6: (c) — Python list: append() = push, pop() = pop (from end).
A7: (b) — Operator precedence: b*c first, then +a → abc*+
A8: (b) — Queue uses FIFO — first in, first out.
A9: (b) — peek/top returns the top element without removing it.
A10: (c) — deque (double-ended queue) supports O(1) append/pop from both ends.
A11: After push 1,2,3: stack=[1,2,3] Pop → 3; stack=[1,2] Pop → 2; stack=[1]
A12: Queue: 5,10,15 Dequeue → 5; Dequeue → 10 Remaining: [15]
A13: A B C * + (* has higher precedence than +)
A14: 4 3 2 1
A15: 10 20
A16: 3*2=6; 5+6=11
A17: 3 [
A18: Call stack tracks function calls. When f() calls g(), g is pushed. When g() returns, it is popped and control returns to f().
A19: [0, 1, 2, 3, 4]
A20: Push ( { [ ; see ] pop [ match; see } pop { match; see ) pop ( match; stack empty → Balanced
A21:
class Stack:
    def __init__(self): self.data=[]
    def push(self,x): self.data.append(x)
    def pop(self):
        if self.is_empty(): raise IndexError("Stack underflow")
        return self.data.pop()
    def peek(self): return self.data[-1] if self.data else None
    def is_empty(self): return len(self.data)==0
    def __str__(self): return str(self.data)
s=Stack()
for x in [1,2,3,4,5]: s.push(x)
print(s)
print("Pop:",s.pop())
print("Peek:",s.peek())
A22:
class Queue:
    def __init__(self): self.data=[]
    def enqueue(self,x): self.data.append(x)
    def dequeue(self):
        if self.is_empty(): raise IndexError("Queue underflow")
        return self.data.pop(0)
    def front(self): return self.data[0] if self.data else None
    def is_empty(self): return len(self.data)==0
    def __str__(self): return str(self.data)
q=Queue()
for x in [10,20,30,40]: q.enqueue(x)
print(q)
print("Dequeue:",q.dequeue())
print("Front:",q.front())
A23:
def balanced(expr):
    stack=[]
    pairs={")":" (","}":" {","]":" ["}
    for ch in expr:
        if ch in "({[": stack.append(ch)
        elif ch in ")}]":
            if not stack or stack[-1]!=pairs[ch]: return False
            stack.pop()
    return not stack
for expr in ["({[]})", "({)}", "((()", ""]:
    print(f"{expr!r:12}: {'Balanced' if balanced(expr) else 'Not balanced'}")
A24:
def infix_to_postfix(expr):
    prec={"+"  :1,"-":1,"*":2,"/":2,"**":3}
    stack=[]
    result=[]
    for token in expr.split():
        if token.isalnum(): result.append(token)
        elif token=="(": stack.append(token)
        elif token==")":
            while stack and stack[-1]!="(": result.append(stack.pop())
            stack.pop()
        else:
            while stack and stack[-1]!="(" and prec.get(stack[-1],0)>=prec.get(token,0):
                result.append(stack.pop())
            stack.append(token)
    while stack: result.append(stack.pop())
    return " ".join(result)
print(infix_to_postfix("A + B * C"))
print(infix_to_postfix("( A + B ) * C"))
A25:
def eval_postfix(expr):
    stack=[]
    for token in expr.split():
        if token.lstrip("-").isdigit(): stack.append(int(token))
        else:
            b,a=stack.pop(),stack.pop()
            if token=="+": stack.append(a+b)
            elif token=="-": stack.append(a-b)
            elif token=="*": stack.append(a*b)
            elif token=="/": stack.append(a/b)
    return stack[0]
print(eval_postfix("5 3 2 * +"))   # 11
print(eval_postfix("3 4 + 2 * 7 /"))  # 2.0
A26:
def reverse_str(s):
    stack=list(s)
    result=""
    while stack: result+=stack.pop()
    return result
print(reverse_str("Hello Python"))
print(reverse_str("CBSEMOCK"))
A27:
class QueueUsingStacks:
    def __init__(self): self.in_s=[]; self.out_s=[]
    def enqueue(self,x): self.in_s.append(x)
    def dequeue(self):
        if not self.out_s:
            while self.in_s: self.out_s.append(self.in_s.pop())
        if not self.out_s: raise IndexError("Empty")
        return self.out_s.pop()
q=QueueUsingStacks()
for x in [1,2,3,4]: q.enqueue(x)
print(q.dequeue(), q.dequeue())
A28:
history=[]
text=""
def type_char(c):
    global text
    history.append(text)
    text+=c
def undo():
    global text
    if history: text=history.pop()
for c in "Hello": type_char(c)
print("Typed:",text)
undo(); undo()
print("After 2 undos:",text)
A29:
class PriorityQueue:
    def __init__(self): self.data=[]
    def push(self,item,priority):
        self.data.append((priority,item))
        self.data.sort(key=lambda x:-x[0])
    def pop(self):
        return self.data.pop(0)[1] if self.data else None
pq=PriorityQueue()
pq.push("Low task",1)
pq.push("High task",5)
pq.push("Medium task",3)
while pq.data:
    print("Process:",pq.pop())
A30:
class CircularQueue:
    def __init__(self,size):
        self.size=size
        self.q=[None]*size
        self.front=self.rear=-1
    def enqueue(self,x):
        if (self.rear+1)%self.size==self.front: print("Full"); return
        elif self.front==-1: self.front=self.rear=0
        else: self.rear=(self.rear+1)%self.size
        self.q[self.rear]=x
    def dequeue(self):
        if self.front==-1: print("Empty"); return None
        val=self.q[self.front]
        if self.front==self.rear: self.front=self.rear=-1
        else: self.front=(self.front+1)%self.size
        return val
cq=CircularQueue(4)
for x in [10,20,30]: cq.enqueue(x)
print(cq.dequeue(), cq.dequeue())
cq.enqueue(40)
cq.enqueue(50)
print(cq.q)
Unit 1 · Computational Thinking & Programming
Functions (Advanced)
Scope, global/local variables, default & keyword arguments, *args, **kwargs, lambda, map, filter, recursion.
12
Marks

Scope & Arguments

1.1
Variable Scope
Local: Defined inside a function; only accessible inside it.

Global: Defined outside all functions; accessible everywhere.

global x — declares x as global inside a function (modifies outer x).

nonlocal x — refers to variable in enclosing (outer) function.

LEGB Rule:
Python searches: Local → Enclosing → Global → Built-in
Argument Types
Positional: def f(a, b) → f(1, 2)

Default: def f(a, b=10) → f(5) works

Keyword: f(b=20, a=5) → any order

*args: Variable positional args → tuple
def f(*args): print(args)
f(1,2,3) → (1,2,3)

**kwargs: Variable keyword args → dict
def f(**kwargs): print(kwargs)
f(x=1,y=2) → {'x':1,'y':2}
Lambda & Functional
Lambda: anonymous one-line function
square = lambda x: x**2
add = lambda x,y: x+y

map(func, iter): apply func to each element
list(map(lambda x:x*2, [1,2,3]))
→ [2, 4, 6]

filter(func, iter): keep elements where func is True
list(filter(lambda x:x%2==0, range(10)))
→ [0, 2, 4, 6, 8]

sorted(iter, key=lambda) for custom sorting
💡 Recursion — Base case is MANDATORY:
A recursive function calls itself. MUST have: (1) a base case that stops recursion, and (2) a recursive case that moves toward the base case.
Without a base case → infinite recursion → RecursionError: maximum recursion depth exceeded.

🐍 Python Runner — Functions Programs

1.2
P1: Scope & global
P2: Default Arguments
P3: *args
P4: **kwargs
P5: Lambda
P6: map()
P7: filter()
P8: Factorial Recursion
P9: Fibonacci Recursion
P10: Combined Concepts
P1: Memoization
P2: Decorators
P3: Generators
P4: Tower of Hanoi
P5: Closures
P6: Binary Search (Recursive)
P7: Functional Pipeline
P8: Sorting (Recursive)
P9: Recursive Structures
P10: Recursive Math
P1: Mutual Recursion
P2: Trampoline
P3: Currying
P4: N-Queens Backtracking
P5: Function Composition
P6: Recursive Parser
P7: Advanced Memoize
P8: Sudoku Solver
P9: Y-Combinator
P10: Stack Machine
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • LEGB rule: Python looks for variable in Local → Enclosing → Global → Built-in order.
  • global x inside function makes x refer to the global variable. Without it, x is always local.
  • *args collects extra positional args as a tuple. **kwargs collects extra keyword args as a dict.
  • Lambda is a single-expression anonymous function. Cannot contain statements (if/for/while blocks).
  • Every recursion needs a base case. Without it → RecursionError (stack overflow).
  • map() transforms; filter() selects; reduce() (from functools) aggregates.

Topic Test: Python Functions & Modules

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which statement imports only one function from a module?
  • (a) import math
  • (b) from math import sqrt
  • (c) import math.sqrt
  • (d) load math.sqrt
[1 mark]
Q2.
What does dir(math) show?
  • (a) Math help
  • (b) All attributes/functions in math
  • (c) Math source code
  • (d) Math version
[1 mark]
Q3.
Which is NOT a built-in module?
  • (a) math
  • (b) os
  • (c) numpy
  • (d) sys
[1 mark]
Q4.
math.floor(3.9) returns:
  • (a) 3
  • (b) 4
  • (c) 3.9
  • (d) Error
[1 mark]
Q5.
random.randint(1,6) generates:
  • (a) 1 to 5
  • (b) 1 to 6
  • (c) 0 to 6
  • (d) 0 to 5
[1 mark]
Q6.
__name__ == "__main__" is True when:
  • (a) Module is imported
  • (b) Script runs directly
  • (c) Any time
  • (d) Never
[1 mark]
Q7.
What does os.getcwd() return?
  • (a) Current file name
  • (b) Current working directory path
  • (c) OS version
  • (d) Home directory
[1 mark]
Q8.
Which module handles dates and times?
  • (a) time
  • (b) date
  • (c) datetime
  • (d) calendar
[1 mark]
Q9.
pip is used for:
  • (a) Running Python
  • (b) Installing packages
  • (c) Debugging
  • (d) Compiling
[1 mark]
Q10.
What is a package in Python?
  • (a) Single .py file
  • (b) Directory with __init__.py
  • (c) Function collection
  • (d) Module alias
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Output?
import math
print(math.sqrt(144), math.ceil(4.1), math.floor(4.9))
[2 marks]
Q12.
What is the output of the following?
What prints?
import random
random.seed(42)
print(random.randint(1,10))
[2 marks]
Q13.
What is the output of the following?
Find:
import os
print(type(os.getcwd()))
[2 marks]
Q14.
What is the output of the following?
Output?
from datetime import date
today=date.today()
print(type(today).__name__)
[2 marks]
Q15.
What is the output of the following?
What prints?
print(abs(-5), round(3.567,2), pow(2,10))
[2 marks]
Q16.
What is the output of the following?
Find the output:
s="Hello World"
print(s.upper(), len(s), s.count("l"))
[2 marks]
Q17.
What is the output of the following?
Output?
import math
print(math.pi, math.e)
[2 marks]
Q18.
What is the output of the following?
What prints?
print(list(range(0,20,5)))
[2 marks]
Q19.
What is the output of the following?
Find:
print(divmod(17,5))
[2 marks]
Q20.
What is the output of the following?
Output?
import sys
print(sys.version[:6])
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Create a module with math utilities and import it.
[3 marks]
Q22.
Use datetime to show current date/time and calculate age.
[3 marks]
Q23.
Use random to simulate dice rolls and find frequency.
[3 marks]
Q24.
Use os module to list files and check paths.
[3 marks]
Q25.
Build a statistics calculator using math module.
[3 marks]
Q26.
Create a password generator using random.
[3 marks]
Q27.
Use sys.argv to process command line arguments (simulate).
[3 marks]
Q28.
Use itertools for combinations and permutations.
[3 marks]
Q29.
Use collections.Counter for word frequency.
[3 marks]
Q30.
Create a simple timer using time module.
[3 marks]
A1: (b) — "from module import name" imports only the specified name.
A2: (b) — dir() returns a list of names in the module/object namespace.
A3: (c) — numpy is a third-party package (pip install); math, os, sys are built-in.
A4: (a) — math.floor() rounds DOWN to nearest integer → 3
A5: (b) — randint(a,b) returns random integer from a to b INCLUSIVE.
A6: (b) — When Python runs a script directly, __name__ is set to "__main__".
A7: (b) — os.getcwd() returns the current working directory as a string.
A8: (c) — datetime module: datetime, date, time, timedelta classes.
A9: (b) — pip (Package Installer for Python) downloads and installs packages.
A10: (b) — Package: a directory containing __init__.py and module files.
A11: 12.0 5 4
A12: 1 (seed 42 gives deterministic output; actual value is 1)
A13: <class 'str'>
A14: date
A15: 5 3.57 1024
A16: HELLO WORLD 11 3
A17: 3.141592653589793 2.718281828459045
A18: [0, 5, 10, 15]
A19: (3, 2)
A20: Shows first 6 chars of Python version string, e.g. "3.11.0"
A21:
# mymath.py (imagine this exists)
def circle_area(r):
    import math
    return math.pi*r**2
def factorial(n):
    return 1 if n<=1 else n*factorial(n-1)
def is_prime(n):
    if n<2: return False
    return all(n%i!=0 for i in range(2,int(n**0.5)+1))
# Main usage
print(f"Area: {circle_area(5):.2f}")
print(f"10! = {factorial(10)}")
print(f"17 prime: {is_prime(17)}")
A22:
from datetime import date
today=date.today()
birth=date(2008,6,15)
age=(today-birth).days//365
print(f"Today: {today}")
print(f"Age: {age} years")
print(f"Days alive: {(today-birth).days}")
A23:
import random
rolls=[random.randint(1,6) for _ in range(100)]
freq={i:rolls.count(i) for i in range(1,7)}
for face,count in freq.items():
    print(f"Face {face}: {"#"*count:20} ({count})")
A24:
import os
print("CWD:",os.getcwd())
print("Files:")
for f in os.listdir(".")[:5]:
    path=os.path.join(".",f)
    print(f"  {f} ({os.path.getsize(path)} bytes)")
A25:
import math
def stats(data):
    n=len(data)
    mean=sum(data)/n
    variance=sum((x-mean)**2 for x in data)/n
    return mean, math.sqrt(variance), min(data), max(data)
data=[15,20,35,40,50]
m,sd,mn,mx=stats(data)
print(f"Mean:{m} SD:{sd:.2f} Min:{mn} Max:{mx}")
A26:
import random, string
def gen_password(length=12):
    chars=string.ascii_letters+string.digits+"!@#$%"
    pwd=[
        random.choice(string.ascii_uppercase),
        random.choice(string.digits),
        random.choice("!@#$%"),
    ]
    pwd+=[random.choice(chars) for _ in range(length-3)]
    random.shuffle(pwd)
    return "".join(pwd)
for _ in range(3):
    print(gen_password())
A27:
import sys
# Simulate: normally sys.argv = ["script.py","Alice","90"]
args=["student_report.py","Alice","90","Math"]
if len(args)>=4:
    name,marks,subject=args[1],int(args[2]),args[3]
    grade="A" if marks>=80 else "B" if marks>=60 else "C"
    print(f"Student: {name}\nSubject: {subject}\nMarks: {marks}\nGrade: {grade}")
else:
    print("Usage: script.py name marks subject")
A28:
from itertools import combinations, permutations
items=["A","B","C","D"]
print("Combinations of 2:")
for c in combinations(items,2):
    print(c,end=" ")
print("\nPermutations of 2:")
for p in permutations(items,2):
    print(p,end=" ")
A29:
from collections import Counter
text="the cat sat on the mat the cat"
word_count=Counter(text.split())
print("Most common words:")
for word,count in word_count.most_common(5):
    print(f"  {word}: {count}")
A30:
import time
def timer(fn,*args):
    start=time.time()
    result=fn(*args)
    elapsed=time.time()-start
    print(f"{fn.__name__} took {elapsed*1000:.3f} ms")
    return result
def bubble_sort(lst):
    lst=lst[:]
    for i in range(len(lst)-1):
        for j in range(len(lst)-i-1):
            if lst[j]>lst[j+1]: lst[j],lst[j+1]=lst[j+1],lst[j]
    return lst
import random
data=[random.randint(1,1000) for _ in range(500)]
timer(bubble_sort,data)
Unit 1 · Computational Thinking & Programming
Exception Handling
try-except-else-finally, common exceptions, raising exceptions, custom exception classes.
8
Marks

Exception Handling Syntax

2.1
try-except Block
try:
    # code that might raise exception
except ExceptionType:
    # handle that exception
except (TypeError, ValueError):
    # handle multiple types
except Exception as e:
    # catch any + get message
else:
    # runs if NO exception occurred
finally:
    # ALWAYS runs (cleanup)
Common Exceptions
ValueError — wrong value type (int('abc'))
TypeError — wrong type operation ('a'+1)
ZeroDivisionError — divide by zero
IndexError — list index out of range
KeyError — dict key not found
FileNotFoundError — file missing
NameError — variable not defined
AttributeError — attribute doesn't exist
ImportError — module not found
RecursionError — max depth exceeded
StopIteration — iterator exhausted
OverflowError — number too large
raise & Custom Exceptions
Raise explicitly:
raise ValueError("must be positive")

Re-raise:
except Exception:
    raise # re-raises same exception

Custom exception class:
class AgeError(Exception):
    def __init__(self, age):
        self.age = age
        super().__init__(f"Invalid: {age}")

raise AgeError(-5)

🐍 Python Runner — Exception Programs

2.2
P1: Basic Exceptions
P2: try-except-else-finally
P3: Multiple Exceptions
P4: Exception Hierarchy
P5: raise Statement
P6: Safe Input Parsing
P7: Custom Exceptions
P8: Nested try-except
P9: assert Statement
P10: Traceback Info
P1: Context Manager
P2: Exception Chaining
P3: Retry Decorator
P4: Exception Hierarchy
P5: Validation Framework
P6: Stack with Exceptions
P7: Safe Calculator
P8: Batch Error Handling
P9: Generator Exceptions
P10: Error Logging
P1: State Machine
P2: Circuit Breaker
P3: Structured Errors
P4: Event System
P5: Parser Errors
P6: Transactions
P7: Interpreter Errors
P8: Saga Pattern
P9: Exception Group
P10: Error Pipeline
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • else in try-except runs ONLY if no exception occurred. finally ALWAYS runs.
  • Order: most specific exception before more general. Put Exception last.
  • except (A, B): handles both types. except A as e: captures exception object.
  • raise (alone inside except) re-raises the current exception.
  • Custom exceptions inherit from Exception. Define __init__ with your own attributes.
  • assert raises AssertionError if condition is False. Used for debugging/testing.

Topic Test: Exception Handling (Class 12)

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which exception handles all exceptions?
  • (a) BaseException
  • (b) Exception
  • (c) Error
  • (d) AnyError
[1 mark]
Q2.
Assertion error is raised by:
  • (a) assert statement when False
  • (b) raise statement
  • (c) try block
  • (d) import statement
[1 mark]
Q3.
What is exception chaining?
  • (a) Multiple except blocks
  • (b) raise e from original_e
  • (c) try-except-try
  • (d) Nested try
[1 mark]
Q4.
Which is raised by sys.exit()?
  • (a) ExitError
  • (b) SystemExit
  • (c) RuntimeError
  • (d) KeyboardInterrupt
[1 mark]
Q5.
Which logs warnings without stopping execution?
  • (a) print()
  • (b) raise
  • (c) warnings.warn()
  • (d) except
[1 mark]
Q6.
StopIteration is raised when:
  • (a) List is empty
  • (b) Iterator is exhausted
  • (c) Loop breaks
  • (d) Generator returns
[1 mark]
Q7.
MemoryError is raised when:
  • (a) Too many imports
  • (b) RAM is full / allocation fails
  • (c) Disk is full
  • (d) CPU overload
[1 mark]
Q8.
RecursionError is raised when:
  • (a) Function returns twice
  • (b) Maximum recursion depth exceeded
  • (c) Recursive import
  • (d) None
[1 mark]
Q9.
What is a context manager?
  • (a) try-except block
  • (b) Object with __enter__/__exit__ (used in with)
  • (c) Module for errors
  • (d) Debugger
[1 mark]
Q10.
Which catches keyboard interrupt (Ctrl+C)?
  • (a) KeyboardInterrupt
  • (b) CtrlCError
  • (c) InterruptException
  • (d) SystemInterrupt
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Output?
try:
    assert 5>10, "5 is not > 10"
except AssertionError as e:
    print("Assertion failed:",e)
[2 marks]
Q12.
What is the output of the following?
What prints?
def gen():
    yield 1; yield 2
g=gen()
print(next(g))
print(next(g))
try: print(next(g))
except StopIteration: print("Done")
[2 marks]
Q13.
What is the output of the following?
Find:
class AppError(Exception):
    def __init__(self,msg,code):
        super().__init__(msg)
        self.code=code
try:
    raise AppError("Not found",404)
except AppError as e:
    print(e, e.code)
[2 marks]
Q14.
What is the output of the following?
Output?
import warnings
warnings.warn("Deprecated!")
print("After warning")
[2 marks]
Q15.
What is the output of the following?
What prints?
try:
    x=[][0]
except (IndexError, KeyError) as e:
    print(type(e).__name__,"caught")
[2 marks]
Q16.
What is the output of the following?
Find output:
def risky():
    raise ValueError("bad")
try:
    try:
        risky()
    except ValueError:
        print("Inner caught")
        raise
except ValueError:
    print("Outer caught")
[2 marks]
Q17.
What is the output of the following?
Output?
class CM:
    def __enter__(self): print("Enter"); return self
    def __exit__(self,*args): print("Exit"); return False
with CM() as c:
    print("Inside")
[2 marks]
Q18.
What is the output of the following?
What is __exit__ return value meaning?
[2 marks]
Q19.
What is the output of the following?
Output?
def f(n):
    if n==0: return
    f(n-1)
try: f(1000)
except RecursionError: print("Recursion limit hit")
else: print("OK")
[2 marks]
Q20.
What is the output of the following?
Find:
try:
    open("nonexistent.xyz")
except OSError as e:
    print(e.errno, type(e).__name__)
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Create a hierarchy of custom exceptions.
[3 marks]
Q22.
Implement a context manager for timing code.
[3 marks]
Q23.
Exception logging with traceback.
[3 marks]
Q24.
Retry decorator with exception handling.
[3 marks]
Q25.
Safe file operation with context manager.
[3 marks]
Q26.
Validate form data with custom exceptions.
[3 marks]
Q27.
Demonstrate exception suppression using contextlib.
[3 marks]
Q28.
Write a program that catches and re-raises with context.
[3 marks]
Q29.
Exception hierarchy exploration.
[3 marks]
Q30.
Build a calculator with complete exception handling.
[3 marks]
A1: (b) — except Exception catches all standard exceptions.
A2: (a) — assert x>0 raises AssertionError if x<=0.
A3: (b) — "raise NewException from original" chains exceptions showing cause.
A4: (b) — sys.exit() raises SystemExit; it inherits BaseException, not Exception.
A5: (c) — warnings.warn() emits a warning but does not stop execution.
A6: (c) — StopIteration signals that an iterator or generator has no more items.
A7: (b) — MemoryError: Python cannot allocate memory for an object.
A8: (b) — RecursionError (formerly RuntimeError) when call stack overflows.
A9: (b) — Context manager: defines setup/teardown; used with "with" statement.
A10: (a) — KeyboardInterrupt is raised when user presses Ctrl+C; inherits BaseException.
A11: Assertion failed: 5 is not > 10
A12: 1 2 Done
A13: Not found 404
A14: (warning printed to stderr) After warning
A15: IndexError caught
A16: Inner caught Outer caught
A17: Enter Inside Exit
A18: True: suppress exception (don't re-raise). False/None: allow exception to propagate.
A19: OK (default limit ~1000; 1000 levels fits)
A20: 2 FileNotFoundError
A21:
class AppError(Exception): pass
class NetworkError(AppError): pass
class TimeoutError(NetworkError): pass
class AuthError(AppError): pass
def connect(host,authenticated=True):
    if not authenticated: raise AuthError("Not authenticated")
    if host=="slow": raise TimeoutError("Connection timed out")
    return f"Connected to {host}"
for host,auth in [("google.com",True),("slow",True),("fb.com",False)]:
    try:
        print(connect(host,auth))
    except TimeoutError as e:
        print(f"Timeout: {e}")
    except AuthError as e:
        print(f"Auth: {e}")
A22:
import time
class Timer:
    def __enter__(self):
        self.start=time.time()
        return self
    def __exit__(self,*args):
        self.elapsed=time.time()-self.start
        print(f"Time: {self.elapsed*1000:.2f} ms")
        return False
with Timer():
    total=sum(range(1000000))
    print(f"Sum: {total}")
A23:
import traceback, io
def divide(a,b):
    return a/b
log_buffer=io.StringIO()
for pair in [(10,2),(5,0),(8,4)]:
    try:
        print(f"{pair[0]}/{pair[1]}={divide(*pair)}")
    except ZeroDivisionError:
        traceback.print_exc(file=log_buffer)
print("\nError log:")
print(log_buffer.getvalue())
A24:
import time
def retry(times=3, delay=0.1):
    def decorator(fn):
        def wrapper(*args,**kwargs):
            for attempt in range(times):
                try:
                    return fn(*args,**kwargs)
                except Exception as e:
                    print(f"Attempt {attempt+1} failed: {e}")
                    if attempt<times-1: time.sleep(delay)
            raise RuntimeError(f"Failed after {times} attempts")
        return wrapper
    return decorator
import random
@retry(times=3)
def unstable():
    if random.random()<0.7: raise ConnectionError("Network error")
    return "Success!"
try:
    print(unstable())
except RuntimeError as e:
    print(e)
A25:
class SafeFile:
    def __init__(self,filename,mode="r"):
        self.filename=filename
        self.mode=mode
        self.file=None
    def __enter__(self):
        try:
            self.file=open(self.filename,self.mode)
            return self.file
        except FileNotFoundError:
            print(f"Warning: {self.filename} not found, using StringIO")
            import io
            self.file=io.StringIO("Default content")
            return self.file
    def __exit__(self,exc_type,exc_val,exc_tb):
        if self.file: self.file.close()
        return False
with SafeFile("test.txt","w") as f:
    f.write("Hello")
with SafeFile("test.txt") as f:
    print(f.read())
with SafeFile("missing.txt") as f:
    print(f.read())
A26:
class ValidationError(Exception): pass
class EmptyFieldError(ValidationError): pass
class FormatError(ValidationError): pass
def validate_email(email):
    if not email: raise EmptyFieldError("Email cannot be empty")
    if "@" not in email: raise FormatError(f"Invalid email: {email}")
    return True
for email in ["alice@example.com","","bademail","bob@test.org"]:
    try:
        validate_email(email)
        print(f"{email or repr(email)}: Valid")
    except EmptyFieldError as e:
        print(f"Empty: {e}")
    except FormatError as e:
        print(f"Format: {e}")
A27:
from contextlib import suppress
data=[1,0,2,0,3]
results=[]
for d in data:
    with suppress(ZeroDivisionError):
        results.append(10/d)
print("Results (zeros skipped):", results)
A28:
def parse_config(text):
    try:
        lines=text.strip().split("\n")
        config={}
        for line in lines:
            k,v=line.split("=")
            config[k.strip()]=v.strip()
        return config
    except ValueError as e:
        raise RuntimeError(f"Config parse error: invalid format") from e
configs=["host=localhost\nport=8080","host=localhost\nbadline","name=test\nvalue=42"]
for c in configs:
    try:
        print(parse_config(c))
    except RuntimeError as e:
        print(f"Error: {e} | Cause: {e.__cause__}")
A29:
def show_hierarchy(exc_class, indent=0):
    print(" "*indent+exc_class.__name__)
    for sub in exc_class.__subclasses__():
        show_hierarchy(sub, indent+2)
show_hierarchy(Exception)
A30:
def calculate(expr):
    try:
        parts=expr.split()
        if len(parts)!=3: raise ValueError("Format: num op num")
        a,op,b=float(parts[0]),parts[1],float(parts[2])
        ops={"+":lambda x,y:x+y,"-":lambda x,y:x-y,"*":lambda x,y:x*y,"/":lambda x,y:x/y}
        if op not in ops: raise ValueError(f"Unknown op: {op}")
        return ops[op](a,b)
    except ZeroDivisionError: raise ZeroDivisionError("Cannot divide by zero")
for expr in ["10 + 5","8 / 0","3 * abc","6 % 2","10 / 4"]:
    try:
        print(f"{expr} = {calculate(expr)}")
    except Exception as e:
        print(f"{expr} → Error: {type(e).__name__}: {e}")
Unit 1 · Computational Thinking & Programming
Text File Handling
open(), read(), write(), seek(), tell(), file modes, with statement, reading line by line.
10
Marks

File Modes & Operations

3.1
File Open Modes
'r' — Read (default). Error if file absent.
'w' — Write. Creates/overwrites file.
'a' — Append. Creates if absent; adds to end.
'x' — Exclusive create. Error if exists.
'r+' — Read & Write (file must exist).
'w+' — Write & Read (overwrites).
'b' — Binary mode (add to above: 'rb', 'wb')
't' — Text mode (default)

Always use with statement:
with open('file.txt','r') as f:
    content = f.read()
(auto-closes file even if error occurs)
Read Methods
f.read() → entire file as one string
f.read(n) → read n characters
f.readline() → one line (with \n)
f.readlines() → list of all lines

Iterate directly:
for line in f:
    print(line.strip())

Position methods:
f.tell() → current position (bytes)
f.seek(0) → go to start
f.seek(n) → go to position n
Write Methods
f.write(str) → writes string, returns char count
f.writelines(list) → writes list of strings

Note: write() does NOT add \n automatically. You must add it:
f.write('Hello\n')

Flush: f.flush() — force write to disk

Check if closed: f.closed → True/False
File name: f.name
Mode: f.mode

🐍 Python Runner — Text File Programs

3.2
P1: Write & Read
P2: Read Methods
P3: Append Mode
P4: seek() & tell()
P5: Word Count
P6: Copy File
P7: Word Frequency
P8: Head & Tail
P9: Search & Replace
P10: Student Marks File
P1: Parse & Sort
P2: Merge Files
P3: File Indexer
P4: Config File
P5: Simple DB File
P6: Log Analysis
P7: File Encryption
P8: Report Generator
P9: Text Statistics
P10: Diary App
P1: Inverted Index
P2: RLE Compression
P3: Persistent Queue
P4: File Diff
P5: Virtual File System
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • Always use with open(filename, mode) as f: — it auto-closes the file even if an exception occurs.
  • 'w' mode overwrites existing content. Use 'a' mode to append without deleting existing data.
  • f.read() returns whole file. f.readline() returns ONE line. f.readlines() returns a LIST of lines.
  • Iterate with for line in f: — most memory-efficient method for large files.
  • f.write() does NOT add newline automatically. Add \n explicitly.
  • f.seek(0) resets file pointer to start. f.tell() returns current position.

Topic Test: File Handling (Class 12)

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which module handles CSV files?
  • (a) file
  • (b) csv
  • (c) pandas
  • (d) io
[1 mark]
Q2.
pickle module is used to:
  • (a) Read text files
  • (b) Serialise Python objects to binary
  • (c) Handle CSV
  • (d) Compress files
[1 mark]
Q3.
What is serialisation?
  • (a) Converting object to bytes/string for storage
  • (b) Sorting a list
  • (c) Compressing a file
  • (d) Encrypting data
[1 mark]
Q4.
csv.reader returns:
  • (a) List of strings
  • (b) Iterator of rows (lists)
  • (c) String
  • (d) Dict
[1 mark]
Q5.
Which mode opens binary file for writing?
  • (a) "w"
  • (b) "wb"
  • (c) "bw"
  • (d) "wbin"
[1 mark]
Q6.
json.dumps() converts:
  • (a) JSON string to dict
  • (b) Python object to JSON string
  • (c) File to JSON
  • (d) Dict to CSV
[1 mark]
Q7.
What does DictReader do?
  • (a) Reads CSV as list rows
  • (b) Reads CSV rows as dicts (header as keys)
  • (c) Reads JSON
  • (d) Reads binary
[1 mark]
Q8.
Which is NOT a pickle operation?
  • (a) dump
  • (b) load
  • (c) dumps
  • (d) write
[1 mark]
Q9.
json.load() vs json.loads():
  • (a) Same
  • (b) load reads from file, loads from string
  • (c) loads reads from file
  • (d) Both from string
[1 mark]
Q10.
Which file operation is NOT line-by-line?
  • (a) readline()
  • (b) readlines()
  • (c) read()
  • (d) for line in file
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Output?
import json
d={"name":"Alice","age":16}
s=json.dumps(d)
print(type(s).__name__, s)
[2 marks]
Q12.
What is the output of the following?
What prints?
import json
s='{"x":10,"y":20}'
d=json.loads(s)
print(d["x"]+d["y"])
[2 marks]
Q13.
What is the output of the following?
Find:
import pickle
data=[1,2,3,"hello"]
b=pickle.dumps(data)
loaded=pickle.loads(b)
print(loaded)
[2 marks]
Q14.
What is the output of the following?
Output of csv.reader on "a,b,c\n1,2,3"?
[2 marks]
Q15.
What is the output of the following?
What does with open("f.csv","r",newline="") do?
[2 marks]
Q16.
What is the output of the following?
Difference between pickle and json serialisation.
[2 marks]
Q17.
What is the output of the following?
Output?
import io, csv
buf=io.StringIO()
w=csv.writer(buf)
w.writerow(["Name","Age"])
w.writerow(["Alice",16])
print(buf.getvalue())
[2 marks]
Q18.
What is the output of the following?
What is the danger of pickle from untrusted sources?
[2 marks]
Q19.
What is the output of the following?
Output?
import json
print(json.dumps([1,2,3], indent=2))
[2 marks]
Q20.
What is the output of the following?
Difference between text mode and binary mode files.
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write and read student records using CSV.
[3 marks]
Q22.
Use DictReader to display CSV data.
[3 marks]
Q23.
Serialise and deserialise with pickle.
[3 marks]
Q24.
Save and load configuration using JSON.
[3 marks]
Q25.
Compare pickle vs json for a complex object.
[3 marks]
Q26.
Write a CSV gradebook and compute averages.
[3 marks]
Q27.
Read CSV, filter rows, write to new CSV.
[3 marks]
Q28.
Build a simple JSON-based contact book.
[3 marks]
Q29.
Pickle a list of objects and reload.
[3 marks]
Q30.
JSON pretty-print and validate.
[3 marks]
A1: (b) — csv module provides reader/writer for CSV files.
A2: (b) — pickle: serialises (dumps) and deserialises (loads) Python objects.
A3: (a) — Serialisation: converting Python objects to bytes for storage/transmission.
A4: (b) — csv.reader returns an iterator; each row is a list of strings.
A5: (b) — "wb" opens file in binary write mode — writes raw bytes.
A6: (b) — json.dumps() serialises Python object to a JSON-formatted string.
A7: (b) — csv.DictReader: each row becomes an OrderedDict using header row as keys.
A8: (d) — pickle.write() does not exist. Use dump (to file), dumps (to bytes).
A9: (b) — json.load(file): file → Python; json.loads(str): JSON string → Python.
A10: (c) — read() reads entire file as one string; others are line-based.
A11: str {"name": "Alice", "age": 16}
A12: 30
A13: [1, 2, 3, 'hello']
A14: Row 1: ['a', 'b', 'c'] Row 2: ['1', '2', '3']
A15: "newline=" prevents csv.reader from mangling \r\n line endings.
A16: pickle: binary, Python-specific, supports all types. json: text, cross-language, supports only basic types (str,int,float,list,dict,bool,None).
A17: Name,Age Alice,16
A18: pickle.loads() can execute arbitrary code — never unpickle data from untrusted sources.
A19: [ 1, 2, 3 ]
A20: Text: encodes/decodes (UTF-8 default), translates \n. Binary: raw bytes, no encoding.
A21:
import csv
students=[("Name","Maths","Science"),("Alice",90,85),("Bob",72,68)]
with open("students.csv","w",newline="") as f:
    csv.writer(f).writerows(students)
with open("students.csv") as f:
    for row in csv.reader(f):
        print(row)
A22:
import csv, io
data="Name,Age,City\nAlice,16,Delhi\nBob,17,Mumbai"
reader=csv.DictReader(io.StringIO(data))
for row in reader:
    print(f"{row['Name']} is {row['Age']} from {row['City']}")
A23:
import pickle
class Student:
    def __init__(self,name,marks):
        self.name=name; self.marks=marks
    def __repr__(self): return f"Student({self.name},{self.marks})"
s=Student("Alice",90)
with open("student.pkl","wb") as f:
    pickle.dump(s,f)
with open("student.pkl","rb") as f:
    loaded=pickle.load(f)
print(loaded, type(loaded).__name__)
A24:
import json
config={"host":"localhost","port":8080,"debug":True,"max_conn":100}
with open("config.json","w") as f:
    json.dump(config,f,indent=2)
with open("config.json") as f:
    loaded=json.load(f)
print("Port:",loaded["port"])
loaded["port"]=9090
with open("config.json","w") as f:
    json.dump(loaded,f,indent=2)
print("Updated port:",loaded["port"])
A25:
import json, pickle, sys
data={"students":["Alice","Bob"],"scores":[90,85],"active":True}
j_str=json.dumps(data)
p_bytes=pickle.dumps(data)
print(f"JSON size: {sys.getsizeof(j_str)} bytes")
print(f"Pickle size: {sys.getsizeof(p_bytes)} bytes")
print("JSON:", json.loads(j_str))
print("Pickle:", pickle.loads(p_bytes))
A26:
import csv, io
records=[("Alice",85,90,88),("Bob",72,65,70),("Carol",95,92,97)]
buf=io.StringIO()
w=csv.writer(buf)
w.writerow(["Name","Math","Science","English","Average"])
for r in records:
    avg=sum(r[1:])/3
    w.writerow(list(r)+[f"{avg:.1f}"])
buf.seek(0)
for row in csv.reader(buf):
    print(",".join(row))
A27:
import csv, io
data="Name,Score\nAlice,90\nBob,55\nCarol,78\nDave,45"
src=csv.DictReader(io.StringIO(data))
passed=[r for r in src if int(r["Score"])>=60]
buf=io.StringIO()
w=csv.DictWriter(buf,fieldnames=["Name","Score"])
w.writeheader()
w.writerows(passed)
buf.seek(0)
print("Passed students:")
print(buf.read())
A28:
import json, os
FILE="contacts.json"
if os.path.exists(FILE):
    with open(FILE) as f: contacts=json.load(f)
else:
    contacts={}
contacts["Alice"]="9876543210"
contacts["Bob"]="8765432109"
with open(FILE,"w") as f:
    json.dump(contacts,f,indent=2)
print("Contacts:")
for name,num in contacts.items():
    print(f"  {name}: {num}")
A29:
import pickle
class Point:
    def __init__(self,x,y): self.x=x; self.y=y
    def dist(self): return (self.x**2+self.y**2)**0.5
    def __repr__(self): return f"Point({self.x},{self.y})"
points=[Point(3,4),Point(0,5),Point(1,1)]
with open("points.pkl","wb") as f:
    pickle.dump(points,f)
with open("points.pkl","rb") as f:
    loaded=pickle.load(f)
for p in loaded:
    print(f"{p} distance from origin: {p.dist():.2f}")
A30:
import json
raw_jsons=[
    '{"name":"Alice","age":16}',
    '{"invalid json',
    '[1,2,3]',
    '{"nested":{"a":1,"b":2}}'
]
for raw in raw_jsons:
    try:
        parsed=json.loads(raw)
        print("Valid:", json.dumps(parsed, indent=2)[:50])
    except json.JSONDecodeError as e:
        print(f"Invalid JSON: {e.msg}")
Unit 1 · Computational Thinking & Programming
Binary File Handling
pickle module — dump, load, reading/writing Python objects to binary files.
6
Marks

Binary Files & pickle

4.1
Binary vs Text Files
Text files: store data as human-readable characters
Binary files: store data as bytes (not directly readable)

Binary files are used for:
• Images, audio, video
• Compiled programs (.exe, .pyc)
• Database files
• Serialised Python objects (pickle)

Open binary:
open('file.bin', 'rb') — read binary
open('file.bin', 'wb') — write binary
open('file.bin', 'ab') — append binary
pickle Module
Serialization: converting Python object → bytes
Deserialization: bytes → Python object

import pickle

Write (dump):
with open('data.pkl','wb') as f:
    pickle.dump(obj, f)

Read (load):
with open('data.pkl','rb') as f:
    obj = pickle.load(f)

To bytes: pickle.dumps(obj)
From bytes: pickle.loads(bytes_data)
Multiple Records
To store multiple records, dump them all in a loop:

with open('students.pkl','wb') as f:
    for s in students:
        pickle.dump(s, f)

Read back:
with open('students.pkl','rb') as f:
    while True:
        try:
            s = pickle.load(f)
        except EOFError:
            break

OR dump entire list at once:
pickle.dump(students_list, f)

🐍 Python Runner — Binary File Programs

4.2
P1: Basic pickle
P2: Student Records
P3: Multiple Objects
P4: Pickle Custom Class
P5: Search Binary File
P6: Update Record
P7: Delete Record
P8: Complex Data Types
P9: Inventory System
P10: Exam Results
P1: CRUD with Binary
P2: Versioned Snapshots
P3: GradeBook
P4: Binary vs Text Size
P5: SMS System
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • pickle serialises any Python object (lists, dicts, classes) to binary format.
  • Binary file mode is 'rb' (read binary) and 'wb' (write binary). Forgetting 'b' → error.
  • pickle.dump(obj, file) → write. pickle.load(file) → read. File must be open in binary mode.
  • To read multiple individually-dumped objects, use a while True / except EOFError loop.
  • To update a record: load all → modify in memory → save all (overwrite the file).
  • Binary files are NOT human-readable. Open them in 'rb' mode, NOT 'r' mode.

Topic Test: Binary Files & CSV

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Binary files store data as:
  • (a) Text lines
  • (b) Raw bytes
  • (c) CSV rows
  • (d) JSON objects
[1 mark]
Q2.
Which mode reads a binary file?
  • (a) "r"
  • (b) "rb"
  • (c) "br"
  • (d) "binary"
[1 mark]
Q3.
pickle.dump(obj, file) requires file opened in:
  • (a) "r"
  • (b) "w"
  • (c) "rb"
  • (d) "wb"
[1 mark]
Q4.
CSV stands for:
  • (a) Comma Separated Values
  • (b) Comma String Values
  • (c) Character Separated Values
  • (d) Column String Values
[1 mark]
Q5.
Which csv class maps column names to values?
  • (a) csv.reader
  • (b) csv.writer
  • (c) csv.DictReader
  • (d) csv.DictWriter
[1 mark]
Q6.
What is the default delimiter in csv.writer?
  • (a) Tab
  • (b) Space
  • (c) Comma
  • (d) Semicolon
[1 mark]
Q7.
Which method writes all rows at once?
  • (a) writerow()
  • (b) write()
  • (c) writerows()
  • (d) writeall()
[1 mark]
Q8.
open(file,"wb") creates file if not exists?
  • (a) No
  • (b) Yes
  • (c) Only on Windows
  • (d) Only on Linux
[1 mark]
Q9.
Struct module is used for:
  • (a) OOP structures
  • (b) Packing/unpacking binary data
  • (c) Database
  • (d) Sorting
[1 mark]
Q10.
What does seek(-1, 2) do?
  • (a) Go to start
  • (b) Go to last byte
  • (c) Go to byte -1
  • (d) Error
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Write and read an integer as binary.
[2 marks]
Q12.
What is the output of the following?
What does tell() return after writing 10 bytes?
[2 marks]
Q13.
What is the output of the following?
Output?
import csv, io
buf=io.StringIO()
w=csv.writer(buf)
w.writerow([1,2,3])
buf.seek(0)
print(buf.read())
[2 marks]
Q14.
What is the output of the following?
Difference between csv.reader and csv.DictReader.
[2 marks]
Q15.
What is the output of the following?
What is the use of newline="" when opening CSV files?
[2 marks]
Q16.
What is the output of the following?
How do you write a binary file containing bytes [65,66,67]?
[2 marks]
Q17.
What is the output of the following?
Output?
with open("t.bin","wb") as f:
    f.write(b"hello")
with open("t.bin","rb") as f:
    print(f.read(3), f.read())
[2 marks]
Q18.
What is the output of the following?
What is struct format string "3s2i"?
[2 marks]
Q19.
What is the output of the following?
How do you append to a binary file?
[2 marks]
Q20.
What is the output of the following?
CSV quoting: when are fields automatically quoted?
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write and read student data using pickle.
[3 marks]
Q22.
Write integers to a binary file using struct.
[3 marks]
Q23.
Write CSV and read with DictReader.
[3 marks]
Q24.
Search and update records in CSV.
[3 marks]
Q25.
Compare file sizes: text vs binary storage.
[3 marks]
Q26.
Encrypt text file using XOR cipher.
[3 marks]
Q27.
Merge multiple CSV files.
[3 marks]
Q28.
Binary file: store and retrieve a 2D matrix.
[3 marks]
Q29.
CSV statistics: min, max, average from numeric column.
[3 marks]
Q30.
Validate CSV data before writing.
[3 marks]
A1: (b) — Binary files store raw byte sequences, not human-readable text.
A2: (b) — "rb" opens a file in binary read mode.
A3: (d) — pickle.dump writes bytes — file must be in binary write mode "wb".
A4: (a) — CSV = Comma Separated Values — plain text with comma delimiters.
A5: (c) — DictReader uses the header row as keys for each row dictionary.
A6: (c) — Default delimiter is comma. Use delimiter="\t" for TSV.
A7: (c) — writerows() takes an iterable and writes all rows at once.
A8: (b) — "wb" creates the file if it doesn't exist and truncates if it does.
A9: (b) — struct module packs Python values into binary byte strings and unpacks back.
A10: (b) — seek(-1, 2): move 1 byte before the end (mode 2 = from end).
A11: import struct b=struct.pack("i",42) # 4 bytes val=struct.unpack("i",b)[0] print(val) # 42
A12: 10 (file pointer is at byte position 10)
A13: 1,2,3
A14: reader: returns rows as lists. DictReader: returns rows as dicts using header as keys.
A15: Prevents Python's universal newline translation from mangling \r\n in CSV, which csv module expects to handle itself.
A16: with open("f.bin","wb") as f: f.write(bytes([65,66,67])) # Reads back as b"ABC" (ASCII codes)
A17: b'hel' b'lo'
A18: "3s": 3-byte string, "2i": two integers. Total bytes: 3+4+4=11 (with padding may vary).
A19: Open with "ab" mode: open("file.bin","ab"). Appends bytes without truncating.
A20: When field contains the delimiter, newline, or the quotechar (default "). e.g. "hello, world" becomes "\"hello, world\"".
A21:
import pickle
students=[
    {"name":"Alice","marks":90},
    {"name":"Bob","marks":72},
]
with open("data.pkl","wb") as f:
    pickle.dump(students,f)
with open("data.pkl","rb") as f:
    loaded=pickle.load(f)
for s in loaded:
    print(s["name"],":",s["marks"])
A22:
import struct
numbers=[10,200,3000,40000]
with open("nums.bin","wb") as f:
    for n in numbers:
        f.write(struct.pack("i",n))
with open("nums.bin","rb") as f:
    while True:
        data=f.read(4)
        if not data: break
        print(struct.unpack("i",data)[0])
A23:
import csv
rows=[{"Name":"Alice","Score":90},{"Name":"Bob","Score":72}]
with open("scores.csv","w",newline="") as f:
    w=csv.DictWriter(f,fieldnames=["Name","Score"])
    w.writeheader()
    w.writerows(rows)
with open("scores.csv",newline="") as f:
    for row in csv.DictReader(f):
        grade="Pass" if int(row["Score"])>=60 else "Fail"
        print(f"{row['Name']}: {row['Score']} ({grade})")
A24:
import csv, io
data="ID,Name,Score\n1,Alice,90\n2,Bob,72\n3,Carol,85"
rows=list(csv.DictReader(io.StringIO(data)))
for row in rows:
    if row["Name"]=="Bob":
        row["Score"]="80"
buf=io.StringIO()
w=csv.DictWriter(buf,fieldnames=["ID","Name","Score"])
w.writeheader()
w.writerows(rows)
buf.seek(0)
print(buf.read())
A25:
import struct, os
# Text storage
numbers=list(range(100))
with open("text_nums.txt","w") as f:
    for n in numbers: f.write(f"{n}\n")
# Binary storage
with open("bin_nums.bin","wb") as f:
    for n in numbers: f.write(struct.pack("i",n))
print(f"Text size: {os.path.getsize('text_nums.txt')} bytes")
print(f"Binary size: {os.path.getsize('bin_nums.bin')} bytes")
A26:
KEY=42
def xor_cipher(data,key):
    return bytes(b^key for b in data)
text="Secret message from CBSEMOCK!"
encrypted=xor_cipher(text.encode(),KEY)
with open("encrypted.bin","wb") as f:
    f.write(encrypted)
with open("encrypted.bin","rb") as f:
    data=f.read()
decrypted=xor_cipher(data,KEY).decode()
print("Original:",text)
print("Decrypted:",decrypted)
A27:
import csv, io
csv1="Name,Score\nAlice,90\nBob,72"
csv2="Name,Score\nCarol,88\nDave,55"
all_rows=[]
for src in [csv1,csv2]:
    reader=csv.DictReader(io.StringIO(src))
    all_rows.extend(reader)
buf=io.StringIO()
w=csv.DictWriter(buf,fieldnames=["Name","Score"])
w.writeheader()
w.writerows(all_rows)
buf.seek(0)
print(buf.read())
A28:
import struct
matrix=[[1,2,3],[4,5,6],[7,8,9]]
with open("matrix.bin","wb") as f:
    rows=len(matrix); cols=len(matrix[0])
    f.write(struct.pack("ii",rows,cols))
    for row in matrix:
        for val in row:
            f.write(struct.pack("i",val))
with open("matrix.bin","rb") as f:
    rows,cols=struct.unpack("ii",f.read(8))
    for i in range(rows):
        row=[struct.unpack("i",f.read(4))[0] for _ in range(cols)]
        print(row)
A29:
import csv, io
data="Student,Math,Science\nAlice,85,90\nBob,72,68\nCarol,95,88"
rows=list(csv.DictReader(io.StringIO(data)))
for subject in ["Math","Science"]:
    scores=[int(r[subject]) for r in rows]
    print(f"{subject}: Min={min(scores)} Max={max(scores)} Avg={sum(scores)/len(scores):.1f}")
A30:
import csv, io
raw_data=[("Alice","90"),("Bob","invalid"),("","85"),("Carol","105")]
valid=[]
errors=[]
for name,score in raw_data:
    try:
        if not name: raise ValueError("Name is empty")
        s=int(score)
        if not 0<=s<=100: raise ValueError(f"Score {s} out of range")
        valid.append((name,score))
    except ValueError as e:
        errors.append(f"{name}/{score}: {e}")
print("Valid:",valid)
print("Errors:",errors)
Unit 1 · Computational Thinking & Programming
CSV File Handling
csv module — reader, writer, DictReader, DictWriter for structured data files.
6
Marks

CSV Module

5.1
csv.reader / writer
import csv

Read:
with open('f.csv','r',newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row) # list of strings

Write:
with open('f.csv','w',newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['Name','Marks'])
    writer.writerows(data)

⚠️ Always use newline='' to avoid blank rows on Windows.
DictReader / DictWriter
DictReader — each row is a dict with column headers as keys:
reader = csv.DictReader(f)
for row in reader:
    print(row['Name'], row['Marks'])

DictWriter — write dicts as CSV rows:
fieldnames = ['Name','Marks','Grade']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Name':'Aarav','Marks':85,'Grade':'A'})
CSV Options
delimiter: character separating fields (default ',')
csv.reader(f, delimiter=';')
csv.reader(f, delimiter='\t') — TSV

quotechar: char to quote fields containing delimiter
quoting: QUOTE_ALL, QUOTE_MINIMAL, QUOTE_NONE

Skip header:
next(reader) # skip first row

Get header:
reader.fieldnames on DictReader

Write with quote:
csv.writer(f, quoting=csv.QUOTE_ALL)

🐍 Python Runner — CSV File Programs

5.2
P1: Basic CSV
P2: DictReader
P3: CSV Analysis
P4: Filter CSV
P5: Append CSV
P6: Skip Header
P7: Custom Delimiter
P8: Search CSV
P9: Update CSV
P10: Sales Report
P1: CSV Pipeline
P2: Merge CSVs
P3: Pivot Table
P4: CSV CRUD
P5: Class Statistics
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • Always open CSV files with newline='': open('f.csv', 'r', newline='') to avoid extra blank rows.
  • csv.reader gives each row as a list. csv.DictReader gives each row as an OrderedDict.
  • csv.writer.writerow() writes one row. writerows() writes multiple rows at once.
  • DictWriter needs writeheader() to write the column names on the first row.
  • To skip the header row with csv.reader, use next(reader) before the loop.
  • All values read from CSV are strings. Convert to int/float explicitly: int(row['Marks']).

Topic Test: CSV File Handling (Advanced)

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which CSV quoting constant quotes all fields?
  • (a) QUOTE_MINIMAL
  • (b) QUOTE_ALL
  • (c) QUOTE_NONNUMERIC
  • (d) QUOTE_NONE
[1 mark]
Q2.
csv.QUOTE_NONNUMERIC converts unquoted fields to:
  • (a) str
  • (b) int
  • (c) float
  • (d) bool
[1 mark]
Q3.
Which parameter changes CSV delimiter to tab?
  • (a) sep="\t"
  • (b) delimiter="\t"
  • (c) tab=True
  • (d) sep=tab
[1 mark]
Q4.
DictWriter requires:
  • (a) fieldnames parameter
  • (b) auto headers
  • (c) header=True
  • (d) column list
[1 mark]
Q5.
What does csv.Sniffer do?
  • (a) Creates CSV
  • (b) Detects CSV dialect
  • (c) Validates CSV
  • (d) Sorts CSV
[1 mark]
Q6.
Which handles missing values gracefully?
  • (a) DictReader with restval
  • (b) reader with default
  • (c) writer with fill
  • (d) None
[1 mark]
Q7.
extrasaction in DictWriter:
  • (a) Adds extra columns
  • (b) Handles extra keys in dict (ignore/raise)
  • (c) Extends file
  • (d) None
[1 mark]
Q8.
csv.reader by default handles:
  • (a) Only UTF-8
  • (b) Any encoding with proper open()
  • (c) Only ASCII
  • (d) Auto-detects encoding
[1 mark]
Q9.
Which is fastest for large CSV files?
  • (a) csv.reader
  • (b) csv.DictReader
  • (c) pandas
  • (d) All same
[1 mark]
Q10.
line_num attribute of csv.reader gives:
  • (a) Total lines
  • (b) Current line number
  • (c) Blank lines count
  • (d) Header line
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Output?
import csv, io
f=io.StringIO("a,b,c\n1,2,3")
r=csv.reader(f)
for row in r:
    print(r.line_num, row)
[2 marks]
Q12.
What is the output of the following?
What does QUOTE_ALL produce for ["hello",42]?
[2 marks]
Q13.
What is the output of the following?
Find the sniffer output on "a;b;c\n1;2;3".
[2 marks]
Q14.
What is the output of the following?
DictReader with missing column: what does restval do?
[2 marks]
Q15.
What is the output of the following?
Output?
import csv, io
f=io.StringIO("1,2,3\n4,5,6")
r=csv.reader(f,quoting=csv.QUOTE_NONNUMERIC)
for row in r: print(row)
[2 marks]
Q16.
What is the output of the following?
How to read a CSV with ";" delimiter?
[2 marks]
Q17.
What is the output of the following?
Output?
import csv, io
buf=io.StringIO()
w=csv.writer(buf,quoting=csv.QUOTE_ALL)
w.writerow(["Hello","World",42])
buf.seek(0)
print(buf.read())
[2 marks]
Q18.
What is the output of the following?
What is a CSV dialect?
[2 marks]
Q19.
What is the output of the following?
DictWriter with extrasaction="ignore": what happens with extra keys?
[2 marks]
Q20.
What is the output of the following?
How to skip the header row when using csv.reader?
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Read CSV and compute statistics per column.
[3 marks]
Q22.
Sort CSV data by a column and write back.
[3 marks]
Q23.
Detect CSV dialect with Sniffer.
[3 marks]
Q24.
Filter CSV rows based on multiple conditions.
[3 marks]
Q25.
Pivot CSV data: group by one column.
[3 marks]
Q26.
Add a computed column (grade) to CSV.
[3 marks]
Q27.
Handle CSV with quoted fields containing commas.
[3 marks]
Q28.
Convert TSV to CSV.
[3 marks]
Q29.
Validate CSV and report errors.
[3 marks]
Q30.
Merge two CSVs on a common key.
[3 marks]
A1: (b) — csv.QUOTE_ALL: all fields are quoted regardless of content.
A2: (c) — QUOTE_NONNUMERIC: unquoted fields (read) are converted to float.
A3: (b) — csv.reader(f, delimiter="\t") reads TSV (tab-separated) files.
A4: (a) — DictWriter needs fieldnames to know the column order.
A5: (b) — csv.Sniffer: detects delimiter, quoting style from a sample of CSV data.
A6: (a) — DictReader(restval=default): fills missing fields with the specified default.
A7: (b) — extrasaction="ignore": ignores dict keys not in fieldnames without error.
A8: (b) — csv module works with whatever encoding the file is opened with.
A9: (c) — pandas is faster for large CSV analysis due to vectorised C operations.
A10: (b) — reader.line_num: number of lines read from the source so far.
A11: 1 ['a', 'b', 'c'] 2 ['1', '2', '3']
A12: "hello","42" — both fields quoted.
A13: Detected dialect: delimiter=';'
A14: Fills missing value with the restval default (e.g. "" or None).
A15: [1.0, 2.0, 3.0] [4.0, 5.0, 6.0]
A16: csv.reader(f, delimiter=";")
A17: "Hello","World","42"
A18: A named bundle of CSV formatting parameters (delimiter, quotechar, lineterminator). Built-in: "excel", "excel-tab", "unix".
A19: Extra keys in the row dict are silently ignored; only fieldnames columns are written.
A20: next(reader) # reads and discards the header line
A21:
import csv, io, statistics
data="Name,Math,Sci,Eng\nAlice,85,90,88\nBob,72,68,70\nCarol,95,92,97"
rows=list(csv.DictReader(io.StringIO(data)))
for subj in ["Math","Sci","Eng"]:
    scores=[int(r[subj]) for r in rows]
    print(f"{subj}: Mean={statistics.mean(scores):.1f} Stdev={statistics.stdev(scores):.1f}")
A22:
import csv, io
data="Name,Score\nCarol,95\nAlice,85\nBob,72"
rows=list(csv.DictReader(io.StringIO(data)))
rows.sort(key=lambda r:int(r["Score"]),reverse=True)
buf=io.StringIO()
w=csv.DictWriter(buf,fieldnames=["Name","Score"])
w.writeheader()
w.writerows(rows)
buf.seek(0)
print(buf.read())
A23:
import csv
samples=["a,b,c\n1,2,3","a;b;c\n1;2;3","a|b|c\n1|2|3"]
for sample in samples:
    dialect=csv.Sniffer().sniff(sample)
    print(f"Delimiter: {repr(dialect.delimiter)}")
A24:
import csv, io
data="Name,Score,Attendance\nAlice,90,95\nBob,72,60\nCarol,85,88\nDave,55,70"
rows=list(csv.DictReader(io.StringIO(data)))
passed=[r for r in rows if int(r["Score"])>=60 and int(r["Attendance"])>=75]
print("Eligible students:")
for r in passed: print(f"  {r['Name']}: Score={r['Score']} Att={r['Attendance']}%")
A25:
import csv, io
data="Dept,Name,Score\nCS,Alice,90\nMath,Bob,85\nCS,Carol,88\nMath,Dave,72"
rows=list(csv.DictReader(io.StringIO(data)))
groups={}
for r in rows:
    groups.setdefault(r["Dept"],[]).append(r["Name"])
for dept,names in groups.items():
    print(f"{dept}: {names}")
A26:
import csv, io
data="Name,Score\nAlice,90\nBob,72\nCarol,55"
rows=list(csv.DictReader(io.StringIO(data)))
for r in rows:
    s=int(r["Score"])
    r["Grade"]="A" if s>=80 else "B" if s>=60 else "F"
buf=io.StringIO()
w=csv.DictWriter(buf,fieldnames=["Name","Score","Grade"])
w.writeheader()
w.writerows(rows)
buf.seek(0)
print(buf.read())
A27:
import csv, io
data='Name,Address,Score\n"Smith, John","123 Main St, NY",90\n"Jones, Amy","456 Oak Ave, CA",85'
for row in csv.DictReader(io.StringIO(data)):
    print(f"{row['Name']} at {row['Address']}: {row['Score']}") 
A28:
import csv, io
tsv="Name\tScore\tGrade\nAlice\t90\tA\nBob\t72\tB"
tsv_reader=csv.reader(io.StringIO(tsv),delimiter="\t")
buf=io.StringIO()
csv_writer=csv.writer(buf)
for row in tsv_reader:
    csv_writer.writerow(row)
buf.seek(0)
print(buf.read())
A29:
import csv, io
data="Name,Age,Score\nAlice,16,90\nBob,abc,72\nCarol,17\nDave,15,105"
errors=[]
valid=[]
for i,row in enumerate(csv.DictReader(io.StringIO(data)),1):
    try:
        name=row["Name"]
        age=int(row["Age"])
        score=int(row.get("Score",0))
        if not 0<=score<=100: raise ValueError("Score out of range")
        valid.append(row)
    except (ValueError,KeyError) as e:
        errors.append(f"Row {i}: {e}")
print(f"Valid: {len(valid)} Errors: {len(errors)}")
for e in errors: print(" ",e)
A30:
import csv, io
csv1="ID,Name\n1,Alice\n2,Bob\n3,Carol"
csv2="ID,Score\n1,90\n2,72\n3,88"
d1={r["ID"]:r for r in csv.DictReader(io.StringIO(csv1))}
d2={r["ID"]:r for r in csv.DictReader(io.StringIO(csv2))}
print("ID Name Score")
for id,row in d1.items():
    score=d2.get(id,{}).get("Score","N/A")
    print(id,row["Name"],score)
Unit 1 · Computational Thinking & Programming
Stack
LIFO data structure — push, pop, peek, isEmpty using Python list. Applications: expression evaluation, undo, recursion.
10
Marks

Stack — LIFO Structure

6.1
STACK 20 35 50 10 ← TOP [3] [2] [1] [0] PUSH(10) stack.append(10) POP() → 10 stack.pop() BOTTOM (index 0) — never removed first Stack Operations O(1) Push: stack.append(val) Pop: stack.pop() Peek: stack[-1] isEmpty: len(stack) == 0
Stack Class Implementation
class Stack:
  def __init__(self):
    self.items = []
  def push(self, val):
    self.items.append(val)
  def pop(self):
    if not self.is_empty():
      return self.items.pop()
  def peek(self):
    return self.items[-1]
  def is_empty(self):
    return len(self.items) == 0
  def size(self):
    return len(self.items)
Applications of Stack
• Undo/Redo in text editors
• Browser back/forward navigation
• Balanced parentheses checking
• Expression conversion: Infix → Postfix
• Expression evaluation: Postfix evaluation
• Function call stack (recursion)
• DFS (Depth First Search)
• Syntax parsing by compilers

LIFO: Last In First Out
Top element is always the last one pushed.
Exam Tip
Stack Trace Format (CBSE):
Given push/pop operations, show state:

push(5) → [5] TOP=5
push(3) → [5,3] TOP=3
push(7) → [5,3,7] TOP=7
pop() → [5,3] returns 7
peek() → returns 3
pop() → [5] returns 3

Always draw the stack vertically with TOP at the right end of the list (or top of diagram).

🐍 Python Runner — Stack Programs

6.2
P1: Stack Class
P2: Stack Trace
P3: Balanced Parentheses
P4: Reverse String
P5: Bounded Stack
P6: Dec to Binary
P7: Palindrome
P8: Undo/Redo
P9: Two Stacks
P10: Expression Validator
P1: Infix→Postfix
P2: Postfix Evaluator
P3: Sort a Stack
P4: Browser History
P5: Iterative DFS
P6: Stack Calculator
P7: Stock Span
P8: Next Greater Element
P9: Histogram Area
P10: Min Stack
P1: Maze Solver
P2: Full Expression Eval
P3: Hanoi with Stack
P4: Decode String
P5: Persistent Stack
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • LIFO: Last In, First Out — the last element pushed is the first to be popped.
  • Python list used as stack: push = append(), pop = pop(), peek = list[-1].
  • Always check is_empty() before pop() or peek() to avoid errors (underflow).
  • Stack applications: balanced parentheses, infix→postfix, postfix evaluation, undo, DFS.
  • Infix: A+B*C. Postfix: A B C * +. Operators come AFTER operands in postfix.
  • CBSE exam: Show stack state after EACH operation — list format with TOP marked.

Topic Test: Database Concepts

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
A DBMS manages:
  • (a) Files only
  • (b) Only SQL
  • (c) Organised data with access control
  • (d) Only tables
[1 mark]
Q2.
Which is a relational DBMS?
  • (a) MongoDB
  • (b) Cassandra
  • (c) MySQL
  • (d) Redis
[1 mark]
Q3.
Primary key:
  • (a) Can be NULL
  • (b) Must be unique and NOT NULL
  • (c) Can repeat
  • (d) Optional
[1 mark]
Q4.
Foreign key:
  • (a) Primary key of same table
  • (b) Unique key
  • (c) References PK of another table
  • (d) Any column
[1 mark]
Q5.
SQL stands for:
  • (a) Standard Query Language
  • (b) Structured Query Language
  • (c) Simple Query Language
  • (d) Sequential Query Language
[1 mark]
Q6.
Which SQL command retrieves data?
  • (a) INSERT
  • (b) UPDATE
  • (c) SELECT
  • (d) DELETE
[1 mark]
Q7.
Normalization is used to:
  • (a) Speed up queries
  • (b) Remove redundancy
  • (c) Add tables
  • (d) Delete duplicates
[1 mark]
Q8.
Which is a DDL command?
  • (a) SELECT
  • (b) INSERT
  • (c) CREATE
  • (d) UPDATE
[1 mark]
Q9.
A tuple in RDBMS is:
  • (a) A column
  • (b) A row/record
  • (c) A table
  • (d) A key
[1 mark]
Q10.
Which normal form removes partial dependencies?
  • (a) 1NF
  • (b) 2NF
  • (c) 3NF
  • (d) BCNF
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
What is ACID in databases?
[2 marks]
Q12.
What is the output of the following?
Difference between DDL and DML.
[2 marks]
Q13.
What is the output of the following?
What is a candidate key?
[2 marks]
Q14.
What is the output of the following?
Explain 1NF with example.
[2 marks]
Q15.
What is the output of the following?
What is referential integrity?
[2 marks]
Q16.
What is the output of the following?
Difference between INNER JOIN and LEFT JOIN.
[2 marks]
Q17.
What is the output of the following?
What are the 4 properties of a relation (table)?
[2 marks]
Q18.
What is the output of the following?
What is a surrogate key?
[2 marks]
Q19.
What is the output of the following?
What is a view in SQL?
[2 marks]
Q20.
What is the output of the following?
Difference between WHERE and HAVING.
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Design a database schema for a school management system.
[3 marks]
Q22.
Simulate normalization from 0NF to 3NF.
[3 marks]
Q23.
Draw entity-relationship diagram in text.
[3 marks]
Q24.
Simulate basic SQL queries in Python dict.
[3 marks]
Q25.
Implement a simple in-memory relational table.
[3 marks]
Q26.
Simulate JOIN operation between two tables.
[3 marks]
Q27.
Simulate GROUP BY and aggregate.
[3 marks]
Q28.
Validate database constraints programmatically.
[3 marks]
Q29.
Implement indexing simulation for fast lookup.
[3 marks]
Q30.
Model a many-to-many relationship.
[3 marks]
A1: (c) — DBMS: software to create, manage, and query structured databases.
A2: (c) — MySQL is a relational DBMS using SQL and tables with rows/columns.
A3: (b) — Primary key uniquely identifies each row; must be unique and not null.
A4: (c) — Foreign key: column referencing the primary key of another table.
A5: (b) — SQL = Structured Query Language — used to manage relational databases.
A6: (c) — SELECT retrieves data from one or more tables.
A7: (b) — Normalization: structuring database to reduce data redundancy.
A8: (c) — DDL (Data Definition Language): CREATE, ALTER, DROP — define structure.
A9: (b) — In RDBMS, a tuple = a row/record in a table.
A10: (b) — 2NF removes partial dependencies on composite primary keys.
A11: Atomicity: all or nothing. Consistency: valid state before/after. Isolation: concurrent transactions don't interfere. Durability: committed data persists.
A12: DDL (Data Definition Language): CREATE, ALTER, DROP — defines structure. DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE — manipulates data.
A13: A minimal set of attributes that can uniquely identify a tuple. A table may have multiple candidate keys; one is chosen as primary key.
A14: 1NF: no repeating groups, each cell has one atomic value. Bad: StudentID, Subjects="Math,Science" Good: One row per subject.
A15: Ensures foreign key values always reference a valid primary key in the parent table. Cannot insert orphan foreign key values.
A16: INNER JOIN: returns rows with matching values in both tables. LEFT JOIN: returns all rows from left table + matched rows from right (NULL if no match).
A17: 1. Each cell has one value. 2. Column values are from same domain. 3. Rows are unique. 4. Column order is insignificant.
A18: An artificial primary key (like auto-increment ID) not derived from data. Used when no natural unique identifier exists.
A19: A virtual table defined by a SELECT query. Simplifies complex queries, provides security by hiding columns, and doesn't store data.
A20: WHERE: filters rows before grouping. HAVING: filters groups after GROUP BY. Example: WHERE age>18; HAVING COUNT(*)>5
A21:
# Schema design (text description)
schema="""
Students(StudentID PK, Name, DOB, ClassID FK)
Classes(ClassID PK, ClassName, TeacherID FK)
Teachers(TeacherID PK, Name, Subject, Phone)
Subjects(SubjectID PK, SubjectName, MaxMarks)
Marks(MarkID PK, StudentID FK, SubjectID FK, MarksObtained)
"""
print(schema)
# Relationships:
print("Students → Classes: Many-to-One")
print("Classes → Teachers: Many-to-One")
print("Marks → Students, Subjects: Many-to-Many resolved")
A22:
print("0NF (Unnormalized):")
print("Order(OrderID, Customer, Items=[P1:2,P2:3])")
print("\n1NF (Atomic values):")
print("Order(OrderID, Customer, ProductID, Quantity)")
print("\n2NF (Remove partial deps - OrderID+ProductID is PK):")
print("Order(OrderID, Customer)")
print("OrderItem(OrderID FK, ProductID FK, Quantity)")
print("\n3NF (Remove transitive deps):")
print("Order(OrderID, CustomerID FK)")
print("Customer(CustomerID, CustomerName, City)")
print("OrderItem(OrderID FK, ProductID FK, Quantity)")
A23:
erd="""
[STUDENT]---(enrolled in)---[COURSE]
    |                          |
  <StudentID>              <CourseID>
  <Name>                   <CourseName>
  <DOB>                    <Credits>
    |                          |
[STUDENT] has MARKS
  [MARKS]--<StudentID FK, CourseID FK, Score>
"""
print(erd)
A24:
students=[
    {"id":1,"name":"Alice","age":16,"dept":"CS"},
    {"id":2,"name":"Bob","age":17,"dept":"Math"},
    {"id":3,"name":"Carol","age":16,"dept":"CS"},
]
# SELECT * WHERE dept="CS"
cs_students=[s for s in students if s["dept"]=="CS"]
print("CS students:",[s["name"] for s in cs_students])
# SELECT name, age ORDER BY age
sorted_s=sorted(students,key=lambda x:x["age"])
print("Sorted by age:",[s["name"] for s in sorted_s])
A25:
class Table:
    def __init__(self,name,columns):
        self.name=name
        self.columns=columns
        self.rows=[]
    def insert(self,**kwargs):
        self.rows.append({c:kwargs.get(c) for c in self.columns})
    def select(self,where=None):
        return [r for r in self.rows if where is None or where(r)]
    def display(self):
        print(f"\nTable: {self.name}")
        print(" | ".join(self.columns))
        print("-"*40)
        for r in self.rows:
            print(" | ".join(str(r[c]) for c in self.columns))
stud=Table("Students",["ID","Name","Marks"])
stud.insert(ID=1,Name="Alice",Marks=90)
stud.insert(ID=2,Name="Bob",Marks=72)
stud.insert(ID=3,Name="Carol",Marks=85)
stud.display()
print("Pass:",[r["Name"] for r in stud.select(where=lambda r:r["Marks"]>=80)])
A26:
students=[{"sid":1,"name":"Alice"},{"sid":2,"name":"Bob"},{"sid":3,"name":"Carol"}]
marks=[{"sid":1,"subject":"Math","score":90},{"sid":2,"subject":"Math","score":72},{"sid":1,"subject":"Sci","score":85}]
# INNER JOIN students ON marks.sid=students.sid
joined=[]
for m in marks:
    for s in students:
        if m["sid"]==s["sid"]:
            joined.append({**s,**m})
print("Name","Subject","Score")
for r in joined:
    print(r["name"],r["subject"],r["score"])
A27:
data=[
    {"dept":"CS","score":90},{"dept":"Math","score":85},
    {"dept":"CS","score":88},{"dept":"Math","score":72},{"dept":"CS","score":95}
]
groups={}
for r in data:
    groups.setdefault(r["dept"],[]).append(r["score"])
print("Dept | Count | Avg | Max")
for dept,scores in groups.items():
    print(f"{dept:6}|{len(scores):6}|{sum(scores)/len(scores):5.1f}|{max(scores):4}")
A28:
class PrimaryKeyError(Exception): pass
class ForeignKeyError(Exception): pass
students={}
courses={1:"Math",2:"Science",3:"English"}
def add_student(sid,name,course_id):
    if sid in students: raise PrimaryKeyError(f"Student {sid} exists")
    if course_id not in courses: raise ForeignKeyError(f"Course {course_id} not found")
    students[sid]={"name":name,"course":course_id}
for sid,name,cid in [(1,"Alice",1),(2,"Bob",5),(1,"Carol",2)]:
    try:
        add_student(sid,name,cid)
        print(f"Added: {name}")
    except (PrimaryKeyError,ForeignKeyError) as e:
        print(f"Error: {e}")
A29:
import time
records=[{"id":i,"name":f"Student{i}","score":i%100} for i in range(10000)]
# Linear search
t=time.time()
result=[r for r in records if r["id"]==9999]
linear_time=time.time()-t
# Index-based search
index={r["id"]:r for r in records}
t=time.time()
result=index.get(9999)
index_time=time.time()-t
print(f"Linear: {linear_time*1000:.3f}ms")
print(f"Index:  {index_time*1000:.3f}ms")
print(f"Speedup: {linear_time/max(index_time,0.000001):.0f}x")
A30:
students={1:"Alice",2:"Bob",3:"Carol"}
courses={101:"Python",102:"Database",103:"Networks"}
enrollments=[(1,101),(1,102),(2,102),(2,103),(3,101),(3,103)]
print("Student enrollments:")
for sid,cid in enrollments:
    print(f"  {students[sid]} → {courses[cid]}")
print("\nCourse rosters:")
for cid,cname in courses.items():
    enrolled=[students[s] for s,c in enrollments if c==cid]
    print(f"  {cname}: {enrolled}")
Unit 1 · Computational Thinking & Programming
Queue
FIFO data structure — enqueue, dequeue, peek, isEmpty using Python list and collections.deque.
8
Marks

Queue — FIFO Structure

7.1
QUEUE (FIFO — First In First Out) 10 20 35 50 FRONT[0] REAR[-1] DEQUEUE → returns 10 ENQUEUE(60) added at rear dequeue: queue.pop(0) or popleft() enqueue: queue.append(val)
Queue using List
class Queue:
  def __init__(self): self.items = []
  def enqueue(self, val):
    self.items.append(val)
  def dequeue(self):
    if not self.is_empty():
      return self.items.pop(0)
  def front(self): return self.items[0]
  def rear(self): return self.items[-1]
  def is_empty(self): return len(self.items)==0

⚠️ pop(0) is O(n) — slow for large queues.
Queue using deque (Efficient)
from collections import deque
q = deque()

q.append(val) → enqueue (rear) O(1)
q.popleft() → dequeue (front) O(1)
q[0] → peek front
q[-1] → peek rear
len(q) == 0 → is empty

deque is double-ended:
q.appendleft(val) → add to front
q.pop() → remove from rear
Queue Types
Simple Queue: FIFO — add rear, remove front
Circular Queue: rear wraps to front (no wasted space)
Priority Queue: highest priority dequeued first
Deque (Double-ended): add/remove both ends

Applications:
• Print spooling (print jobs)
• CPU scheduling (Round Robin)
• BFS (Breadth First Search)
• Call centre queues, ticket booking
• Keyboard buffer, IO buffers

🐍 Python Runner — Queue Programs

7.2
P1: Queue Class
P2: Queue with deque
P3: Queue Trace
P4: Print Queue
P5: BFS with Queue
P6: Circular Queue
P7: Priority Queue
P8: Sliding Window Max
P9: Hot Potato
P10: Round Robin
P1: Level-Order Tree
P2: BFS Shortest Path
P3: Bank Simulation
P4: BFS Maze
P5: Deque Operations
P6: Josephus Problem
P7: Non-Repeating Stream
P8: Download Queue
P9: Multi-Level Queue
P10: Binary Generation
P1: Dijkstra
P2: LRU Cache
P3: Wildfire BFS
P4: Topological Sort
P5: Rate Limiter
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • FIFO: First In, First Out — the first element enqueued is the first to be dequeued.
  • Enqueue = append() (add to rear). Dequeue = pop(0) (remove from front).
  • Use collections.deque for efficient queue: popleft() is O(1) vs list's pop(0) which is O(n).
  • Check is_empty() before dequeue to avoid IndexError (underflow).
  • Queue applications: BFS, print spooling, CPU scheduling, keyboard buffer.
  • Circular queue solves the wasted space problem of simple queue with front/rear pointers.

Topic Test: MySQL Basics

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
MySQL is a:
  • (a) NoSQL DB
  • (b) Relational DBMS
  • (c) Object DB
  • (d) File system
[1 mark]
Q2.
Which SQL command creates a table?
  • (a) MAKE TABLE
  • (b) CREATE TABLE
  • (c) ADD TABLE
  • (d) NEW TABLE
[1 mark]
Q3.
VARCHAR(50) stores:
  • (a) Exactly 50 chars
  • (b) Up to 50 chars
  • (c) 50 bytes
  • (d) 50 numbers
[1 mark]
Q4.
Which constraint ensures no duplicate values?
  • (a) NOT NULL
  • (b) PRIMARY KEY
  • (c) UNIQUE
  • (d) DEFAULT
[1 mark]
Q5.
AUTO_INCREMENT is used for:
  • (a) Dates
  • (b) Auto-increasing integer PK
  • (c) Floats
  • (d) Boolean
[1 mark]
Q6.
Which command shows all tables?
  • (a) SHOW ALL
  • (b) SHOW TABLES
  • (c) LIST TABLES
  • (d) DISPLAY TABLES
[1 mark]
Q7.
INT vs BIGINT:
  • (a) Same
  • (b) INT: 4 bytes (-2B to 2B); BIGINT: 8 bytes (±9×10¹⁸)
  • (c) BIGINT is for decimals
  • (d) INT is larger
[1 mark]
Q8.
DESCRIBE tablename shows:
  • (a) All rows
  • (b) Column definitions (name,type,constraints)
  • (c) Row count
  • (d) All databases
[1 mark]
Q9.
Which is a valid MySQL data type?
  • (a) TEXT
  • (b) STRING
  • (c) CHARACTER
  • (d) ALPHABET
[1 mark]
Q10.
DEFAULT keyword sets:
  • (a) Column constraint
  • (b) Fallback value when INSERT omits column
  • (c) Data type
  • (d) Index
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Write SQL to create a Students table.
[2 marks]
Q12.
What is the output of the following?
Write SQL to insert 3 student records.
[2 marks]
Q13.
What is the output of the following?
Write SQL to select all students with Grade A.
[2 marks]
Q14.
What is the output of the following?
How do you update a student's grade?
[2 marks]
Q15.
What is the output of the following?
Write SQL to delete a student record.
[2 marks]
Q16.
What is the output of the following?
What does DESC Students; show?
[2 marks]
Q17.
What is the output of the following?
Write SQL to add a new column Phone to Students.
[2 marks]
Q18.
What is the output of the following?
What is the output of SELECT COUNT(*) FROM Students;?
[2 marks]
Q19.
What is the output of the following?
Write SQL to find the student with highest marks.
[2 marks]
Q20.
What is the output of the following?
Difference between CHAR and VARCHAR.
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write complete SQL to create and populate a library database.
[3 marks]
Q22.
Write SQL for a student marks database with queries.
[3 marks]
Q23.
Write SQL queries using WHERE with multiple conditions.
[3 marks]
Q24.
Write SQL to use ORDER BY and LIMIT.
[3 marks]
Q25.
Write SQL to use string functions.
[3 marks]
Q26.
Write SQL for date functions.
[3 marks]
Q27.
Write SQL using aggregate functions.
[3 marks]
Q28.
Write SQL to alter and modify a table.
[3 marks]
Q29.
Write SQL for sub-queries.
[3 marks]
Q30.
Write SQL for DISTINCT and NULL handling.
[3 marks]
A1: (b) — MySQL is an open-source Relational Database Management System (RDBMS).
A2: (b) — CREATE TABLE tablename (col datatype, ...) — DDL command.
A3: (b) — VARCHAR(n): variable-length string up to n characters.
A4: (c) — UNIQUE constraint: values in the column must be distinct (no duplicates).
A5: (b) — AUTO_INCREMENT: automatically increments integer column on each insert.
A6: (b) — SHOW TABLES; — lists all tables in current database.
A7: (b) — INT: 32-bit signed; BIGINT: 64-bit signed for very large numbers.
A8: (b) — DESC tablename: shows column names, types, null settings, keys, defaults.
A9: (a) — TEXT: variable-length string up to 65,535 bytes. STRING is not a MySQL type.
A10: (b) — DEFAULT value: used when INSERT does not specify a value for that column.
A11: CREATE TABLE Students ( StudentID INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(100) NOT NULL, Age INT, Grade CHAR(1), Email VARCHAR(150) UNIQUE );
A12: INSERT INTO Students (Name, Age, Grade) VALUES ('Alice', 16, 'A'), ('Bob', 17, 'B'), ('Carol', 16, 'A');
A13: SELECT * FROM Students WHERE Grade = 'A';
A14: UPDATE Students SET Grade = 'A' WHERE StudentID = 2;
A15: DELETE FROM Students WHERE StudentID = 3;
A16: Shows table structure: column names, data types, NULL/NOT NULL, Key (PRI/UNI/MUL), Default, Extra (e.g. auto_increment).
A17: ALTER TABLE Students ADD Phone VARCHAR(15);
A18: Returns the total number of rows in the Students table.
A19: SELECT Name, MAX(Marks) FROM Students; -- or SELECT * FROM Students ORDER BY Marks DESC LIMIT 1;
A20: CHAR(n): fixed length, always stores n chars (padded with spaces). VARCHAR(n): variable length, stores only what's entered. VARCHAR is more space-efficient.
A21:
-- Create
CREATE TABLE Books (
  BookID INT PRIMARY KEY AUTO_INCREMENT,
  Title VARCHAR(200) NOT NULL,
  Author VARCHAR(100),
  Year INT,
  Price DECIMAL(8,2)
);
-- Insert
INSERT INTO Books (Title, Author, Year, Price) VALUES
("Python Basics","Gupta",2022,450.00),
("DBMS Concepts","Sharma",2021,380.50),
("Computer Networks","Tanenbaum",2020,599.00);
-- Query
SELECT * FROM Books WHERE Price < 500 ORDER BY Price;
A22:
CREATE TABLE Marks (
  MarkID INT PRIMARY KEY AUTO_INCREMENT,
  StudentName VARCHAR(100),
  Subject VARCHAR(50),
  Score INT
);
INSERT INTO Marks (StudentName,Subject,Score) VALUES
("Alice","Math",90),("Alice","Sci",85),
("Bob","Math",72),("Bob","Sci",68);
-- Average per student
SELECT StudentName, AVG(Score) AS Average FROM Marks GROUP BY StudentName;
-- Top scorer per subject
SELECT Subject, MAX(Score) AS TopScore FROM Marks GROUP BY Subject;
A23:
SELECT * FROM Students
WHERE Age >= 16 AND Grade = "A";

SELECT * FROM Products
WHERE Price BETWEEN 100 AND 500
AND Category = "Electronics";

SELECT * FROM Employees
WHERE Department IN ("CS","IT","ECE")
OR Salary > 50000;
A24:
-- Top 3 students by marks
SELECT Name, Marks FROM Students
ORDER BY Marks DESC LIMIT 3;

-- Alphabetical order
SELECT Name FROM Students ORDER BY Name ASC;

-- Second highest marks
SELECT Name, Marks FROM Students
ORDER BY Marks DESC LIMIT 1 OFFSET 1;
A25:
SELECT UPPER(Name), LOWER(Email), LENGTH(Name) FROM Students;
SELECT CONCAT(FirstName," ",LastName) AS FullName FROM Employees;
SELECT SUBSTRING(Name,1,3) AS ShortName FROM Students;
SELECT * FROM Students WHERE Name LIKE "A%"; -- starts with A
SELECT * FROM Students WHERE Name LIKE "%son"; -- ends with son
A26:
SELECT NOW(), CURDATE(), CURTIME();
SELECT Name, YEAR(DOB) AS BirthYear FROM Students;
SELECT Name, DATEDIFF(CURDATE(), JoinDate) AS DaysEnrolled FROM Students;
SELECT * FROM Orders WHERE OrderDate >= "2024-01-01"
AND OrderDate <= "2024-12-31";
A27:
SELECT COUNT(*) AS Total FROM Students;
SELECT AVG(Marks) AS Average FROM Students;
SELECT MAX(Marks) AS Highest, MIN(Marks) AS Lowest FROM Students;
SELECT SUM(Amount) AS TotalRevenue FROM Sales;
SELECT Department, COUNT(*) as Staff FROM Employees GROUP BY Department HAVING COUNT(*) > 5;
A28:
-- Add column
ALTER TABLE Students ADD COLUMN Phone VARCHAR(15);
-- Modify column type
ALTER TABLE Students MODIFY COLUMN Age TINYINT;
-- Rename column
ALTER TABLE Students CHANGE Name FullName VARCHAR(150);
-- Drop column
ALTER TABLE Students DROP COLUMN Phone;
-- Rename table
ALTER TABLE Students RENAME TO Learners;
A29:
-- Students with marks above average
SELECT Name, Marks FROM Students
WHERE Marks > (SELECT AVG(Marks) FROM Students);
-- Students in the top 10%
SELECT Name FROM Students
WHERE Marks >= (SELECT MAX(Marks)*0.9 FROM Students);
-- Students not in any club
SELECT Name FROM Students
WHERE StudentID NOT IN (SELECT StudentID FROM ClubMembers);
A30:
-- Unique grades
SELECT DISTINCT Grade FROM Students;
-- Count non-null emails
SELECT COUNT(Email) FROM Students;  -- NULLs not counted
-- Replace NULLs
SELECT Name, IFNULL(Phone,"Not provided") AS Phone FROM Students;
-- Find rows with NULL
SELECT Name FROM Students WHERE Email IS NULL;
SELECT Name FROM Students WHERE Email IS NOT NULL;
Unit 1 · Computational Thinking & Programming
Sorting Algorithms
Bubble Sort, Selection Sort, Insertion Sort — algorithm traces, time complexity analysis, and CBSE exam patterns.
12
Marks

Sorting — Algorithm Comparison

8.1
Bubble Sort: [5, 3, 8, 1] — Pass 1 5 3 8 1 5>3 → swap 3 5 8 1 5<8 ok 3 5 8 1 8>1 → swap After Pass 1: [3, 5, 1, 8] ← 8 is in place Algorithm Complexity Summary Algorithm Best Case Average Case Worst Case Space Stable? Bubble Sort O(n) O(n²) O(n²) O(1) ✓ Yes Selection Sort O(n²) O(n²) O(n²) O(1) ✗ No Insertion Sort O(n) O(n²) O(n²) O(1) ✓ Yes O(n)=already sorted input (best), O(n²)=reverse sorted (worst). All three are in-place (O(1) space).
Bubble Sort
Compare adjacent pairs; swap if out of order.
Largest element "bubbles up" to end each pass.

def bubble_sort(arr):
  n = len(arr)
  for i in range(n-1):
    for j in range(n-i-1):
      if arr[j] > arr[j+1]:
        arr[j], arr[j+1] = arr[j+1], arr[j]

Passes needed: n−1. Comparisons: n−1, n−2, … 1.
Selection Sort
Find minimum in unsorted part; swap to front.
After pass i, first i elements are sorted.

def selection_sort(arr):
  n = len(arr)
  for i in range(n-1):
    min_idx = i
    for j in range(i+1, n):
      if arr[j] < arr[min_idx]:
        min_idx = j
    arr[i], arr[min_idx] = arr[min_idx], arr[i]
Insertion Sort
Pick next element; insert into correct position in sorted part.
Like sorting playing cards in hand.

def insertion_sort(arr):
  for i in range(1, len(arr)):
    key = arr[i]
    j = i - 1
    while j >= 0 and arr[j] > key:
      arr[j+1] = arr[j]
      j -= 1
    arr[j+1] = key

🐍 Python Runner — Sorting Programs

8.2
P1: Bubble Sort Trace
P2: Selection Sort
P3: Insertion Sort
P4: CBSE Trace Format
P5: Sort Strings
P6: Sort Student Records
P7: Sort Visualiser
P8: Sort Comparison
P9: Descending Sort
P10: Kth Element
P1: Merge Sort
P2: Quick Sort
P3: Counting Sort
P4: Optimised Bubble
P5: Radix Sort
P6: Stability Demo
P7: Sort Linked List
P8: Sort Matrix Rows
P9: External Sort
P10: Shell Sort
P1: TimSort
P2: Benchmark
P3: Patience Sort
P4: Parallel Merge Sort
P5: Adaptive Sort
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • Bubble Sort: Compare adjacent pairs, swap if out of order. After pass i, last i elements are sorted.
  • Selection Sort: Find minimum in unsorted portion, swap to position i. After pass i, first i elements sorted.
  • Insertion Sort: Pick element, shift larger elements right, insert in correct position. Best for nearly-sorted data.
  • All three have O(n²) average/worst time complexity and O(1) space complexity.
  • Bubble and Insertion are stable (equal elements keep original order). Selection is not stable.
  • Bubble Sort best case is O(n) with early exit flag when no swaps occur in a pass.

Topic Test: SQL DDL & DML

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which is a DDL command?
  • (a) INSERT
  • (b) SELECT
  • (c) ALTER
  • (d) UPDATE
[1 mark]
Q2.
TRUNCATE TABLE vs DELETE FROM:
  • (a) Same
  • (b) TRUNCATE: removes all rows faster, no rollback; DELETE: can have WHERE, rollback
  • (c) DELETE is faster
  • (d) TRUNCATE keeps rows
[1 mark]
Q3.
DROP TABLE removes:
  • (a) All rows only
  • (b) All rows and table structure
  • (c) Only columns
  • (d) Table from another DB
[1 mark]
Q4.
COMMIT in SQL:
  • (a) Cancels transaction
  • (b) Saves all changes permanently
  • (c) Drops table
  • (d) Starts transaction
[1 mark]
Q5.
Which constraint checks a condition?
  • (a) NOT NULL
  • (b) UNIQUE
  • (c) CHECK
  • (d) FOREIGN KEY
[1 mark]
Q6.
ROLLBACK undoes:
  • (a) Committed transactions
  • (b) Uncommitted changes in current transaction
  • (c) All table data
  • (d) Indexes
[1 mark]
Q7.
ON DELETE CASCADE means:
  • (a) Prevent delete if child exists
  • (b) Delete child rows when parent is deleted
  • (c) Set child to NULL
  • (d) Error on delete
[1 mark]
Q8.
Which DML retrieves data?
  • (a) INSERT
  • (b) UPDATE
  • (c) SELECT
  • (d) DELETE
[1 mark]
Q9.
SAVEPOINT is used to:
  • (a) End transaction
  • (b) Create a rollback point within transaction
  • (c) Commit part
  • (d) Delete rows
[1 mark]
Q10.
GRANT command belongs to:
  • (a) DDL
  • (b) DML
  • (c) DCL
  • (d) TCL
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Write DDL to create Products table with constraints.
[2 marks]
Q12.
What is the output of the following?
What does ALTER TABLE ... MODIFY do?
[2 marks]
Q13.
What is the output of the following?
Write SQL to add UNIQUE constraint to existing column.
[2 marks]
Q14.
What is the output of the following?
Difference between DROP TABLE and TRUNCATE TABLE.
[2 marks]
Q15.
What is the output of the following?
What is a transaction? Give its properties.
[2 marks]
Q16.
What is the output of the following?
Write a transaction with SAVEPOINT.
[2 marks]
Q17.
What is the output of the following?
What is ON DELETE SET NULL vs ON DELETE CASCADE?
[2 marks]
Q18.
What is the output of the following?
Write SQL to grant and revoke privileges.
[2 marks]
Q19.
What is the output of the following?
What does DESCRIBE (or DESC) show?
[2 marks]
Q20.
What is the output of the following?
Difference between WHERE and HAVING with GROUP BY.
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write complete DDL for a hospital database.
[3 marks]
Q22.
Write DML to insert, update, delete records.
[3 marks]
Q23.
Write SQL with multiple JOIN types.
[3 marks]
Q24.
Write a transaction for bank transfer.
[3 marks]
Q25.
Write SQL with GROUP BY and aggregate functions.
[3 marks]
Q26.
Create a view and query it.
[3 marks]
Q27.
Write SQL to use indexes.
[3 marks]
Q28.
Write SQL with subqueries.
[3 marks]
Q29.
Write SQL for CHECK, DEFAULT, and NOT NULL constraints.
[3 marks]
Q30.
Write SQL to backup and restore concepts.
[3 marks]
A1: (c) — DDL: CREATE, ALTER, DROP, TRUNCATE. ALTER modifies table structure.
A2: (b) — TRUNCATE: DDL — deletes all rows, auto-committed. DELETE: DML — can use WHERE, can rollback.
A3: (b) — DROP TABLE removes the entire table (structure + data + indexes).
A4: (b) — COMMIT: permanently saves all changes made in the current transaction.
A5: (c) — CHECK constraint: ensures column values satisfy a specified condition (e.g., age>0).
A6: (b) — ROLLBACK: undoes all changes since the last COMMIT or savepoint.
A7: (b) — ON DELETE CASCADE: deleting a parent row automatically deletes all child rows.
A8: (c) — DML commands: SELECT (query), INSERT, UPDATE, DELETE.
A9: (b) — SAVEPOINT name: creates a point in transaction you can roll back to.
A10: (c) — DCL (Data Control Language): GRANT and REVOKE — manage user permissions.
A11: CREATE TABLE Products ( ProductID INT PRIMARY KEY AUTO_INCREMENT, ProductName VARCHAR(100) NOT NULL, Price DECIMAL(10,2) CHECK(Price > 0), Stock INT DEFAULT 0, CategoryID INT, FOREIGN KEY (CategoryID) REFERENCES Categories(CategoryID) ON DELETE CASCADE );
A12: Changes a column's data type or constraints. Example: ALTER TABLE Students MODIFY Age TINYINT NOT NULL;
A13: ALTER TABLE Students ADD CONSTRAINT uq_email UNIQUE (Email);
A14: DROP TABLE: removes table structure and data completely. TRUNCATE TABLE: removes all data but keeps the table structure.
A15: A transaction is a group of SQL operations that execute as a unit. Properties: ACID (Atomicity, Consistency, Isolation, Durability).
A16: START TRANSACTION; INSERT INTO Accounts VALUES(1,"Alice",5000); SAVEPOINT sp1; UPDATE Accounts SET Balance=Balance-500 WHERE ID=1; ROLLBACK TO sp1; -- undo the UPDATE only COMMIT;
A17: SET NULL: sets FK column to NULL when parent is deleted. CASCADE: deletes child rows when parent is deleted.
A18: GRANT SELECT, INSERT ON Students TO 'teacher'@'localhost'; REVOKE INSERT ON Students FROM 'teacher'@'localhost';
A19: Shows: column name, data type, NULL/NOT NULL, Key (PRI/UNI/MUL), Default value, Extra (auto_increment).
A20: WHERE: filters individual rows BEFORE grouping. HAVING: filters groups AFTER GROUP BY. Example: SELECT Dept, AVG(Sal) FROM Emp GROUP BY Dept HAVING AVG(Sal) > 50000;
A21:
-- Patients table
CREATE TABLE Patients (
  PatientID INT PRIMARY KEY AUTO_INCREMENT,
  Name VARCHAR(100) NOT NULL,
  DOB DATE,
  Gender CHAR(1) CHECK(Gender IN ("M","F","O")),
  Phone VARCHAR(15)
);
-- Doctors table
CREATE TABLE Doctors (
  DoctorID INT PRIMARY KEY AUTO_INCREMENT,
  Name VARCHAR(100) NOT NULL,
  Specialty VARCHAR(50),
  Phone VARCHAR(15)
);
-- Appointments table
CREATE TABLE Appointments (
  AppID INT PRIMARY KEY AUTO_INCREMENT,
  PatientID INT,
  DoctorID INT,
  AppDate DATETIME,
  FOREIGN KEY (PatientID) REFERENCES Patients(PatientID) ON DELETE CASCADE,
  FOREIGN KEY (DoctorID) REFERENCES Doctors(DoctorID)
);
A22:
-- Insert
INSERT INTO Patients (Name,DOB,Gender,Phone)
VALUES ("Alice Sharma","2008-06-15","F","9876543210");
-- Insert multiple
INSERT INTO Patients (Name,DOB,Gender) VALUES
("Bob Roy","2007-03-20","M"),
("Carol Das","2008-11-05","F");
-- Update
UPDATE Patients SET Phone="8765432109" WHERE Name="Bob Roy";
-- Delete
DELETE FROM Patients WHERE PatientID = 3;
-- View changes
SELECT * FROM Patients;
A23:
-- INNER JOIN
SELECT S.Name, M.Subject, M.Score
FROM Students S
INNER JOIN Marks M ON S.StudentID = M.StudentID;
-- LEFT JOIN
SELECT S.Name, M.Score
FROM Students S
LEFT JOIN Marks M ON S.StudentID = M.StudentID;
-- RIGHT JOIN
SELECT S.Name, M.Subject
FROM Students S
RIGHT JOIN Marks M ON S.StudentID = M.StudentID;
A24:
START TRANSACTION;
-- Debit sender
UPDATE Accounts SET Balance = Balance - 5000
WHERE AccountNo = "ACC001";
-- Credit receiver
UPDATE Accounts SET Balance = Balance + 5000
WHERE AccountNo = "ACC002";
-- Check balance
SELECT AccountNo, Balance FROM Accounts
WHERE AccountNo IN ("ACC001","ACC002");
-- If OK
COMMIT;
-- If error
-- ROLLBACK;
A25:
SELECT Department,
    COUNT(*) AS HeadCount,
    AVG(Salary) AS AvgSalary,
    MAX(Salary) AS MaxSal,
    MIN(Salary) AS MinSal
FROM Employees
GROUP BY Department
HAVING COUNT(*) >= 3
ORDER BY AvgSalary DESC;
A26:
CREATE VIEW TopStudents AS
SELECT Name, Marks, Grade
FROM Students
WHERE Marks >= 80;
-- Query the view
SELECT * FROM TopStudents ORDER BY Marks DESC;
-- With additional filter
SELECT Name FROM TopStudents WHERE Grade = "A";
-- Drop view
DROP VIEW TopStudents;
A27:
-- Create index
CREATE INDEX idx_name ON Students(Name);
-- Create unique index
CREATE UNIQUE INDEX idx_email ON Students(Email);
-- Composite index
CREATE INDEX idx_dept_sal ON Employees(Department, Salary);
-- Show indexes
SHOW INDEX FROM Students;
-- Drop index
DROP INDEX idx_name ON Students;
A28:
-- Correlated subquery: students scoring above class average
SELECT Name, Marks
FROM Students s
WHERE Marks > (
  SELECT AVG(Marks) FROM Students WHERE Class = s.Class
);
-- IN subquery
SELECT Name FROM Students
WHERE StudentID IN (
  SELECT StudentID FROM Marks WHERE Score > 90
);
-- EXISTS
SELECT Name FROM Students s
WHERE EXISTS (
  SELECT 1 FROM Marks m WHERE m.StudentID = s.StudentID AND m.Score > 85
);
A29:
CREATE TABLE Employee (
  EmpID INT PRIMARY KEY AUTO_INCREMENT,
  Name VARCHAR(100) NOT NULL,
  Age INT CHECK(Age BETWEEN 18 AND 65),
  Salary DECIMAL(10,2) DEFAULT 25000.00 CHECK(Salary > 0),
  Department VARCHAR(50) NOT NULL DEFAULT "General",
  Email VARCHAR(150) UNIQUE,
  JoinDate DATE DEFAULT (CURDATE())
);
A30:
-- Creating a backup table
CREATE TABLE Students_Backup AS SELECT * FROM Students;
-- Restore: insert from backup
INSERT INTO Students SELECT * FROM Students_Backup
WHERE StudentID NOT IN (SELECT StudentID FROM Students);
-- Archive old records
CREATE TABLE Marks_Archive AS
SELECT * FROM Marks WHERE Year < 2022;
DELETE FROM Marks WHERE Year < 2022;
Unit 1 · Computational Thinking & Programming
Searching Algorithms
Linear Search (O(n)) and Binary Search (O(log n)) — algorithm traces, comparison, and applications.
8
Marks

Linear vs Binary Search

9.1
Linear Search: target=7 in [2, 5, 9, 7, 3, 1] Checks each element left to right until found 2 5 9 7 ✓ 3 1 [0]✗ [1]✗ [2]✗ [3]✓ Binary Search: target=7 in [1, 2, 3, 5, 7, 9] (MUST be sorted) 1 2 3 5←mid 7 ✓ 9 Step 1: mid=2 → arr[2]=3 < 7 → search right half Step 2: mid=4 → arr[4]=7 = target → Found at index 4! Comparison Linear: O(n) Binary: O(log n) Linear: works unsorted Binary: needs sorted n=1000: Linear≤1000 steps, Binary≤10 steps
Linear Search
Sequentially checks each element until found or end of list.

def linear_search(arr, target):
  for i, val in enumerate(arr):
    if val == target:
      return i
  return -1

Best: O(1) — found at index 0.
Average: O(n/2) = O(n)
Worst: O(n) — not found or at end.
Works on unsorted lists.
Binary Search
Divides sorted list in half each step.

def binary_search(arr, target):
  low, high = 0, len(arr)-1
  while low <= high:
    mid = (low + high) // 2
    if arr[mid] == target: return mid
    elif arr[mid] < target: low = mid+1
    else: high = mid-1
  return -1

All cases: O(log n). Requires sorted list.
When to Use Which?
Use Linear Search when:
• List is unsorted (or rarely searched)
• List is very small (n < 10)
• Searching linked lists
• First/last occurrence needed

Use Binary Search when:
• List is already sorted
• Large lists (n > 100)
• Repeated searches on same data
• Finding insertion points (bisect)

For n=1,000,000: Linear up to 1M steps, Binary up to only 20 steps.

🐍 Python Runner — Searching Programs

9.2
P1: Linear Search Trace
P2: Binary Search Trace
P3: All Occurrences
P4: Recursive Binary Search
P5: Search 2D Matrix
P6: Search Records
P7: Bisect Module
P8: Comparison Count
P9: Sentinel Search
P10: Rotated Array Search
P1: Interpolation Search
P2: Exponential Search
P3: Jump Search
P4: Ternary Search
P5: Fibonacci Search
P6: Binary Search on Answer
P7: Infinite Array Search
P8: Find Peak Element
P9: Count Occurrences
P10: Fuzzy Search
P1: KMP Search
P2: Rabin-Karp
P3: Matrix Search
P4: Suffix Array
P5: Trie Auto-complete
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • Linear Search: Check each element. Works on unsorted lists. O(n) worst case.
  • Binary Search: Divide in half each step. Needs sorted list. O(log n) all cases.
  • Binary search key formula: mid = (low + high) // 2
  • Binary search loop condition: while low <= high. Returns -1 when not found.
  • For n=1024: Linear may take 1024 steps; Binary takes at most log₂(1024) = 10 steps.
  • CBSE exam: Show low, high, mid at each step of binary search with the array state.

Topic Test: SQL Aggregate Functions

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which aggregate ignores NULL?
  • (a) COUNT(*)
  • (b) COUNT(col)
  • (c) Both same
  • (d) Neither
[1 mark]
Q2.
AVG(Marks) calculates:
  • (a) Highest mark
  • (b) Sum of marks
  • (c) Sum divided by count (ignoring NULLs)
  • (d) Median
[1 mark]
Q3.
GROUP BY groups rows by:
  • (a) Distinct column values
  • (b) Row number
  • (c) Primary key
  • (d) Table name
[1 mark]
Q4.
HAVING is used instead of WHERE because:
  • (a) WHERE is slower
  • (b) WHERE cannot filter aggregate results
  • (c) HAVING is shorter
  • (d) No difference
[1 mark]
Q5.
Which returns the total of a column?
  • (a) COUNT
  • (b) MAX
  • (c) SUM
  • (d) AVG
[1 mark]
Q6.
SELECT MAX(Salary) FROM Emp; returns:
  • (a) Highest salary row
  • (b) Just the highest salary value
  • (c) All salaries sorted
  • (d) Error
[1 mark]
Q7.
Which function counts distinct values?
  • (a) COUNT(*)
  • (b) COUNT(DISTINCT col)
  • (c) SUM(DISTINCT col)
  • (d) AVG(DISTINCT col)
[1 mark]
Q8.
GROUP_CONCAT (MySQL) does:
  • (a) Groups rows
  • (b) Concatenates grouped values into a string
  • (c) Counts groups
  • (d) Sums strings
[1 mark]
Q9.
Rollup in GROUP BY:
  • (a) Filters groups
  • (b) Adds subtotals and grand total
  • (c) Sorts groups
  • (d) Removes NULLs
[1 mark]
Q10.
Which is NOT an aggregate function?
  • (a) SUM
  • (b) AVG
  • (c) UPPER
  • (d) COUNT
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Write SQL: count students per grade.
[2 marks]
Q12.
What is the output of the following?
Write SQL: average marks by subject.
[2 marks]
Q13.
What is the output of the following?
Write SQL: find departments with more than 5 employees.
[2 marks]
Q14.
What is the output of the following?
Write SQL: total sales per month.
[2 marks]
Q15.
What is the output of the following?
Write SQL: find the second highest salary.
[2 marks]
Q16.
What is the output of the following?
Write SQL: count distinct cities in a table.
[2 marks]
Q17.
What is the output of the following?
Write SQL: show percentage of total for each dept.
[2 marks]
Q18.
What is the output of the following?
Write SQL: grades with average > 80.
[2 marks]
Q19.
What is the output of the following?
Write SQL: MIN and MAX per subject.
[2 marks]
Q20.
What is the output of the following?
Write SQL using GROUP_CONCAT.
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Simulate SQL aggregates in Python.
[3 marks]
Q22.
Write SQL queries for a sales analysis.
[3 marks]
Q23.
HAVING vs WHERE — demonstrate the difference.
[3 marks]
Q24.
Write SQL to rank students using variables.
[3 marks]
Q25.
Write SQL for WITH ROLLUP.
[3 marks]
Q26.
Simulate COUNT DISTINCT in Python.
[3 marks]
Q27.
Write SQL for cumulative sum.
[3 marks]
Q28.
Calculate grade distribution.
[3 marks]
Q29.
Write SQL for pivot-like query using CASE.
[3 marks]
Q30.
Write SQL: top N per group.
[3 marks]
A1: (b) — COUNT(col) ignores NULLs; COUNT(*) counts all rows including NULLs.
A2: (c) — AVG: sum of non-NULL values divided by count of non-NULL values.
A3: (a) — GROUP BY aggregates rows with the same value in specified column(s).
A4: (b) — HAVING filters after aggregation; WHERE filters rows before grouping.
A5: (c) — SUM(col) adds all non-NULL numeric values in the column.
A6: (b) — MAX() returns the maximum value as a scalar — not the whole row.
A7: (b) — COUNT(DISTINCT col): counts unique non-NULL values in the column.
A8: (b) — GROUP_CONCAT: joins column values from a group into a comma-separated string.
A9: (b) — WITH ROLLUP: adds summary rows (subtotals + grand total) after each GROUP BY level.
A10: (c) — UPPER() is a string function, not an aggregate. Aggregates: SUM, AVG, COUNT, MIN, MAX.
A11: SELECT Grade, COUNT(*) AS Count FROM Students GROUP BY Grade ORDER BY Grade;
A12: SELECT Subject, AVG(Score) AS Average FROM Marks GROUP BY Subject;
A13: SELECT Department, COUNT(*) AS Staff FROM Employees GROUP BY Department HAVING COUNT(*) > 5;
A14: SELECT MONTH(SaleDate) AS Month, SUM(Amount) AS Total FROM Sales GROUP BY MONTH(SaleDate) ORDER BY Month;
A15: SELECT MAX(Salary) FROM Employees WHERE Salary < (SELECT MAX(Salary) FROM Employees);
A16: SELECT COUNT(DISTINCT City) AS UniqueCities FROM Students;
A17: SELECT Dept, SUM(Sales) AS DeptSales, ROUND(SUM(Sales)*100/(SELECT SUM(Sales) FROM SalesTable),2) AS Pct FROM SalesTable GROUP BY Dept;
A18: SELECT Grade, AVG(Marks) AS Avg FROM Students GROUP BY Grade HAVING AVG(Marks) > 80;
A19: SELECT Subject, MIN(Score) AS Lowest, MAX(Score) AS Highest FROM Marks GROUP BY Subject;
A20: SELECT Class, GROUP_CONCAT(Name ORDER BY Name SEPARATOR ', ') AS Students FROM Students GROUP BY Class;
A21:
data=[
  {"name":"Alice","dept":"CS","salary":50000},
  {"name":"Bob","dept":"Math","salary":45000},
  {"name":"Carol","dept":"CS","salary":60000},
  {"name":"Dave","dept":"Math","salary":55000},
]
from collections import defaultdict
groups=defaultdict(list)
for r in data: groups[r["dept"]].append(r["salary"])
print("Dept | Count | Avg | Max")
for dept,salaries in groups.items():
  print(f"{dept:8}|{len(salaries):6}|{sum(salaries)/len(salaries):7.0f}|{max(salaries):4}")
A22:
SELECT ProductName, SUM(Quantity*Price) AS Revenue
FROM OrderItems GROUP BY ProductName ORDER BY Revenue DESC LIMIT 5;
-- Monthly trend
SELECT YEAR(OrderDate) AS Yr, MONTH(OrderDate) AS Mo, SUM(Amount) AS Total
FROM Orders GROUP BY Yr, Mo ORDER BY Yr, Mo;
A23:
-- WHERE: filter before grouping
SELECT Dept, AVG(Salary) FROM Emp WHERE Salary > 20000 GROUP BY Dept;
-- HAVING: filter after grouping
SELECT Dept, AVG(Salary) AS Avg FROM Emp GROUP BY Dept HAVING AVG(Salary) > 40000;
-- Combined: both WHERE and HAVING
SELECT Dept, COUNT(*) AS Staff, AVG(Salary) AS AvgSal
FROM Emp WHERE JoinYear >= 2020
GROUP BY Dept HAVING COUNT(*) >= 3 ORDER BY AvgSal DESC;
A24:
SET @rank = 0;
SELECT @rank := @rank+1 AS Rank, Name, Marks
FROM Students ORDER BY Marks DESC;
-- OR with RANK() window function (MySQL 8+)
SELECT Name, Marks, RANK() OVER (ORDER BY Marks DESC) AS Rank
FROM Students;
A25:
SELECT COALESCE(Department,"ALL") AS Dept,
  COALESCE(Job,"ALL JOBS") AS Job,
  SUM(Salary) AS TotalSal
FROM Employees
GROUP BY Department, Job WITH ROLLUP;
A26:
data=[{"city":"Delhi"},{"city":"Mumbai"},{"city":"Delhi"},
  {"city":"Chennai"},{"city":"Mumbai"},{"city":"Delhi"}]
total=len(data)
unique_cities=len(set(r["city"] for r in data))
print(f"Total rows: {total}")
print(f"Distinct cities: {unique_cities}")
from collections import Counter
for city,count in Counter(r["city"] for r in data).most_common():
  print(f"  {city}: {count}")
A27:
-- MySQL 8+ window function
SELECT Month, Sales,
  SUM(Sales) OVER (ORDER BY Month) AS CumulativeSales
FROM MonthlySales;
-- MySQL 5.7 simulation with variable
SET @cum = 0;
SELECT Month, Sales, (@cum := @cum + Sales) AS CumulativeSales
FROM MonthlySales ORDER BY Month;
A28:
marks={"Alice":92,"Bob":75,"Carol":88,"Dave":55,"Eve":60,"Frank":45}
buckets={"A (>=80)":0,"B (60-79)":0,"C (<60)":0}
for m in marks.values():
  if m>=80: buckets["A (>=80)"]+=1
  elif m>=60: buckets["B (60-79)"]+=1
  else: buckets["C (<60)"]+=1
total=len(marks)
for grade,count in buckets.items():
  bar="#"*count
  print(f"{grade}: {bar} ({count}, {count/total*100:.0f}%)")
A29:
SELECT StudentID,
  SUM(CASE WHEN Subject="Math" THEN Score ELSE 0 END) AS Math,
  SUM(CASE WHEN Subject="Science" THEN Score ELSE 0 END) AS Science,
  SUM(CASE WHEN Subject="English" THEN Score ELSE 0 END) AS English
FROM Marks GROUP BY StudentID;
A30:
-- Top 2 scorers per class (MySQL 8+)
SELECT Name, Class, Marks FROM (
  SELECT Name, Class, Marks,
    ROW_NUMBER() OVER (PARTITION BY Class ORDER BY Marks DESC) AS rn
  FROM Students
) ranked WHERE rn <= 2;
Unit 2 · Computer Networks
Network Fundamentals
Types of networks, topologies, network devices — essential concepts for CBSE board examination.
10
Marks

Network Types

10.1
PAN Phone ~10 metres LAN Switch/Hub School/Office up to ~1 km MAN LAN 1 LAN 2 City-wide up to ~50 km WAN Asia Europe USA Worldwide Internet = WAN

Network Topologies

10.2
Bus Single backbone Easy to install Failure=network down Star HUB Central hub/switch Easy fault detection Hub failure=all down Ring Token passing Equal access Break=all fail Mesh Every node connected High reliability Expensive
Network Devices
Hub: Broadcasts to all ports. Layer 1. Shared bandwidth.
Switch: Forwards to specific port using MAC address. Layer 2. Dedicated bandwidth. More intelligent than hub.
Router: Connects different networks. Uses IP address. Layer 3. WAN connectivity.
Modem: Modulate/demodulate — converts digital↔analog for telephone/cable lines.
Gateway: Connects networks with different protocols. Acts as entry/exit point.
Repeater: Amplifies/regenerates signal to extend range.
Transmission Media
Guided (Wired):
• Twisted Pair (UTP/STP): cheapest, most common. Up to 100 Mbps.
• Coaxial Cable: better shielding. Used in cable TV.
• Optical Fibre: light pulses. Fastest (Gbps). Immune to EMI. Most expensive.

Unguided (Wireless):
• Radio waves (WiFi, Bluetooth)
• Microwave (point-to-point, satellite)
• Infrared (TV remote, short range)
Exam Key Points
LAN — Local Area Network (room/building, private)
MAN — Metropolitan Area Network (city-wide)
WAN — Wide Area Network (country/world, Internet)
PAN — Personal Area Network (Bluetooth, ~10m)

Star topology is the most commonly used in offices.
Bus topology uses terminators at each end.
Mesh: Full mesh = n(n-1)/2 links for n nodes.
Bandwidth = data transfer rate (bps, Mbps, Gbps).
Latency = delay in data transmission.
📌 Remember for Exam
  • Network: A group of computers connected to share resources and data.
  • LAN vs WAN: LAN=private/local, WAN=public/global. MAN=city-level.
  • Star topology is most popular — easy to add/remove nodes, easy troubleshooting.
  • Bus topology — needs terminators at both ends; backbone failure stops entire network.
  • Switch > Hub — Switch sends to specific device (unicast), Hub broadcasts to all.
  • Router connects different networks using IP addresses; Switch connects same network using MAC addresses.

Topic Test: SQL Joins

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
INNER JOIN returns:
  • (a) All rows from both tables
  • (b) Only matching rows from both tables
  • (c) All left + matching right
  • (d) All right + matching left
[1 mark]
Q2.
LEFT JOIN returns:
  • (a) Only matching rows
  • (b) All left rows + matching right (NULL for non-matches)
  • (c) All right rows
  • (d) Cartesian product
[1 mark]
Q3.
Which join returns all rows from both tables?
  • (a) INNER
  • (b) LEFT
  • (c) RIGHT
  • (d) FULL OUTER
[1 mark]
Q4.
Cartesian product is produced by:
  • (a) INNER JOIN
  • (b) NATURAL JOIN
  • (c) CROSS JOIN
  • (d) LEFT JOIN
[1 mark]
Q5.
Self-join joins:
  • (a) Different tables
  • (b) Same table with alias
  • (c) Related tables
  • (d) Foreign keys
[1 mark]
Q6.
NATURAL JOIN joins on:
  • (a) All columns
  • (b) Columns with same name and type
  • (c) Primary keys only
  • (d) Foreign keys only
[1 mark]
Q7.
To avoid duplicates in NATURAL JOIN vs USING:
  • (a) Use DISTINCT
  • (b) Use USING(col) to specify join column
  • (c) Use WHERE
  • (d) Use HAVING
[1 mark]
Q8.
Which shows employees with no manager?
  • (a) INNER JOIN
  • (b) LEFT JOIN with WHERE manager IS NULL
  • (c) CROSS JOIN
  • (d) RIGHT JOIN
[1 mark]
Q9.
Equi-join uses:
  • (a) <, > operators
  • (b) = operator
  • (c) LIKE
  • (d) BETWEEN
[1 mark]
Q10.
JOIN without ON is equivalent to:
  • (a) INNER JOIN
  • (b) LEFT JOIN
  • (c) CROSS JOIN
  • (d) NATURAL JOIN
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Write INNER JOIN: students with their marks.
[2 marks]
Q12.
What is the output of the following?
Write LEFT JOIN: all students even without marks.
[2 marks]
Q13.
What is the output of the following?
Write SELF JOIN: find employee and their manager.
[2 marks]
Q14.
What is the output of the following?
Write query to find students with no marks.
[2 marks]
Q15.
What is the output of the following?
Write a 3-table join.
[2 marks]
Q16.
What is the output of the following?
CROSS JOIN: how many rows from 5×3 tables?
[2 marks]
Q17.
What is the output of the following?
Write FULL OUTER JOIN in MySQL (simulation).
[2 marks]
Q18.
What is the output of the following?
Write query: common students in two classes.
[2 marks]
Q19.
What is the output of the following?
Write JOIN with aggregate.
[2 marks]
Q20.
What is the output of the following?
Difference between ON and WHERE in a LEFT JOIN.
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Simulate INNER JOIN in Python.
[3 marks]
Q22.
Simulate LEFT JOIN in Python.
[3 marks]
Q23.
Write SQL to find common records between two tables (INTERSECT simulation).
[3 marks]
Q24.
Write SQL for a complex multi-table join (school DB).
[3 marks]
Q25.
Write SQL: students who enrolled in all courses.
[3 marks]
Q26.
Write SQL to find pairs of students with same score.
[3 marks]
Q27.
Simulate CROSS JOIN and use case.
[3 marks]
Q28.
Write SQL: department average vs company average.
[3 marks]
Q29.
Write SQL: chain of supervisors (recursive).
[3 marks]
Q30.
Write SQL: report card with multiple subjects joined.
[3 marks]
A1: (b) — INNER JOIN returns rows that have matching values in both tables.
A2: (b) — LEFT JOIN keeps all rows from the left table; non-matching right columns are NULL.
A3: (d) — FULL OUTER JOIN: all rows from both tables; NULL where no match.
A4: (c) — CROSS JOIN: every row from table A × every row from table B (m×n rows).
A5: (b) — Self-join: a table joined to itself using aliases to represent different roles.
A6: (b) — NATURAL JOIN: automatically joins on all columns with identical names.
A7: (b) — USING(col): join on one named column, avoids duplicate column in result.
A8: (b) — LEFT JOIN employee to itself on manager_id; WHERE manager_id IS NULL.
A9: (b) — Equi-join: join condition uses the equality operator (=).
A10: (c) — JOIN without ON or WHERE produces the Cartesian product, like CROSS JOIN.
A11: SELECT S.Name, M.Subject, M.Score FROM Students S INNER JOIN Marks M ON S.StudentID = M.StudentID;
A12: SELECT S.Name, IFNULL(M.Score, "No marks") AS Score FROM Students S LEFT JOIN Marks M ON S.StudentID = M.StudentID;
A13: SELECT E.Name AS Employee, M.Name AS Manager FROM Employees E LEFT JOIN Employees M ON E.ManagerID = M.EmpID;
A14: SELECT S.Name FROM Students S LEFT JOIN Marks M ON S.StudentID = M.StudentID WHERE M.StudentID IS NULL;
A15: SELECT S.Name, C.CourseName, M.Score FROM Students S JOIN Enrollments E ON S.StudentID = E.StudentID JOIN Courses C ON E.CourseID = C.CourseID JOIN Marks M ON S.StudentID = M.StudentID AND M.CourseID = C.CourseID;
A16: 15 rows — every row from table 1 combined with every row from table 2.
A17: SELECT * FROM A LEFT JOIN B ON A.id=B.id UNION SELECT * FROM A RIGHT JOIN B ON A.id=B.id;
A18: SELECT Name FROM Class11 WHERE Name IN (SELECT Name FROM Class12);
A19: SELECT S.Name, COUNT(M.Subject) AS Subjects, AVG(M.Score) AS Avg FROM Students S JOIN Marks M ON S.StudentID = M.StudentID GROUP BY S.StudentID, S.Name HAVING AVG(M.Score) >= 70;
A20: ON: join condition evaluated during join (keeps all left rows). WHERE after LEFT JOIN: filters post-join, converts to INNER JOIN if right col checked. Use ON for join conditions, WHERE for filtering.
A21:
students=[{"sid":1,"name":"Alice"},{"sid":2,"name":"Bob"},{"sid":3,"name":"Carol"}]
marks=[{"sid":1,"subject":"Math","score":90},{"sid":2,"subject":"Math","score":72}]
result=[{**s,**m} for s in students for m in marks if s["sid"]==m["sid"]]
for r in result:
  print(r["name"],r["subject"],r["score"])
A22:
students=[{"sid":1,"name":"Alice"},{"sid":2,"name":"Bob"},{"sid":3,"name":"Carol"}]
marks=[{"sid":1,"score":90},{"sid":2,"score":72}]
marks_dict={m["sid"]:m["score"] for m in marks}
for s in students:
  score=marks_dict.get(s["sid"],"No marks")
  print(f"{s['name']}: {score}")
A23:
-- MySQL has no INTERSECT; use INNER JOIN or IN
SELECT DISTINCT A.Name FROM TableA A
INNER JOIN TableB B ON A.Name = B.Name;
-- OR
SELECT Name FROM TableA
WHERE Name IN (SELECT Name FROM TableB);
A24:
SELECT S.Name, T.Name AS Teacher, C.CourseName, M.Score
FROM Students S
JOIN Enrollments E ON S.StudentID = E.StudentID
JOIN Courses C ON E.CourseID = C.CourseID
JOIN Teachers T ON C.TeacherID = T.TeacherID
JOIN Marks M ON S.StudentID = M.StudentID
  AND M.CourseID = C.CourseID
WHERE M.Score >= 60
ORDER BY S.Name, C.CourseName;
A25:
SELECT S.Name FROM Students S
WHERE NOT EXISTS (
  SELECT C.CourseID FROM Courses C
  WHERE NOT EXISTS (
    SELECT 1 FROM Enrollments E
    WHERE E.StudentID = S.StudentID
      AND E.CourseID = C.CourseID
  )
);
A26:
SELECT A.Name AS Student1, B.Name AS Student2, A.Score
FROM Marks A
JOIN Marks B ON A.Score = B.Score
  AND A.StudentID < B.StudentID
  AND A.Subject = B.Subject
ORDER BY A.Score DESC;
A27:
sizes=["S","M","L","XL"]
colors=["Red","Blue","Green"]
combinations=[(s,c) for s in sizes for c in colors]
print(f"Total combinations: {len(combinations)}")
for combo in combinations[:6]:
  print(combo)
A28:
SELECT D.DeptName, AVG(E.Salary) AS DeptAvg,
  (SELECT AVG(Salary) FROM Employees) AS CompanyAvg,
  AVG(E.Salary) - (SELECT AVG(Salary) FROM Employees) AS Difference
FROM Employees E
JOIN Departments D ON E.DeptID = D.DeptID
GROUP BY D.DeptID, D.DeptName ORDER BY DeptAvg DESC;
A29:
-- MySQL 8+ CTE (Common Table Expression)
WITH RECURSIVE ManagerChain AS (
  SELECT EmpID, Name, ManagerID, 0 AS Level
  FROM Employees WHERE EmpID = 5
  UNION ALL
  SELECT E.EmpID, E.Name, E.ManagerID, MC.Level+1
  FROM Employees E
  JOIN ManagerChain MC ON E.EmpID = MC.ManagerID
)
SELECT Level, Name FROM ManagerChain ORDER BY Level;
A30:
SELECT S.Name,
  MAX(CASE WHEN M.Subject="Math" THEN M.Score END) AS Math,
  MAX(CASE WHEN M.Subject="Science" THEN M.Score END) AS Science,
  MAX(CASE WHEN M.Subject="English" THEN M.Score END) AS English,
  AVG(M.Score) AS Overall
FROM Students S
LEFT JOIN Marks M ON S.StudentID = M.StudentID
GROUP BY S.StudentID, S.Name;
Unit 2 · Computer Networks
Data Communication
Components, transmission modes, switching techniques — how data travels across networks.
8
Marks

Transmission Modes

11.1
Simplex Sender Receiver One direction only e.g. TV, Radio Half Duplex Device A Device B Both directions but NOT simultaneously e.g. Walkie-Talkie Full Duplex Device A Device B Simultaneously both directions e.g. Telephone, Internet Switching Techniques Circuit Switching Dedicated path (e.g. PSTN) Message Switching Store-and-forward whole message Packet Switching Data split into packets (Internet)
Components of Data Communication
Sender: Device that sends data (computer, phone).
Receiver: Device that receives data.
Message: The data/information being communicated.
Transmission Medium: Physical path (wire, fibre, air).
Protocol: Set of rules governing communication (TCP/IP, HTTP).

All five must be present for successful communication.
Bandwidth & Speed
Bandwidth: Maximum data capacity of a medium (bps).
Bit Rate: Actual number of bits transmitted per second.
Baud Rate: Number of signal changes per second.

Units:
• 1 Kbps = 1,000 bps
• 1 Mbps = 1,000,000 bps
• 1 Gbps = 1,000,000,000 bps

Latency: Time delay from sender to receiver (in ms).
Throughput: Actual data transferred per second (may be less than bandwidth due to errors/overhead).
Serial vs Parallel Transmission
Serial: One bit at a time over single wire.
 • Slower but cheaper; used over long distances.
 • USB, SATA, network cables.

Parallel: Multiple bits simultaneously over multiple wires.
 • Faster but expensive, short distances only.
 • Older printers (LPT port), internal buses.

Synchronous: Data flows continuously with clock sync.
Asynchronous: Data sent in blocks with start/stop bits.
📌 Remember for Exam
  • 5 components: Sender, Receiver, Message, Transmission Medium, Protocol.
  • Simplex: TV broadcast. Half-duplex: Walkie-talkie. Full-duplex: Telephone call.
  • Packet Switching is used by the Internet — data split into packets, each may take a different route.
  • Circuit Switching — dedicated path established before transmission (traditional telephone).
  • Optical fibre uses light pulses, immune to electromagnetic interference.
  • Bandwidth ≠ Speed. Bandwidth is capacity; actual speed (throughput) can be less.

Topic Test: Python-MySQL Connectivity

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which module connects Python to MySQL?
  • (a) pymysql
  • (b) mysql
  • (c) connector
  • (d) dbconn
[1 mark]
Q2.
What does cursor.fetchone() return?
  • (a) All rows
  • (b) First row as tuple
  • (c) Row count
  • (d) Column names
[1 mark]
Q3.
Which method executes a SQL query?
  • (a) cursor.run()
  • (b) cursor.query()
  • (c) cursor.execute()
  • (d) cursor.sql()
[1 mark]
Q4.
What does connection.commit() do?
  • (a) Close connection
  • (b) Send query
  • (c) Save DML changes permanently
  • (d) Rollback
[1 mark]
Q5.
Parameterized queries use ___ to prevent SQL injection.
  • (a) f-strings
  • (b) str.format()
  • (c) %s placeholders
  • (d) String concatenation
[1 mark]
Q6.
fetchall() returns:
  • (a) One row
  • (b) Last row
  • (c) List of all remaining rows
  • (d) Row count
[1 mark]
Q7.
What is a cursor in DB context?
  • (a) Mouse cursor
  • (b) Object for executing SQL and navigating results
  • (c) Database connection
  • (d) SQL file
[1 mark]
Q8.
SQL injection is caused by:
  • (a) Slow queries
  • (b) Unsanitised user input in SQL strings
  • (c) Too many rows
  • (d) Wrong datatype
[1 mark]
Q9.
cursor.rowcount after UPDATE gives:
  • (a) Columns updated
  • (b) Rows affected
  • (c) Table size
  • (d) 0
[1 mark]
Q10.
Which is correct connection code?
  • (a) mysql.open()
  • (b) mysql.connector.connect(host=...,user=...,password=...,database=...)
  • (c) mysql.login()
  • (d) connector.start()
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Write Python code to connect to MySQL.
[2 marks]
Q12.
What is the output of the following?
Write code to fetch and display all students.
[2 marks]
Q13.
What is the output of the following?
Write code to insert a student record.
[2 marks]
Q14.
What is the output of the following?
Write safe UPDATE with parameterized query.
[2 marks]
Q15.
What is the output of the following?
What does cursor.description contain?
[2 marks]
Q16.
What is the output of the following?
Write DELETE with parameter.
[2 marks]
Q17.
What is the output of the following?
How to get column names from cursor?
[2 marks]
Q18.
What is the output of the following?
What is the danger of string formatting in SQL?
[2 marks]
Q19.
What is the output of the following?
Write code to fetch one row.
[2 marks]
Q20.
What is the output of the following?
Write proper connection close code.
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Complete Python-MySQL CRUD application.
[3 marks]
Q22.
Safe search with LIKE and parameter.
[3 marks]
Q23.
Transaction: transfer marks between records.
[3 marks]
Q24.
Display results as formatted table.
[3 marks]
Q25.
Bulk insert using executemany.
[3 marks]
Q26.
Generate report from DB and write to CSV.
[3 marks]
Q27.
Context manager for MySQL connection.
[3 marks]
Q28.
Parameterized stored procedure call.
[3 marks]
Q29.
Fetch data and plot with matplotlib (simulate).
[3 marks]
Q30.
Handle connection errors gracefully.
[3 marks]
A1: (a) — mysql-connector-python (or PyMySQL) provides the Python-MySQL interface.
A2: (b) — fetchone(): returns the next row as a tuple (or None if no more rows).
A3: (c) — cursor.execute(sql, params): sends the SQL to MySQL for execution.
A4: (b) — commit(): finalises INSERT/UPDATE/DELETE changes so they persist.
A5: (c) — cursor.execute(sql, (val,)): %s placeholders with a values tuple prevent injection.
A6: (c) — fetchall(): returns all remaining rows as a list of tuples.
A7: (b) — Cursor: an object via which SQL is executed and results fetched.
A8: (b) — SQL injection: attacker inserts SQL code via user input if not sanitised.
A9: (b) — rowcount: number of rows affected by the last DML statement.
A10: (b) — mysql.connector.connect(**params) creates the connection object.
A11: import mysql.connector conn = mysql.connector.connect( host="localhost", user="root", password="pass", database="school" ) cursor = conn.cursor() print("Connected:", conn.is_connected())
A12: cursor.execute("SELECT * FROM Students") rows = cursor.fetchall() for row in rows: print(row)
A13: sql = "INSERT INTO Students (Name,Age) VALUES (%s,%s)" cursor.execute(sql, ('Alice', 16)) conn.commit() print('Rows inserted:', cursor.rowcount)
A14: sql = "UPDATE Students SET Grade=%s WHERE StudentID=%s" cursor.execute(sql, ('A', 3)) conn.commit()
A15: A sequence of 7-item tuples describing result columns: (name, type_code, display_size, internal_size, precision, scale, null_ok)
A16: cursor.execute("DELETE FROM Students WHERE StudentID=%s", (5,)) conn.commit() print('Deleted:', cursor.rowcount)
A17: cursor.execute('SELECT * FROM Students LIMIT 0') cols = [d[0] for d in cursor.description] print(cols)
A18: f"SELECT * FROM Users WHERE name='{name}'" — if name = "' OR 1=1 --" the query returns ALL users. Use %s params instead.
A19: cursor.execute("SELECT * FROM Students WHERE StudentID=%s", (1,)) row = cursor.fetchone() print(row)
A20: cursor.close() conn.close() # Or use try/finally to ensure close even on error
A21:
import mysql.connector

conn=mysql.connector.connect(host="localhost",user="root",password="",database="school")
cur=conn.cursor()

def create(name,age):
    cur.execute("INSERT INTO Students(Name,Age) VALUES(%s,%s)",(name,age))
    conn.commit(); return cur.lastrowid

def read_all():
    cur.execute("SELECT * FROM Students")
    return cur.fetchall()

def update(sid,name):
    cur.execute("UPDATE Students SET Name=%s WHERE StudentID=%s",(name,sid))
    conn.commit()

def delete(sid):
    cur.execute("DELETE FROM Students WHERE StudentID=%s",(sid,))
    conn.commit()

create("Alice",16); create("Bob",17)
print("All:", read_all())
update(1,"Alicia")
delete(2)
print("After:", read_all())
cur.close(); conn.close()
A22:
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",password="",database="school")
cur=conn.cursor()
search=input("Search name: ")
cur.execute("SELECT * FROM Students WHERE Name LIKE %s",("%"+search+"%",))
for row in cur.fetchall():
    print(row)
cur.close(); conn.close()
A23:
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",password="",database="school")
cur=conn.cursor()
try:
    cur.execute("UPDATE Accounts SET Balance=Balance-500 WHERE ID=1")
    cur.execute("UPDATE Accounts SET Balance=Balance+500 WHERE ID=2")
    conn.commit()
    print("Transfer complete")
except Exception as e:
    conn.rollback()
    print("Error, rolled back:",e)
finally:
    cur.close(); conn.close()
A24:
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",password="",database="school")
cur=conn.cursor()
cur.execute("SELECT * FROM Students LIMIT 5")
cols=[d[0] for d in cur.description]
rows=cur.fetchall()
widths=[max(len(str(r[i])) for r in rows+[cols]) for i in range(len(cols))]
header=" | ".join(c.ljust(widths[i]) for i,c in enumerate(cols))
print(header)
print("-"*len(header))
for row in rows:
    print(" | ".join(str(v).ljust(widths[i]) for i,v in enumerate(row)))
cur.close(); conn.close()
A25:
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",password="",database="school")
cur=conn.cursor()
students=[("Alice",16,"A"),("Bob",17,"B"),("Carol",16,"A")]
cur.executemany("INSERT INTO Students(Name,Age,Grade) VALUES(%s,%s,%s)",students)
conn.commit()
print(f"Inserted {cur.rowcount} rows")
cur.close(); conn.close()
A26:
import mysql.connector, csv
conn=mysql.connector.connect(host="localhost",user="root",password="",database="school")
cur=conn.cursor()
cur.execute("SELECT Name, AVG(Score) AS Avg FROM Students JOIN Marks USING(StudentID) GROUP BY StudentID")
cols=[d[0] for d in cur.description]
rows=cur.fetchall()
with open("report.csv","w",newline="") as f:
    w=csv.writer(f)
    w.writerow(cols)
    w.writerows(rows)
print(f"Wrote {len(rows)} rows to report.csv")
cur.close(); conn.close()
A27:
import mysql.connector
from contextlib import contextmanager

@contextmanager
def get_db():
    conn=mysql.connector.connect(host="localhost",user="root",password="",database="school")
    cur=conn.cursor()
    try:
        yield cur
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        cur.close(); conn.close()

with get_db() as cur:
    cur.execute("SELECT COUNT(*) FROM Students")
    print("Student count:",cur.fetchone()[0])
A28:
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",password="",database="school")
cur=conn.cursor()
# Call stored procedure
cur.callproc("GetStudentReport",(1,))
for result in cur.stored_results():
    for row in result.fetchall():
        print(row)
cur.close(); conn.close()
A29:
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",password="",database="school")
cur=conn.cursor()
cur.execute("SELECT Subject, AVG(Score) FROM Marks GROUP BY Subject")
data=cur.fetchall()
subjects=[r[0] for r in data]
avgs=[r[1] for r in data]
print("Subject Averages:")
for s,a in zip(subjects,avgs):
    bar="#"*int(a/5)
    print(f"{s:15} {bar} {a:.1f}")
cur.close(); conn.close()
A30:
import mysql.connector
from mysql.connector import Error

def connect_db(host,user,pwd,db):
    try:
        conn=mysql.connector.connect(host=host,user=user,password=pwd,database=db)
        if conn.is_connected():
            info=conn.get_server_info()
            print(f"Connected to MySQL {info}")
            return conn
    except Error as e:
        print(f"Connection failed: {e}")
        return None

conn=connect_db("localhost","root","","school")
if conn:
    try:
        cur=conn.cursor()
        cur.execute("SELECT DATABASE()")
        print("DB:",cur.fetchone()[0])
    finally:
        conn.close()
Unit 2 · Computer Networks
Protocols & Internet
TCP/IP, HTTP, FTP, DNS, SMTP, POP3 — how the Internet works and web technologies.
10
Marks

TCP/IP Protocol Stack

12.1
TCP/IP Model (4 Layers) Application Layer Transport Layer Internet Layer Network Access Layer Protocols HTTP, HTTPS, FTP, SMTP, POP3, DNS, DHCP TCP (reliable, connection-oriented) UDP (fast, connectionless) IP — Routing & Addressing ICMP (error reporting, ping) Ethernet, WiFi, PPP
Important Protocols
HTTP — HyperText Transfer Protocol (web browsing). Port 80.
HTTPS — HTTP Secure (encrypted). Port 443.
FTP — File Transfer Protocol. Upload/download files. Port 21.
SMTP — Simple Mail Transfer Protocol. Send email. Port 25.
POP3 — Post Office Protocol v3. Receive email. Port 110.
IMAP — Internet Message Access Protocol. Email sync. Port 143.
DNS — Domain Name System. Translates domain → IP.
DHCP — Dynamic Host Configuration Protocol. Auto-assigns IP.
TCP — Reliable, connection-oriented (handshake).
UDP — Unreliable, fast, connectionless (video streaming).
IP Addressing
IPv4: 32-bit address. 192.168.1.1 format (4 octets).
Range: 0.0.0.0 to 255.255.255.255 (~4 billion addresses).

IPv6: 128-bit address. Solves IPv4 exhaustion.
Format: 2001:0db8:85a3:0000:0000:8a2e:0370:7334

Private IP ranges (not routable on Internet):
• 10.0.0.0 – 10.255.255.255
• 172.16.0.0 – 172.31.255.255
• 192.168.0.0 – 192.168.255.255

MAC Address: 48-bit hardware address (e.g. AA:BB:CC:DD:EE:FF).
Web Technologies
URL: Uniform Resource Locator — address of a web resource.
  https://www.cbsemock.in/class12/cs
  [protocol][domain][path]

Domain Name: Human-readable IP address alias. DNS resolves it.
Web Server: Stores and serves web pages (Apache, Nginx).
Web Browser: Client software to view web pages (Chrome).
HTML: HyperText Markup Language — web page structure.
WWW: World Wide Web — system of hyperlinked pages over Internet.

Internet ≠ WWW. Internet is the infrastructure; WWW is a service on it.
📌 Remember for Exam
  • DNS translates domain names (www.google.com) to IP addresses — "phonebook of the Internet".
  • TCP vs UDP: TCP=reliable delivery with acknowledgement; UDP=fast, no guarantee (used for streaming/gaming).
  • HTTP vs HTTPS: HTTPS uses SSL/TLS encryption — look for padlock in browser.
  • SMTP sends email; POP3/IMAP receives email — "SMTP = Send Mail To People".
  • IPv4 has ~4 billion addresses; running out → IPv6 has 2¹²⁸ addresses.
  • URL parts: protocol://domain:port/path?query#fragment

Topic Test: Networking Concepts

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which topology connects all devices to a central hub?
  • (a) Bus
  • (b) Ring
  • (c) Star
  • (d) Mesh
[1 mark]
Q2.
IP address 192.168.x.x belongs to:
  • (a) Class A
  • (b) Class B
  • (c) Class C
  • (d) Class D
[1 mark]
Q3.
DNS translates:
  • (a) IP to MAC
  • (b) Domain names to IP addresses
  • (c) HTTP to HTTPS
  • (d) URLs to paths
[1 mark]
Q4.
Which protocol sends email?
  • (a) HTTP
  • (b) FTP
  • (c) SMTP
  • (d) POP3
[1 mark]
Q5.
HTTP operates at which OSI layer?
  • (a) Physical
  • (b) Data Link
  • (c) Transport
  • (d) Application
[1 mark]
Q6.
Which device connects different networks?
  • (a) Hub
  • (b) Switch
  • (c) Router
  • (d) Repeater
[1 mark]
Q7.
TCP vs UDP:
  • (a) Same
  • (b) TCP: reliable, connection-oriented; UDP: fast, connectionless
  • (c) UDP is reliable
  • (d) TCP is faster
[1 mark]
Q8.
What is bandwidth?
  • (a) Signal strength
  • (b) Maximum data transfer rate of a channel
  • (c) Network delay
  • (d) IP range
[1 mark]
Q9.
VPN stands for:
  • (a) Virtual Public Network
  • (b) Very Private Node
  • (c) Virtual Private Network
  • (d) Verified Public Node
[1 mark]
Q10.
What is a subnet mask?
  • (a) IP address type
  • (b) Divides IP into network and host portions
  • (c) Password
  • (d) Router IP
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
What is the OSI model and its layers?
[2 marks]
Q12.
What is the output of the following?
Difference between LAN, MAN and WAN.
[2 marks]
Q13.
What is the output of the following?
What is the full form and use of HTTPS?
[2 marks]
Q14.
What is the output of the following?
What is MAC address?
[2 marks]
Q15.
What is the output of the following?
Explain the TCP 3-way handshake.
[2 marks]
Q16.
What is the output of the following?
What is an IP address? Differentiate IPv4 and IPv6.
[2 marks]
Q17.
What is the output of the following?
What are the functions of a router?
[2 marks]
Q18.
What is the output of the following?
What is the difference between a hub and a switch?
[2 marks]
Q19.
What is the output of the following?
Explain FTP and its use.
[2 marks]
Q20.
What is the output of the following?
What is latency/ping?
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write Python code to get IP address of host.
[3 marks]
Q22.
Write Python TCP server-client simulation.
[3 marks]
Q23.
Simulate subnet calculation.
[3 marks]
Q24.
Write Python to check network connectivity.
[3 marks]
Q25.
Demonstrate HTTP request in Python.
[3 marks]
Q26.
Simulate ARP table (IP to MAC mapping).
[3 marks]
Q27.
Implement a simple port scanner.
[3 marks]
Q28.
Calculate IP class and range.
[3 marks]
Q29.
Network topology comparison.
[3 marks]
Q30.
Simulate DNS resolution process.
[3 marks]
A1: (c) — Star topology: all devices connect to a central hub/switch.
A2: (c) — 192.168.x.x: Class C private address range (192.0.0.0 – 223.255.255.255).
A3: (b) — DNS (Domain Name System): converts human-readable hostnames to IP addresses.
A4: (c) — SMTP (Simple Mail Transfer Protocol): sends outgoing email.
A5: (d) — HTTP is an Application layer protocol (Layer 7 of OSI).
A6: (c) — Router: connects different networks and routes packets between them.
A7: (b) — TCP ensures delivery and order; UDP is faster but no delivery guarantee.
A8: (b) — Bandwidth: maximum capacity of a network channel (e.g., 100 Mbps).
A9: (c) — VPN: Virtual Private Network — encrypted tunnel over a public network.
A10: (b) — Subnet mask: used with AND operation on IP to separate network/host parts.
A11: OSI = Open Systems Interconnection (7 layers): 7. Application (HTTP, DNS, SMTP) 6. Presentation (SSL, encryption) 5. Session (session setup) 4. Transport (TCP, UDP) 3. Network (IP, routing) 2. Data Link (MAC, Ethernet) 1. Physical (cables, bits)
A12: LAN: Local Area Network — single building/campus (e.g., school lab). MAN: Metropolitan Area Network — city-wide. WAN: Wide Area Network — country/world (Internet is a WAN).
A13: Hypertext Transfer Protocol Secure. Uses TLS/SSL to encrypt HTTP. Data between browser and server is encrypted, preventing eavesdropping.
A14: Media Access Control address: 48-bit hardware address burned into NIC. Format: AA:BB:CC:DD:EE:FF. Unique per NIC globally. Used at Data Link layer.
A15: 1. Client → Server: SYN (I want to connect) 2. Server → Client: SYN-ACK (OK, I acknowledge) 3. Client → Server: ACK (Connection established) Now data can flow reliably.
A16: IP address: unique identifier for a device on a network. IPv4: 32-bit (4 octets), ~4 billion addresses (192.168.1.1) IPv6: 128-bit (8 hex groups), ~3.4×10³⁸ addresses (2001:db8::1)
A17: 1. Routes packets between different networks. 2. Determines best path using routing tables. 3. Assigns IP via DHCP. 4. Provides NAT (Network Address Translation). 5. Firewall functionality.
A18: Hub: broadcasts to all ports (dumb), half-duplex, causes collisions. Switch: sends to specific port using MAC table (smart), full-duplex, no collisions. Switches are preferred.
A19: File Transfer Protocol: used to transfer files between client and server. Port 21. Uses two channels: control (commands) and data. Active vs passive modes. SFTP adds SSH encryption.
A20: Latency: time delay for a packet to travel from source to destination. Ping: tool that measures round-trip time to a host using ICMP echo requests. Lower ping = faster connection.
A21:
import socket
# Get local hostname and IP
hostname=socket.gethostname()
ip=socket.gethostbyname(hostname)
print(f"Hostname: {hostname}")
print(f"IP Address: {ip}")
# Resolve domain name
print(f"google.com IP: {socket.gethostbyname("google.com")}")
A22:
# Server (run first in real scenario)
import socket
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(("localhost",9999))
server.listen(1)
print("Server waiting...")
conn,addr=server.accept()
data=conn.recv(1024).decode()
print(f"Received: {data}")
conn.send("Hello client!".encode())
conn.close()

# Client
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(("localhost",9999))
client.send("Hello server!".encode())
response=client.recv(1024).decode()
print(f"Response: {response}")
client.close()
A23:
def subnet_info(ip, mask):
    ip_parts=[int(x) for x in ip.split(".")]
    mask_parts=[int(x) for x in mask.split(".")]
    network=[ip_parts[i]&mask_parts[i] for i in range(4)]
    wildcard=[255-mask_parts[i] for i in range(4)]
    broadcast=[network[i]|wildcard[i] for i in range(4)]
    hosts=(wildcard[3]+1)*(wildcard[2]+1)-2
    print(f"IP: {ip}")
    print(f"Subnet: {mask}")
    print(f"Network: {'.'.join(map(str,network))}")
    print(f"Broadcast: {'.'.join(map(str,broadcast))}")
    print(f"Usable hosts: {hosts}")
subnet_info("192.168.1.100","255.255.255.0")
A24:
import subprocess, platform
def ping(host):
    param="-n" if platform.system()=="Windows" else "-c"
    cmd=["ping",param,"1",host]
    result=subprocess.run(cmd,capture_output=True,text=True,timeout=5)
    return result.returncode==0
hosts=["google.com","github.com","localhost","nonexistent.xyz"]
for h in hosts:
    try:
        status="✓ Online" if ping(h) else "✗ Offline"
    except Exception as e:
        status=f"Error: {e}"
    print(f"{h:25} {status}")
A25:
import urllib.request
try:
    url="http://httpbin.org/get"
    req=urllib.request.urlopen(url,timeout=5)
    print("Status:",req.status)
    print("Content-Type:",req.headers.get("Content-Type"))
    data=req.read(200).decode()
    print("Data:",data[:100])
except Exception as e:
    print(f"Request failed: {e}")
    print("(Network may not be available in this environment)")
A26:
arp_table={
    "192.168.1.1":"AA:BB:CC:00:00:01",
    "192.168.1.2":"AA:BB:CC:00:00:02",
    "192.168.1.3":"AA:BB:CC:00:00:03",
}
def arp_lookup(ip):
    return arp_table.get(ip,"Unknown")
for ip in ["192.168.1.1","192.168.1.5"]:
    print(f"{ip} -> {arp_lookup(ip)}")
A27:
import socket
def scan_port(host,port,timeout=0.5):
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.settimeout(timeout)
    try:
        s.connect((host,port))
        return True
    except: return False
    finally: s.close()
common_ports={80:"HTTP",443:"HTTPS",22:"SSH",21:"FTP",25:"SMTP"}
host="localhost"
for port,service in common_ports.items():
    status="OPEN" if scan_port(host,port) else "closed"
    print(f"{service:8} port {port:5}: {status}")
A28:
def ip_class(ip):
    first=int(ip.split(".")[0])
    if 1<=first<=126: return "A", "1.0.0.0","126.255.255.255","255.0.0.0"
    elif 128<=first<=191: return "B","128.0.0.0","191.255.255.255","255.255.0.0"
    elif 192<=first<=223: return "C","192.0.0.0","223.255.255.255","255.255.255.0"
    elif 224<=first<=239: return "D","Multicast","-","-"
    else: return "E","Reserved","-","-"
for ip in ["10.0.0.1","172.16.0.1","192.168.1.1"]:
    cls,start,end,mask=ip_class(ip)
    print(f"{ip} → Class {cls} | Default mask: {mask}")
A29:
topologies={
    "Bus":{"pros":["Easy to install","Cheap"],"cons":["Single point of failure","Limited length"]},
    "Star":{"pros":["Easy to troubleshoot","No single point of failure"],"cons":["Hub failure affects all","More cable"]},
    "Ring":{"pros":["Equal access","Predictable performance"],"cons":["Single break stops network","Adding device disrupts"]},
    "Mesh":{"pros":["High redundancy","Very reliable"],"cons":["Expensive","Complex cabling"]},
}
for topo,info in topologies.items():
    print(f"\n{topo} Topology:")
    print(f"  Pros: {info['pros']}")
    print(f"  Cons: {info['cons']}")
A30:
dns_cache={
    "google.com":"142.250.195.46",
    "github.com":"140.82.114.4",
    "localhost":"127.0.0.1",
}
def dns_resolve(domain):
    if domain in dns_cache:
        print(f"Cache hit: {domain} → {dns_cache[domain]}")
        return dns_cache[domain]
    print(f"Cache miss: querying root DNS for {domain}...")
    try:
        import socket
        ip=socket.gethostbyname(domain)
        dns_cache[domain]=ip
        print(f"Resolved: {domain} → {ip}")
        return ip
    except Exception:
        print(f"DNS lookup failed for {domain}")
for d in ["google.com","localhost","example.org"]:
    dns_resolve(d)
Unit 2 · Computer Networks
Network Security
Threats, malware, firewalls, encryption, cookies — staying safe online.
8
Marks

Security Threats & Defences

13.1
🔴 Threats Malware: • Virus: attaches to programs, spreads • Worm: self-replicates over network • Trojan: disguised as legitimate software • Ransomware: encrypts data, demands payment • Spyware: silently monitors activity Attacks: • Phishing: fake emails/sites to steal credentials • DoS/DDoS: flood server with requests • Man-in-the-Middle: intercept communication 🟢 Defences Firewall: Monitors and filters network traffic (in/out) Blocks unauthorised access; hardware or software Encryption: • Symmetric: same key to encrypt/decrypt (AES) • Asymmetric: public/private key pair (RSA) • SSL/TLS: HTTPS — encrypts web traffic Other: • Antivirus software (scan/remove malware) • Strong passwords, 2FA, regular backups FIREWALL
Cookies & Privacy
Cookies: Small text files stored by browser to remember user info (login, preferences, shopping cart).

Session Cookie: Deleted when browser closes.
Persistent Cookie: Stored until expiry date.
Third-party Cookie: Set by external sites (ads) — privacy concern.

Hackers use cookies to: Session hijacking (stealing session tokens to impersonate user).

Protect yourself: Clear cookies regularly, use private browsing, HTTPS sites only.
Hacking Terminology
Hacker: Person who gains unauthorised access to systems.
Cracker: Hacker with malicious intent.
Ethical Hacker / White Hat: Hired to find vulnerabilities.
Black Hat: Malicious hacker.
Grey Hat: In between — finds vulns without permission but reports them.

Keylogger: Records keystrokes to steal passwords.
Brute Force: Tries all possible password combinations.
SQL Injection: Inserts malicious SQL into web forms.
Safe Practices
Strong Password: 12+ chars, mix of upper/lower/numbers/symbols. Unique per site.
Two-Factor Authentication (2FA): Password + OTP/biometric.
Software Updates: Patches fix security vulnerabilities.
Backup: 3-2-1 rule — 3 copies, 2 media types, 1 offsite.
VPN: Virtual Private Network — encrypts all internet traffic.
Public WiFi risks: Avoid banking/sensitive work on open WiFi.
HTTPS: Always check for padlock before entering credentials.
📌 Remember for Exam
  • Virus attaches to files; Worm self-replicates; Trojan disguises itself; Ransomware encrypts & demands money.
  • Phishing uses fake emails/websites to trick users into revealing passwords.
  • Firewall can be hardware (router-based) or software (Windows Defender Firewall).
  • Encryption: Symmetric uses same key; Asymmetric uses public/private key pair.
  • SSL/TLS provides HTTPS — the padlock in the browser indicates encrypted connection.
  • CBSE favourite: "Differentiate between virus and worm" — Virus needs host file; worm is self-contained.

Topic Test: Cyber Security

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Phishing is:
  • (a) Malware type
  • (b) Fake emails/sites to steal credentials
  • (c) DDoS attack
  • (d) SQL injection
[1 mark]
Q2.
DDoS stands for:
  • (a) Disk Denial of Service
  • (b) Distributed Denial of Service
  • (c) Data Denial of Service
  • (d) Double Denial of Service
[1 mark]
Q3.
Which protects against unauthorized access?
  • (a) Antivirus
  • (b) Firewall
  • (c) VPN
  • (d) Router
[1 mark]
Q4.
Ransomware:
  • (a) Tracks keystrokes
  • (b) Encrypts files and demands payment
  • (c) Steals passwords
  • (d) Slows computer
[1 mark]
Q5.
HTTPS uses which port?
  • (a) 80
  • (b) 8080
  • (c) 443
  • (d) 21
[1 mark]
Q6.
Two-factor authentication uses:
  • (a) Password only
  • (b) Two passwords
  • (c) Password + another factor (OTP/biometric)
  • (d) Biometric only
[1 mark]
Q7.
Which is NOT a cyber threat?
  • (a) Malware
  • (b) Phishing
  • (c) Encryption
  • (d) Man-in-the-middle
[1 mark]
Q8.
SQL Injection exploits:
  • (a) Weak passwords
  • (b) Unsanitised database queries
  • (c) Outdated antivirus
  • (d) Open ports
[1 mark]
Q9.
A keylogger records:
  • (a) Network traffic
  • (b) Keystrokes typed by user
  • (c) Screen images
  • (d) File accesses
[1 mark]
Q10.
Strong password should have:
  • (a) Only letters
  • (b) Only numbers
  • (c) Mix of uppercase, lowercase, numbers, symbols, 8+ chars
  • (d) Easy to remember words
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
What is malware? Name 5 types.
[2 marks]
Q12.
What is the output of the following?
What is the CIA triad in cyber security?
[2 marks]
Q13.
What is the output of the following?
What is a firewall and its types?
[2 marks]
Q14.
What is the output of the following?
Explain social engineering.
[2 marks]
Q15.
What is the output of the following?
What is encryption and how does it protect data?
[2 marks]
Q16.
What is the output of the following?
What is a VPN and how does it work?
[2 marks]
Q17.
What is the output of the following?
Explain man-in-the-middle attack.
[2 marks]
Q18.
What is the output of the following?
What is a digital certificate?
[2 marks]
Q19.
What is the output of the following?
What is zero-day vulnerability?
[2 marks]
Q20.
What is the output of the following?
What is the principle of least privilege?
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Implement Caesar cipher encryption/decryption.
[3 marks]
Q22.
Implement password strength checker.
[3 marks]
Q23.
Implement a hash-based password storage.
[3 marks]
Q24.
Simulate SQL injection attack and prevention.
[3 marks]
Q25.
Implement simple port scanner as security check.
[3 marks]
Q26.
Implement XOR encryption.
[3 marks]
Q27.
Simulate phishing email detector.
[3 marks]
Q28.
Implement rate limiting to prevent brute force.
[3 marks]
Q29.
Demonstrate HTTPS vs HTTP security.
[3 marks]
Q30.
Build a simple network intrusion detection system.
[3 marks]
A1: (b) — Phishing: fraudulent messages disguised as legitimate to steal credentials.
A2: (b) — DDoS: Distributed Denial of Service — flood servers with traffic from many sources.
A3: (b) — Firewall: monitors/controls network traffic based on security rules.
A4: (b) — Ransomware: malware that encrypts victim files and demands ransom for decryption.
A5: (c) — HTTPS uses port 443. HTTP uses port 80.
A6: (c) — 2FA: combines two different authentication factors (what you know + what you have/are).
A7: (c) — Encryption is a security protection, not a threat. Others are attack vectors.
A8: (b) — SQL Injection: inserting malicious SQL via input fields to manipulate the database.
A9: (b) — Keylogger: malware/software that records every keystroke, capturing passwords/PINs.
A10: (c) — Strong password: 8+ chars, mixed case, digits, special characters, no dictionary words.
A11: Malware = Malicious Software: 1. Virus: attaches to files, spreads when opened 2. Worm: self-replicates over networks 3. Trojan: disguised as legitimate software 4. Ransomware: encrypts files for ransom 5. Spyware: secretly collects user data
A12: CIA Triad: - Confidentiality: only authorised users access data - Integrity: data is accurate and unaltered - Availability: systems are accessible when needed All three must be maintained for secure systems.
A13: Firewall: monitors and controls network traffic using rules. Types: 1. Packet filtering: checks IP/port headers 2. Stateful: tracks connection state 3. Application layer: deep packet inspection (WAF) 4. Hardware vs Software firewalls
A14: Social engineering: manipulating people to reveal confidential information or perform actions. Examples: phishing, pretexting, baiting, quid pro quo. Target: human psychology, not technical systems.
A15: Encryption: converts plaintext to unreadable ciphertext using a key. Symmetric: same key for encrypt/decrypt (AES) Asymmetric: public key encrypts, private key decrypts (RSA) Protects data in transit (HTTPS) and at rest.
A16: VPN (Virtual Private Network): creates an encrypted tunnel between client and VPN server. 1. Data encrypted on device 2. Sent to VPN server 3. Forwarded to destination 4. Response returns through tunnel Hides real IP, encrypts traffic.
A17: MITM: attacker intercepts communication between two parties. Steps: 1. Attacker positions between client and server 2. Intercepts/reads all traffic 3. May alter messages Prevention: HTTPS, certificate pinning, VPN.
A18: Digital certificate: electronic document proving identity of a website/entity. Issued by Certificate Authority (CA). Contains: public key, owner info, CA signature, expiry. Browser shows padlock when cert is valid (HTTPS).
A19: Zero-day: a software flaw unknown to the developer/public. "Zero days" because patch doesn't exist yet. Dangerous because attackers can exploit before fix. Protection: keep software updated, network monitoring.
A20: Least Privilege: users/programs should have only the minimum permissions needed. Reduces attack surface if account is compromised. Example: regular user shouldn't have admin rights for daily tasks.
A21:
def caesar(text,shift,encrypt=True):
    if not encrypt: shift=-shift
    result=[]
    for ch in text:
        if ch.isalpha():
            base=ord("A") if ch.isupper() else ord("a")
            result.append(chr((ord(ch)-base+shift)%26+base))
        else: result.append(ch)
    return "".join(result)
msg="Hello World!"
enc=caesar(msg,13)
dec=caesar(enc,13,False)
print(f"Original: {msg}")
print(f"Encrypted: {enc}")
print(f"Decrypted: {dec}")
A22:
import re
def check_password(pwd):
    score=0; feedback=[]
    if len(pwd)>=8: score+=1
    else: feedback.append("At least 8 characters")
    if re.search(r"[A-Z]",pwd): score+=1
    else: feedback.append("Add uppercase letters")
    if re.search(r"[a-z]",pwd): score+=1
    else: feedback.append("Add lowercase letters")
    if re.search(r"[0-9]",pwd): score+=1
    else: feedback.append("Add numbers")
    if re.search(r"[!@#$%^&*]",pwd): score+=1
    else: feedback.append("Add special chars")
    strength=["Very Weak","Weak","Fair","Good","Strong"][min(score,4)]
    print(f"Password: {pwd}")
    print(f"Strength: {strength} ({score}/5)")
    if feedback: print("Tips:",", ".join(feedback))
for p in ["abc","Hello1","P@ssw0rd!","Admin123"]:
    check_password(p); print()
A23:
import hashlib, os
def hash_password(pwd,salt=None):
    if salt is None: salt=os.urandom(16).hex()
    hashed=hashlib.sha256((salt+pwd).encode()).hexdigest()
    return salt,hashed
def verify(pwd,salt,stored_hash):
    _,h=hash_password(pwd,salt)
    return h==stored_hash
users={}
pwd="MySecret123"
salt,h=hash_password(pwd)
users["alice"]=(salt,h)
print("Stored hash:",h[:20]+"...")
print("Verify correct:",verify("MySecret123",*users["alice"]))
print("Verify wrong:",verify("wrongpass",*users["alice"]))
A24:
# VULNERABLE code (do not use in production)
userdb={"admin":"secret","user1":"pass1"}
def login_unsafe(name,pwd):
    query=f"SELECT * FROM users WHERE name='{name}' AND password='{pwd}'"
    print("Query:",query)
    return name in userdb and userdb[name]==pwd
# SQL injection attempt
print("Unsafe login:",login_unsafe("admin' --","anything"))
# SAFE code with parameterized query
def login_safe(name,pwd):
    return userdb.get(name)==pwd
print("Safe login:",login_safe("admin' --","anything"))
A25:
import socket
def check_open_ports(host,ports):
    open_ports=[]
    for port in ports:
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.settimeout(0.5)
        try:
            s.connect((host,port))
            open_ports.append(port)
        except: pass
        finally: s.close()
    return open_ports
host="localhost"
check_ports=[80,443,8080,3306,22,21]
open_=check_open_ports(host,check_ports)
print(f"Open ports on {host}: {open_ or ['none found']}")
A26:
def xor_encrypt(text,key):
    key_bytes=(key*(len(text)//len(key)+1))[:len(text)]
    return bytes(t^k for t,k in zip(text.encode(),key_bytes.encode()))
def xor_decrypt(cipher,key):
    key_bytes=(key*(len(cipher)//len(key)+1))[:len(cipher)]
    return bytes(c^k for c,k in zip(cipher,key_bytes.encode())).decode()
msg="Top Secret Data"
key="CBSEMOCK"
cipher=xor_encrypt(msg,key)
plain=xor_decrypt(cipher,key)
print(f"Original: {msg}")
print(f"Cipher: {list(cipher)}")
print(f"Decrypted: {plain}")
A27:
import re
def check_phishing(email_content):
    red_flags=[
        (r"urgent|immediately|expire|suspended","Urgency language"),
        (r"verify your|confirm your|update your","Action required"),
        (r"click here|login now","Suspicious links"),
        (r"bank|paypal|amazon|microsoft|apple","Impersonation"),
        (r"\$|win|prize|lottery","Too good to be true"),
    ]
    findings=[]
    for pattern,desc in red_flags:
        if re.search(pattern,email_content,re.I):
            findings.append(desc)
    risk="HIGH" if len(findings)>=3 else "MEDIUM" if findings else "LOW"
    return risk,findings
emails=[
    "Your Amazon account is SUSPENDED! Click here immediately!",
    "Hi, meeting at 3pm tomorrow.",
    "URGENT: Verify your bank details or account expires in 24 hours!"
]
for e in emails:
    risk,flags=check_phishing(e)
    print(f"Risk: {risk} | Flags: {flags or ['None']}\n  {e[:50]}")
A28:
import time
login_attempts={}
def login(username,password,max_attempts=3,lockout=10):
    now=time.time()
    if username in login_attempts:
        count,last_time=login_attempts[username]
        if count>=max_attempts:
            if now-last_time<lockout:
                remaining=lockout-(now-last_time)
                return False,f"Account locked. Wait {remaining:.0f}s"
            else:
                login_attempts[username]=(0,now)
    valid={"admin":"secret","user":"pass123"}
    if valid.get(username)==password:
        login_attempts.pop(username,None)
        return True,"Login successful"
    count=login_attempts.get(username,(0,0))[0]+1
    login_attempts[username]=(count,now)
    return False,f"Invalid credentials. Attempt {count}/{max_attempts}"
for pwd in ["wrong","wrong","wrong","secret"]:
    ok,msg=login("admin",pwd)
    print(f"[{"OK" if ok else "FAIL"}] {msg}")
A29:
import hashlib
def simulate_http(data):
    """HTTP: data sent as plaintext"""
    print(f"HTTP packet (visible): {data}")
    return data
def simulate_https(data,key="secret_key"):
    """HTTPS: data encrypted"""
    encrypted=hashlib.sha256((key+data).encode()).hexdigest()[:16]+"..."
    print(f"HTTPS packet (encrypted): {encrypted}")
    return encrypted
data="username=alice&password=MyPass123"
print("HTTP (insecure):")
http_pkt=simulate_http(data)
print("\nHTTPS (secure):")
https_pkt=simulate_https(data)
print("\nMiddle attacker sees:")
print(f"HTTP: {http_pkt[:40]} (READABLE!)")
print(f"HTTPS: {https_pkt[:40]} (UNREADABLE)")
A30:
from collections import defaultdict
import time
connection_log=defaultdict(list)
def check_connection(ip,port,threshold=10,window=60):
    now=time.time()
    connection_log[ip]=[t for t in connection_log[ip] if now-t<window]
    connection_log[ip].append(now)
    count=len(connection_log[ip])
    if count>threshold:
        alert=f"ALERT: Port scan detected from {ip} ({count} connections in {window}s)"
        return False,alert
    return True,f"{ip}:{port} allowed ({count}/{threshold})"
# Simulate normal traffic then scan
for i in range(5):
    ok,msg=check_connection("10.0.0.1",80)
    if i<2: print(msg)
# Simulate port scan
for port in range(80,92):
    ok,msg=check_connection("10.0.0.2",port)
    if not ok or port in [80,81,91]: print(msg)
Unit 3 · Data Management
Database Concepts
Relational database model, keys, ER diagrams, normalisation — fundamental database theory for CBSE.
12
Marks

Relational Database Model

14.1
STUDENT Table (Relation) RollNo Name Class Marks 101 Aarav 12A 85 102 Priya 12B 92 103 Rahul 12A 78 Primary Key ← Tuple (Row/Record) ↑ Attribute (Column/Field) Terminology Table / Relation: Collection of rows & columns Tuple / Row: One record (horizontal) Attribute / Column: One field (vertical) Domain: Set of valid values for attribute Degree: Number of attributes (columns) Cardinality: Number of tuples (rows) Above table: degree=4, cardinality=3 Keys Primary Key: unique, not null Candidate Key: could be PK Foreign Key: links to another table's PK Alternate Key: candidate key not chosen as PK
Advantages of DBMS
Over traditional file system:

1. Data Independence: Schema changes don't affect programs.
2. No Redundancy: Each piece of data stored once.
3. Data Consistency: No conflicting versions.
4. Data Integrity: Rules enforced (primary key, NOT NULL).
5. Data Security: Access control per user/role.
6. Concurrent Access: Multiple users simultaneously.
7. Easy Querying: SQL is simple and powerful.
8. Backup & Recovery: Built-in features.
Constraints
PRIMARY KEY: Uniquely identifies each row. Cannot be NULL. One per table.
NOT NULL: Column must always have a value.
UNIQUE: All values in column must be different.
DEFAULT: Provides default value if none given.
CHECK: Validates data against a condition.
FOREIGN KEY: Links to Primary Key of another table — maintains referential integrity.

Example: MARKS table with student RollNo as FK referencing STUDENT(RollNo). Prevents adding marks for non-existent student.
Normalisation (1NF, 2NF, 3NF)
Process of organising data to reduce redundancy.

1NF (First Normal Form): No repeating groups; each cell atomic (single value).
2NF: 1NF + no partial dependency (non-key attributes depend on entire PK).
3NF: 2NF + no transitive dependency (non-key attributes don't depend on other non-key attributes).

Anomalies normalisation prevents:
• Insertion anomaly
• Deletion anomaly
• Update anomaly
📌 Remember for Exam
  • Relation = Table. Tuple = Row. Attribute = Column. Domain = valid values for an attribute.
  • Degree = number of columns. Cardinality = number of rows. (Degree=horizontal count, Cardinality=vertical count — remember: "Cardinal" direction = up-down = rows.)
  • Primary Key: Unique + Not Null. A table has exactly ONE Primary Key.
  • Foreign Key: Creates a relationship between tables. Ensures referential integrity.
  • DBMS popular for CBSE: MySQL (open-source, widely used in industry).
  • Normalisation removes redundancy and anomalies by decomposing tables into smaller related tables.

Topic Test: Societal Impact of Computing

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Digital divide refers to:
  • (a) Splitting a hard drive
  • (b) Gap between those with/without technology access
  • (c) Digital copyright
  • (d) Network partition
[1 mark]
Q2.
Which is a positive impact of computing on society?
  • (a) Privacy loss
  • (b) Cybercrime
  • (c) Global communication and information access
  • (d) E-waste
[1 mark]
Q3.
E-waste is:
  • (a) Electronic newspapers
  • (b) Discarded electronic devices
  • (c) Digital garbage
  • (d) Error messages
[1 mark]
Q4.
Open source software:
  • (a) Costs more
  • (b) Source code is freely available and modifiable
  • (c) Is always better
  • (d) Requires license
[1 mark]
Q5.
Copyright protects:
  • (a) Ideas
  • (b) Facts
  • (c) Expressions (code, text, images)
  • (d) Hardware
[1 mark]
Q6.
FOSS stands for:
  • (a) Fast Open Source Software
  • (b) Free and Open Source Software
  • (c) Free Operating System Software
  • (d) File Open Source Standard
[1 mark]
Q7.
Which is NOT a concern about AI?
  • (a) Job displacement
  • (b) Bias in algorithms
  • (c) Faster computation
  • (d) Privacy invasion
[1 mark]
Q8.
Data privacy means:
  • (a) Keeping data fast
  • (b) Right of individuals to control their personal data
  • (c) Encrypting all data
  • (d) Making data public
[1 mark]
Q9.
Green computing aims to:
  • (a) Use more power
  • (b) Reduce environmental impact of computing
  • (c) Increase processing speed
  • (d) Use green-coloured computers
[1 mark]
Q10.
Plagiarism in the digital age:
  • (a) Is easier to detect only
  • (b) Is only a physical crime
  • (c) Includes copying digital content without credit
  • (d) Has no consequences
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
What are 4 positive and 4 negative impacts of IT on society?
[2 marks]
Q12.
What is the output of the following?
Explain cyber ethics.
[2 marks]
Q13.
What is the output of the following?
What is net neutrality?
[2 marks]
Q14.
What is the output of the following?
What is the IT Act 2000 (India)?
[2 marks]
Q15.
What is the output of the following?
Explain digital footprint.
[2 marks]
Q16.
What is the output of the following?
What is assistive technology?
[2 marks]
Q17.
What is the output of the following?
What is cyberbullying and prevention?
[2 marks]
Q18.
What is the output of the following?
What is intellectual property in computing?
[2 marks]
Q19.
What is the output of the following?
What is the impact of social media on society?
[2 marks]
Q20.
What is the output of the following?
What are the ethical issues of AI?
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Simulate digital divide analysis.
[3 marks]
Q22.
Analyse social media usage patterns.
[3 marks]
Q23.
Simulate carbon footprint of computing.
[3 marks]
Q24.
Check text for plagiarism (basic similarity).
[3 marks]
Q25.
Analyse data privacy policy.
[3 marks]
Q26.
Simulate e-waste calculator.
[3 marks]
Q27.
Evaluate digital literacy skills.
[3 marks]
Q28.
Analyse open source vs proprietary software.
[3 marks]
Q29.
Simulate AI bias detection.
[3 marks]
Q30.
Calculate information spread on social network.
[3 marks]
A1: (b) — Digital divide: inequality in access to digital technology based on economic/social factors.
A2: (c) — Computing enables instant global communication, education, healthcare, and information access.
A3: (b) — E-waste: electronic waste — discarded devices like phones, computers, TVs.
A4: (b) — Open source: source code publicly available; anyone can view, modify, distribute.
A5: (c) — Copyright protects creative expressions, not ideas. Software code is copyrightable.
A6: (b) — FOSS = Free and Open Source Software. "Free" means freedom, not necessarily free of cost.
A7: (c) — Faster computation is a benefit of AI. Others are genuine societal concerns.
A8: (b) — Data privacy: individual's right to control how their personal data is collected and used.
A9: (b) — Green computing: designing, using, and disposing of computers in an eco-friendly way.
A10: (c) — Digital plagiarism: copying code, text, images without proper attribution.
A11: Positive: 1. Global communication and connectivity 2. Access to education and information 3. Healthcare improvements (telemedicine, research) 4. Economic growth, e-commerce, remote work Negative: 1. Privacy erosion and data theft 2. Cybercrime and online fraud 3. Job displacement by automation 4. Digital addiction and mental health issues
A12: Cyber ethics: principles for ethical behaviour in the digital world. Key rules: - Respect privacy of others - No theft of digital property - No spreading misinformation - No hacking or unauthorized access - Give credit for others' work (no plagiarism) - Be civil online (no cyberbullying)
A13: Net neutrality: principle that Internet providers treat all traffic equally. No throttling, blocking, or paid prioritisation. Ensures equal access for all websites and services. Without it, ISPs could charge more for certain content.
A14: IT Act 2000: India's law governing electronic transactions and cybercrime. Key provisions: - Electronic signatures have legal validity - Cybercrime offences and penalties - Data protection obligations - Section 66: hacking punishment - Section 67: obscene content online
A15: Digital footprint: trail of data left by online activities. Active: data you intentionally share (posts, profiles) Passive: data collected without active input (cookies, browsing history) Impact: affects privacy, reputation, job prospects. Can never be fully deleted.
A16: Technology that helps people with disabilities: - Screen readers (JAWS, NVDA) for visually impaired - Voice recognition for motor impaired - Hearing aids and captions for hearing impaired - Alternative keyboards and eye-tracking Digital inclusion: designing tech accessible to all.
A17: Cyberbullying: using digital technology to harass, threaten or humiliate. Forms: offensive messages, spreading rumours, fake profiles. Impact: depression, anxiety, social withdrawal. Prevention: report and block, don't retaliate, tell a trusted adult, preserve evidence.
A18: IP in computing: - Copyright: protects software code, digital art, text - Patent: protects inventions (algorithms if novel) - Trademark: brand names and logos - Trade secret: proprietary algorithms (Google search) Software licenses: proprietary, freeware, shareware, open source.
A19: Positive: connectivity, community building, news sharing, activism, business. Negative: misinformation, filter bubbles, addiction, FOMO, cyberbullying, privacy issues. Algorithms amplify engagement (often emotional content), polarising society.
A20: AI ethical issues: 1. Bias: biased training data → discriminatory outcomes 2. Transparency: black-box decisions unexplainable 3. Privacy: mass surveillance capability 4. Job displacement: automation 5. Autonomous weapons 6. Deepfakes and misinformation Need: ethical AI frameworks, regulation, transparency.
A21:
population={"Urban":{"internet_access":85,"no_access":15},"Rural":{"internet_access":45,"no_access":55}}
print("Digital Divide Analysis:")
for region,data in population.items():
    total=data["internet_access"]+data["no_access"]
    pct=data["internet_access"]
    bar="█"*int(pct/10)+" "*int((100-pct)/10)
    print(f"{region:8}: [{bar}] {pct}% connected")
divide=population["Urban"]["internet_access"]-population["Rural"]["internet_access"]
print(f"\nDigital divide gap: {divide} percentage points")
A22:
daily_usage={"Instagram":120,"YouTube":90,"TikTok":60,"Facebook":30,"Twitter":20}
total=sum(daily_usage.values())
print("Daily Social Media Usage (minutes):")
for platform,mins in sorted(daily_usage.items(),key=lambda x:-x[1]):
    pct=mins/total*100
    bar="▓"*int(pct/5)
    print(f"{platform:12}: {bar} {mins}min ({pct:.1f}%)")
print(f"Total: {total//60}h {total%60}min/day")
A23:
devices={"Laptop":50,"Desktop":300,"Server":500,"Smartphone":10,"Router":10}
hours_per_day={"Laptop":8,"Desktop":6,"Server":24,"Smartphone":3,"Router":24}
print("Annual Carbon Footprint:")
total_kwh=0
for device,watts in devices.items():
    hrs=hours_per_day[device]
    kwh=watts*hrs*365/1000
    kg_co2=kwh*0.4
    total_kwh+=kwh
    print(f"{device:12}: {kwh:6.0f} kWh/year = {kg_co2:.0f} kg CO₂")
print(f"Total: {total_kwh:.0f} kWh/year = {total_kwh*0.4:.0f} kg CO₂")
A24:
def similarity(text1,text2):
    words1=set(text1.lower().split())
    words2=set(text2.lower().split())
    common=words1&words2
    union=words1|words2
    return len(common)/len(union)*100 if union else 0
original="Python is a high-level programming language known for simplicity"
submissions=[
    "Python is a high-level programming language known for simplicity",
    "Python is a popular language known for its simple syntax",
    "Java is an object oriented programming language used widely"
]
for i,sub in enumerate(submissions,1):
    sim=similarity(original,sub)
    flag="⚠ PLAGIARISM" if sim>70 else "✓ OK"
    print(f"Submission {i}: {sim:.0f}% similar {flag}")
A25:
privacy_policy="""
We collect: name, email, location, browsing history, device info.
We share data with: advertisers, partners, government on legal request.
Data retention: 5 years.
Your rights: access, delete, opt-out of targeted ads.
Encryption: in transit. Not at rest.
"""
import re
red_flags=[
    ("share.*advertis","Data shared with advertisers"),
    ("5 years","Long retention period"),
    ("Not at rest","Data not encrypted at rest"),
]
print("Privacy Policy Analysis:")
for pattern,concern in red_flags:
    if re.search(pattern,privacy_policy,re.I):
        print(f"  ⚠ Concern: {concern}")
A26:
devices={"Smartphone":{"life":3,"kg":0.2},
         "Laptop":{"life":5,"kg":2.5},
         "Desktop":{"life":7,"kg":15},
         "Monitor":{"life":8,"kg":5}}
print("E-waste Impact Calculator:")
for device,info in devices.items():
    waste_per_year=info["kg"]/info["life"]
    print(f"{device:12}: {waste_per_year:.2f} kg/year of e-waste")
print("\nGreen Computing Tips:")
for tip in ["Buy refurbished devices","Recycle at certified e-waste centres","Repair before replace","Use energy-efficient devices"]:
    print(f"  • {tip}")
A27:
questions=[
    ("Can you spot a phishing email?",True),
    ("Do you use unique passwords for each site?",True),
    ("Do you read privacy policies?",False),
    ("Do you update software regularly?",True),
    ("Do you use 2FA where possible?",True),
]
print("Digital Literacy Self-Assessment:")
for q,ideal in questions:
    ans=input(f"{q} (y/n): ").strip().lower()=="y"
    match=ans==ideal
    print(f"  {'✓' if match else '✗'} Your answer: {'Yes' if ans else 'No'}")
print("Complete the quiz to see your digital literacy score.")
A28:
comparison={
    "Cost":("Free","Paid license (₹1000s+)"),
    "Source code":("Visible","Hidden"),
    "Customizable":("Yes","Rarely"),
    "Support":("Community","Professional"),
    "Examples":("Linux, Python, LibreOffice","Windows, MS Office, Adobe"),
    "Security":("Community-audited","Vendor-controlled"),
}
print(f"{"Factor":20} {"Open Source":25} {"Proprietary":25}")
print("-"*70)
for factor,(os,prop) in comparison.items():
    print(f"{factor:20} {os:25} {prop:25}")
A29:
import random
random.seed(42)
def biased_model(age,gender):
    base_score=random.randint(60,90)
    if gender=="female": base_score-=10
    if age>40: base_score-=5
    return base_score
applicants=[(22,"male"),(25,"female"),(35,"male"),(38,"female"),(28,"male"),(30,"female")]
scores=[biased_model(a,g) for a,g in applicants]
print("Loan approval scores:")
for (age,gender),score in zip(applicants,scores):
    print(f"  Age {age}, {gender}: {score}")
male_avg=sum(s for (a,g),s in zip(applicants,scores) if g=="male")/3
female_avg=sum(s for (a,g),s in zip(applicants,scores) if g=="female")/3
print(f"\nBias detected: Male avg {male_avg:.0f} vs Female avg {female_avg:.0f}")
A30:
def simulate_spread(initial_users,sharing_rate,rounds):
    current=initial_users
    print(f"Round 0: {current} users")
    for r in range(1,rounds+1):
        new_users=int(current*sharing_rate)
        current+=new_users
        print(f"Round {r}: +{new_users} new = {current:,} total")
    return current
print("MISINFORMATION SPREAD:")
total=simulate_spread(10,3,5)
print(f"\nFrom 10 people to {total:,} in 5 rounds!")
print("\nThis shows why fact-checking matters before sharing.")
Unit 3 · Data Management
SQL — DDL & DML
CREATE, ALTER, DROP, INSERT, UPDATE, DELETE — managing database structure and data.
15
Marks

SQL Command Categories

15.1
DDL Data Definition Language CREATE TABLE ALTER TABLE DROP TABLE Structure of table DML Data Manipulation Language INSERT INTO UPDATE … SET DELETE FROM Data inside table DQL Data Query Language SELECT WHERE / ORDER BY GROUP BY / HAVING Query data DCL / TCL Control / Transaction GRANT / REVOKE COMMIT / ROLLBACK SAVEPOINT Permissions & transactions
DDL Commands
CREATE TABLE student (
  roll INT PRIMARY KEY,
  name VARCHAR(30) NOT NULL,
  marks INT DEFAULT 0,
  grade CHAR(1)
);

ALTER TABLE student ADD email VARCHAR(50);
ALTER TABLE student MODIFY marks FLOAT;
ALTER TABLE student DROP COLUMN grade;

DROP TABLE student; — deletes table and all data.
TRUNCATE TABLE student; — deletes all rows, keeps structure.
DML Commands
INSERT INTO student VALUES (101,'Aarav',85,'A');
INSERT INTO student (roll,name) VALUES (102,'Priya');

UPDATE student
SET marks = marks + 5
WHERE grade = 'C';

DELETE FROM student WHERE marks < 33;
DELETE FROM student; — deletes all rows (use TRUNCATE instead).

⚠️ Always use WHERE in UPDATE and DELETE!
Data Types in SQL
Numeric: INT, BIGINT, FLOAT, DECIMAL(p,s)
String: CHAR(n) — fixed length; VARCHAR(n) — variable length; TEXT
Date/Time: DATE (YYYY-MM-DD), TIME (HH:MM:SS), DATETIME, YEAR
Boolean: BOOLEAN (stored as TINYINT in MySQL)

CHAR vs VARCHAR:
CHAR(10) always uses 10 bytes.
VARCHAR(10) uses only as many bytes as needed (+1).
Use CHAR for fixed-length data (roll no, phone), VARCHAR for variable (name, email).

🗄️ SQL Runner — DDL & DML Programs

15.2
P1: Create & Insert
P2: SELECT with WHERE
P3: ORDER BY & LIMIT
P4: UPDATE Records
P5: DELETE Records
P6: Aggregate Functions
P7: GROUP BY & HAVING
P8: ALTER TABLE
P9: LIKE & Wildcards
P10: BETWEEN, IN, NULL
P1: INNER JOIN
P2: LEFT JOIN
P3: Subqueries
P4: String Functions
P5: Date Functions
P6: Math Functions
P7: Constraints Demo
P8: DISTINCT & Complex
P9: FK & Multi-Table
P10: Views & Transactions
P1: School Database
P2: Self JOIN
P3: Window-style Queries
P4: Pivot with CASE
P5: Complex Analytics
SQL Editor (AlaSQL)
Output
Click ▶ Run SQL to execute...
📌 Remember for Exam
  • DDL: CREATE, ALTER, DROP — changes table structure (schema).
  • DML: INSERT, UPDATE, DELETE — changes data inside table.
  • SELECT is DQL (Data Query Language) — retrieves data without changing it.
  • Always include WHERE in UPDATE and DELETE — without it, ALL rows are affected!
  • ORDER BY default is ASC (ascending). Use DESC for descending.
  • HAVING filters groups (use with GROUP BY); WHERE filters individual rows (before grouping).

Topic Test: SQL Practice

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which clause orders query results?
  • (a) GROUP BY
  • (b) HAVING
  • (c) ORDER BY
  • (d) WHERE
[1 mark]
Q2.
LIMIT 5 OFFSET 10 returns:
  • (a) First 5 rows
  • (b) Rows 6-10
  • (c) Rows 11-15
  • (d) Last 5 rows
[1 mark]
Q3.
Which function returns current date?
  • (a) TODAY()
  • (b) NOW()
  • (c) CURDATE()
  • (d) DATE()
[1 mark]
Q4.
LIKE "A_" matches:
  • (a) Names starting with A
  • (b) Any 2-char string starting with A
  • (c) Names with A anywhere
  • (d) Names ending with A
[1 mark]
Q5.
UNION vs UNION ALL:
  • (a) Same
  • (b) UNION removes duplicates; UNION ALL keeps all rows
  • (c) UNION is faster
  • (d) UNION ALL is newer
[1 mark]
Q6.
Which finds NULL values?
  • (a) = NULL
  • (b) == NULL
  • (c) IS NULL
  • (d) LIKE NULL
[1 mark]
Q7.
BETWEEN 10 AND 20 includes:
  • (a) 10 to 20 exclusive
  • (b) 10 and 20 inclusive
  • (c) 11 to 19
  • (d) None of these
[1 mark]
Q8.
INSERT INTO ... SELECT is used to:
  • (a) Insert one row
  • (b) Copy rows from one table to another
  • (c) Update and insert
  • (d) Delete and insert
[1 mark]
Q9.
Which is NOT a valid JOIN?
  • (a) INNER JOIN
  • (b) OUTER JOIN
  • (c) SIDE JOIN
  • (d) CROSS JOIN
[1 mark]
Q10.
EXPLAIN in MySQL:
  • (a) Explains the database
  • (b) Shows query execution plan
  • (c) Lists columns
  • (d) Shows indexes only
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Write SQL for pagination (page 2, 10 per page).
[2 marks]
Q12.
What is the output of the following?
Write SQL: students enrolled this year.
[2 marks]
Q13.
What is the output of the following?
Write SQL using CASE for conditional logic.
[2 marks]
Q14.
What is the output of the following?
Write SQL: names starting with a vowel.
[2 marks]
Q15.
What is the output of the following?
Write SQL: update multiple rows with CASE.
[2 marks]
Q16.
What is the output of the following?
Write SQL: last 30 days records.
[2 marks]
Q17.
What is the output of the following?
Write SQL: combine results from two tables.
[2 marks]
Q18.
What is the output of the following?
Write SQL: find duplicate emails.
[2 marks]
Q19.
What is the output of the following?
Write SQL: top student per class.
[2 marks]
Q20.
What is the output of the following?
Write SQL: running total using variable.
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Write SQL for a complete student records system.
[3 marks]
Q22.
Write complex query: report card generation.
[3 marks]
Q23.
Write SQL: attendance tracking system.
[3 marks]
Q24.
Write SQL: inventory management system.
[3 marks]
Q25.
Write SQL with window functions.
[3 marks]
Q26.
Write SQL: sales analysis dashboard queries.
[3 marks]
Q27.
Write SQL for library management.
[3 marks]
Q28.
Write SQL: student performance trend.
[3 marks]
Q29.
Write SQL: school bus route management.
[3 marks]
Q30.
Write SQL optimisation techniques.
[3 marks]
A1: (c) — ORDER BY col ASC/DESC: sorts the result set.
A2: (c) — LIMIT 5 OFFSET 10: skip first 10 rows, return next 5 (rows 11–15).
A3: (c) — CURDATE(): returns current date (YYYY-MM-DD). NOW() returns datetime.
A4: (b) — "A_": A followed by exactly one character — 2-character strings starting with A.
A5: (b) — UNION: deduplicates combined results. UNION ALL: keeps all rows including duplicates.
A6: (c) — IS NULL: correct way to check for NULL. = NULL never matches.
A7: (b) — BETWEEN a AND b: inclusive of both endpoints.
A8: (b) — INSERT INTO dest SELECT ... FROM src: copies data between tables.
A9: (c) — SIDE JOIN is not a valid SQL join type. Valid: INNER, LEFT, RIGHT, FULL OUTER, CROSS.
A10: (b) — EXPLAIN SELECT ...: shows how MySQL executes the query (indexes used, rows scanned).
A11: SELECT * FROM Students ORDER BY StudentID LIMIT 10 OFFSET 10;
A12: SELECT * FROM Students WHERE YEAR(EnrollDate) = YEAR(CURDATE());
A13: SELECT Name, Marks, CASE WHEN Marks >= 90 THEN "A" WHEN Marks >= 75 THEN "B" WHEN Marks >= 60 THEN "C" ELSE "F" END AS Grade FROM Students;
A14: SELECT Name FROM Students WHERE Name REGEXP '^[AEIOUaeiou]';
A15: UPDATE Students SET Grade = CASE WHEN Marks >= 90 THEN 'A' WHEN Marks >= 75 THEN 'B' ELSE 'C' END WHERE Grade IS NULL;
A16: SELECT * FROM Orders WHERE OrderDate >= DATE_SUB(CURDATE(), INTERVAL 30 DAY);
A17: SELECT Name, "Student" AS Type FROM Students UNION SELECT Name, "Teacher" AS Type FROM Teachers ORDER BY Name;
A18: SELECT Email, COUNT(*) AS Count FROM Users GROUP BY Email HAVING COUNT(*) > 1;
A19: SELECT Class, Name, Marks FROM Students s1 WHERE Marks = (SELECT MAX(Marks) FROM Students s2 WHERE s2.Class = s1.Class);
A20: SET @total = 0; SELECT Month, Sales, (@total := @total + Sales) AS RunningTotal FROM MonthlySales ORDER BY Month;
A21:
CREATE TABLE Students (
  StudentID INT PRIMARY KEY AUTO_INCREMENT,
  Name VARCHAR(100) NOT NULL,
  DOB DATE,
  Email VARCHAR(150) UNIQUE,
  ClassID INT,
  FOREIGN KEY (ClassID) REFERENCES Classes(ClassID)
);
-- CRUD operations
INSERT INTO Students (Name,DOB,Email,ClassID) VALUES ("Alice","2008-06-15","alice@s.com",1);
SELECT * FROM Students ORDER BY Name;
UPDATE Students SET Email="alice2@s.com" WHERE StudentID=1;
DELETE FROM Students WHERE ClassID IS NULL;
A22:
SELECT
  S.StudentID,
  S.Name,
  SUM(CASE WHEN M.Subject="Math" THEN M.Score END) AS Math,
  SUM(CASE WHEN M.Subject="Science" THEN M.Score END) AS Science,
  SUM(CASE WHEN M.Subject="English" THEN M.Score END) AS English,
  AVG(M.Score) AS Average,
  CASE WHEN AVG(M.Score)>=75 THEN "Pass" ELSE "Fail" END AS Result
FROM Students S
LEFT JOIN Marks M ON S.StudentID=M.StudentID
GROUP BY S.StudentID, S.Name
ORDER BY Average DESC;
A23:
CREATE TABLE Attendance (
  AttID INT PRIMARY KEY AUTO_INCREMENT,
  StudentID INT,
  AttDate DATE,
  Status ENUM("Present","Absent","Late"),
  FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
);
-- Monthly summary
SELECT StudentID,
  COUNT(*) AS Total,
  SUM(Status="Present") AS Present,
  ROUND(SUM(Status="Present")*100/COUNT(*),1) AS AttPct
FROM Attendance
WHERE MONTH(AttDate)=MONTH(CURDATE())
GROUP BY StudentID
HAVING AttPct < 75;
A24:
CREATE TABLE Products (
  PID INT PRIMARY KEY AUTO_INCREMENT,
  Name VARCHAR(100),
  Price DECIMAL(10,2),
  Stock INT DEFAULT 0,
  Reorder INT DEFAULT 10
);
-- Low stock alert
SELECT Name, Stock, Reorder FROM Products WHERE Stock <= Reorder;
-- Update stock
UPDATE Products SET Stock=Stock-5 WHERE PID=1;
-- Top selling (simulate)
SELECT P.Name, SUM(O.Quantity) AS Sold
FROM Products P JOIN OrderItems O ON P.PID=O.PID
GROUP BY P.PID ORDER BY Sold DESC LIMIT 5;
A25:
-- Rank students (MySQL 8+)
SELECT Name, Marks,
  RANK() OVER (ORDER BY Marks DESC) AS Rank,
  DENSE_RANK() OVER (ORDER BY Marks DESC) AS DenseRank,
  ROW_NUMBER() OVER (ORDER BY Marks DESC) AS RowNum,
  PERCENT_RANK() OVER (ORDER BY Marks DESC) AS Percentile
FROM Students;
A26:
-- Total revenue by product category
SELECT C.Name AS Category, SUM(OI.Qty*OI.Price) AS Revenue
FROM Categories C JOIN Products P ON C.CID=P.CID
JOIN OrderItems OI ON P.PID=OI.PID
GROUP BY C.CID ORDER BY Revenue DESC;
-- Monthly growth
SELECT Month, Sales,
  LAG(Sales) OVER (ORDER BY Month) AS PrevMonth,
  ROUND((Sales-LAG(Sales) OVER (ORDER BY Month))/LAG(Sales) OVER (ORDER BY Month)*100,1) AS Growth
FROM MonthlySales;
A27:
CREATE TABLE Books (BID INT PRIMARY KEY AUTO_INCREMENT, Title VARCHAR(200), Author VARCHAR(100), Available BOOLEAN DEFAULT 1);
CREATE TABLE Loans (LID INT PRIMARY KEY AUTO_INCREMENT, BID INT, MemberID INT, LoanDate DATE, ReturnDate DATE, FOREIGN KEY (BID) REFERENCES Books(BID));
-- Overdue books
SELECT B.Title, M.Name, L.LoanDate, DATEDIFF(CURDATE(),L.LoanDate) AS OverdueDays
FROM Loans L JOIN Books B ON L.BID=B.BID JOIN Members M ON L.MemberID=M.MID
WHERE L.ReturnDate IS NULL AND DATEDIFF(CURDATE(),L.LoanDate) > 14;
A28:
-- Marks over time per student
SELECT StudentID, Exam, Score,
  AVG(Score) OVER (PARTITION BY StudentID ORDER BY Exam ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS MovingAvg
FROM ExamScores ORDER BY StudentID, Exam;
-- Improvement rate
SELECT StudentID,
  MAX(Score)-MIN(Score) AS Improvement,
  MAX(Score) AS Best, MIN(Score) AS Worst
FROM ExamScores GROUP BY StudentID ORDER BY Improvement DESC;
A29:
CREATE TABLE Routes (RID INT PRIMARY KEY, RouteName VARCHAR(100), Driver VARCHAR(100));
CREATE TABLE Stops (SID INT PRIMARY KEY AUTO_INCREMENT, RID INT, StopName VARCHAR(100), StopOrder INT, PickupTime TIME);
CREATE TABLE BusStudents (StudentID INT, SID INT, PRIMARY KEY (StudentID,SID));
-- Students on each route
SELECT R.RouteName, COUNT(BS.StudentID) AS Students
FROM Routes R JOIN Stops S ON R.RID=S.RID JOIN BusStudents BS ON S.SID=BS.SID
GROUP BY R.RID ORDER BY Students DESC;
A30:
-- 1. Use index on frequently queried column
CREATE INDEX idx_name ON Students(Name);
-- 2. Avoid SELECT * in production
SELECT StudentID, Name FROM Students WHERE Grade="A";
-- 3. Use LIMIT for large tables
SELECT * FROM Logs ORDER BY LogDate DESC LIMIT 100;
-- 4. Check query plan
EXPLAIN SELECT * FROM Students WHERE Name="Alice";
-- 5. Avoid functions on indexed columns in WHERE
-- Slow: WHERE YEAR(DOB)=2008
-- Fast: WHERE DOB BETWEEN "2008-01-01" AND "2008-12-31"
Unit 3 · Data Management
Advanced SQL & Python-MySQL
JOINs, aggregate queries, subqueries, and connecting Python programs to MySQL database.
15
Marks

Python-MySQL Connectivity

16.1
Python import mysql.connector mydb = connect() cursor = mydb .cursor() cursor.execute(sql) SQL Query MySQL Connector Driver TCP/IP MySQL Server DATABASE TABLE ROWS Result set fetchall() Steps 1. import connector 2. connect(host,user, password,database) 3. create cursor 4. execute(SQL) 5. fetchone()/ fetchall() 6. commit() for DML 7. close()
Python-MySQL Code Template
import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="yourpass",
  database="school"
)
cursor = mydb.cursor()
cursor.execute("SELECT * FROM student")
rows = cursor.fetchall()
for row in rows:
  print(row)
cursor.close()
mydb.close()
Cursor Methods
cursor.execute(sql) — Execute single SQL statement.
cursor.executemany(sql, data_list) — Execute for multiple rows.
cursor.fetchone() — Fetch first row only.
cursor.fetchall() — Fetch all rows as list of tuples.
cursor.fetchmany(n) — Fetch next n rows.
cursor.rowcount — Number of rows affected by last DML.
mydb.commit() — Required after INSERT/UPDATE/DELETE.
mydb.rollback() — Undo uncommitted changes.

For INSERT with parameters, use %s placeholders:
sql = "INSERT INTO s VALUES (%s, %s)"
cursor.execute(sql, (101, 'Aarav'))
Types of JOINs
INNER JOIN: Only matching rows from both tables.
LEFT JOIN: All from left + matching from right (NULL if no match).
RIGHT JOIN: All from right + matching from left.
FULL OUTER JOIN: All rows from both (MySQL uses UNION).
CROSS JOIN: Every row of table A with every row of table B.

Syntax:
SELECT a.col, b.col
FROM table_a a
INNER JOIN table_b b
ON a.id = b.id;

🐍 Python Runner — SQL & MySQL Programs

16.2
P1: Connection Template
80\") # Step 4: Fetch results rows = cursor.fetchall() for row in rows: print(row) # Step 5: Close connection cursor.close() mydb.close() ''' print('Python-MySQL Template:') print('='*50) print(code_template) print('Key steps: import → connect → cursor → execute → fetch → close')" onclick="loadProgram(this,'easy-d16')">P2: MySQL Code Template
P3: INSERT Parameterised
P4: Fetch Methods
P5: Student Report
P6: UPDATE/DELETE Template
P7: JOIN Simulation
P8: Error Handling
P9: Aggregate Queries
P10: Menu-Driven App
P1: Multi-table JOINs
P2: Advanced Subqueries
P3: Search & Display
P4: executemany
P5: Grade Calculator
P6: UNION Queries
P7: Transactions
P8: Dict Cursor
P9: SQL Views
P10: Complete App
P1: Full Application
P2: Progress Analysis
P3: Python Analytics
P4: Full Marksheet
P5: CBSE Practical
Python Editor
Output
Click ▶ Run to execute...
📌 Remember for Exam
  • Import: import mysql.connector
  • Connect: mysql.connector.connect(host, user, password, database)
  • DML commits: After INSERT/UPDATE/DELETE, always call mydb.commit().
  • fetchone() = single row tuple; fetchall() = list of tuples; fetchmany(n) = next n rows.
  • Use %s placeholders for parameterised queries — prevents SQL injection.
  • INNER JOIN = intersection; LEFT JOIN = all from left table (NULLs for no match).

Topic Test: Revision & Mixed Practice

Time: 60 min · Total Marks: 60 · MCQ: 10×1 | Output: 10×2 | Programs: 10×3

Section A — MCQ (1 mark each)

Q1.
Which is both mutable and ordered?
  • (a) Tuple
  • (b) String
  • (c) List
  • (d) Set
[1 mark]
Q2.
SELECT DISTINCT removes:
  • (a) NULL values
  • (b) Duplicate rows from result
  • (c) Empty strings
  • (d) Indexed rows
[1 mark]
Q3.
What is OSI Layer 4?
  • (a) Network
  • (b) Session
  • (c) Transport
  • (d) Data Link
[1 mark]
Q4.
Which Python keyword raises an exception?
  • (a) except
  • (b) error
  • (c) raise
  • (d) throw
[1 mark]
Q5.
NIC stands for:
  • (a) Network Interface Card
  • (b) New Internet Connection
  • (c) Network IP Configuration
  • (d) None
[1 mark]
Q6.
Which SQL function returns length of string?
  • (a) SIZE()
  • (b) LEN()
  • (c) LENGTH()
  • (d) COUNT()
[1 mark]
Q7.
Binary 1010 in decimal:
  • (a) 8
  • (b) 10
  • (c) 12
  • (d) 14
[1 mark]
Q8.
Which module provides os.path?
  • (a) path
  • (b) sys
  • (c) os
  • (d) filesystem
[1 mark]
Q9.
Normalisation to 3NF removes:
  • (a) Repeating groups
  • (b) Partial dependencies
  • (c) Transitive dependencies
  • (d) NULL values
[1 mark]
Q10.
Which is a valid IPv6 address?
  • (a) 192.168.1.1
  • (b) 2001:db8::1
  • (c) 127.0.0.1
  • (d) 10.0.0.1
[1 mark]

Section B — Predict the Output (2 marks each)

Q11.
What is the output of the following?
Output?
def mystery(lst):
    return [x**2 for x in lst if x%2==0]
print(mystery([1,2,3,4,5,6]))
[2 marks]
Q12.
What is the output of the following?
Write SQL: find 3rd highest salary.
[2 marks]
Q13.
What is the output of the following?
Output?
try:
    d={"a":1}
    print(d["b"])
except KeyError as e:
    print(f"KeyError: {e}")
finally:
    print("Done")
[2 marks]
Q14.
What is the output of the following?
What is output?
class Dog:
    species="Canis"
    def __init__(self,name): self.name=name
d=Dog("Rex")
print(d.name,Dog.species)
[2 marks]
Q15.
What is the output of the following?
Write SQL: count students per grade with HAVING.
[2 marks]
Q16.
What is the output of the following?
Output?
s="Python Programming"
print(s[7:],s[:6].upper(),s.count("m"))
[2 marks]
Q17.
What is the output of the following?
What does this binary search return?
def bs(lst,t):
    l,r=0,len(lst)-1
    while l<=r:
        m=(l+r)//2
        if lst[m]==t: return m
        elif lst[m]<t: l=m+1
        else: r=m-1
    return -1
print(bs([1,3,5,7,9,11],7))
[2 marks]
Q18.
What is the output of the following?
Write SQL: students with marks in all subjects.
[2 marks]
Q19.
What is the output of the following?
Output?
stack=[]
for x in [1,2,3,4,5]:
    if x%2: stack.append(x)
while stack:
    print(stack.pop(),end=" ")
[2 marks]
Q20.
What is the output of the following?
Ping vs traceroute: what is the difference?
[2 marks]

Section C — Write Programs (3 marks each)

Q21.
Full revision: Python + SQL integration.
[3 marks]
Q22.
Revision: OOP + file handling.
[3 marks]
Q23.
Revision: exceptions + network concepts quiz.
[3 marks]
Q24.
Revision: all Python data structures.
[3 marks]
Q25.
Revision: SQL database design to queries.
[3 marks]
Q26.
Revision: sorting algorithms comparison.
[3 marks]
Q27.
Revision: cyber security checklist.
[3 marks]
Q28.
Revision: mixed class 12 concepts.
[3 marks]
Q29.
Revision: generate complete question paper.
[3 marks]
Q30.
Revision: full Python program combining all topics.
[3 marks]
A1: (c) — List: mutable (can change), ordered (maintains order). Tuples are immutable.
A2: (b) — DISTINCT: eliminates duplicate rows from the SELECT result.
A3: (c) — Layer 4 = Transport (TCP/UDP) — end-to-end communication, reliability.
A4: (c) — "raise ExceptionType("msg")": manually raises an exception.
A5: (a) — NIC: Network Interface Card — hardware that connects a device to a network.
A6: (c) — LENGTH(str): returns number of bytes (or characters for ASCII) in string.
A7: (b) — 1×8 + 0×4 + 1×2 + 0×1 = 10
A8: (c) — os.path is part of the os module. import os gives access to os.path.
A9: (c) — 3NF: removes transitive dependencies (non-key attributes depend only on PK).
A10: (b) — IPv6: 128-bit hex groups separated by colons. :: represents consecutive zero groups.
A11: [4, 16, 36]
A12: SELECT DISTINCT Salary FROM Employees ORDER BY Salary DESC LIMIT 1 OFFSET 2;
A13: KeyError: 'b' Done
A14: Rex Canis
A15: SELECT Grade, COUNT(*) AS Count FROM Students GROUP BY Grade HAVING COUNT(*) >= 5 ORDER BY Grade;
A16: Programming PYTHON 2
A17: 3
A18: SELECT StudentID FROM Marks GROUP BY StudentID HAVING COUNT(DISTINCT Subject) = (SELECT COUNT(*) FROM Subjects);
A19: 5 3 1
A20: ping: sends ICMP echo to test if host is reachable and measures RTT. traceroute: shows the path (each hop/router) a packet takes to reach destination.
A21:
import sqlite3
conn=sqlite3.connect(":memory:")
cur=conn.cursor()
cur.execute("CREATE TABLE Students(ID INTEGER PRIMARY KEY,Name TEXT,Score INTEGER)")
data=[("Alice",90),("Bob",72),("Carol",88),("Dave",55)]
cur.executemany("INSERT INTO Students(Name,Score) VALUES(?,?)",data)
conn.commit()
cur.execute("SELECT Name,Score,CASE WHEN Score>=80 THEN 'A' WHEN Score>=60 THEN 'B' ELSE 'F' END AS Grade FROM Students ORDER BY Score DESC")
print("Name","Score","Grade")
for row in cur.fetchall():
    print(*row)
conn.close()
A22:
import json
class Student:
    def __init__(self,name,marks):
        self.name=name; self.marks=marks
    def grade(self): return "A" if self.marks>=80 else "B" if self.marks>=60 else "C"
    def to_dict(self): return {"name":self.name,"marks":self.marks}
students=[Student("Alice",90),Student("Bob",72),Student("Carol",55)]
data=[s.to_dict() for s in students]
with open("students.json","w") as f:
    json.dump(data,f,indent=2)
with open("students.json") as f:
    loaded=[Student(**d) for d in json.load(f)]
for s in loaded:
    print(f"{s.name}: {s.marks} → {s.grade()}")
A23:
import random
qa=[
    ("Which OSI layer handles routing?","Network"),
    ("TCP provides which type of service?","Reliable"),
    ("What does DNS stand for?","Domain Name System"),
    ("Port number for HTTPS?","443"),
    ("What is a subnet mask used for?","Divides IP into network and host"),
]
random.shuffle(qa)
score=0
for q,ans in qa[:3]:
    try:
        user=input(f"Q: {q}\nA: ").strip()
        if ans.lower() in user.lower():
            print("Correct!"); score+=1
        else:
            print(f"Wrong. Answer: {ans}")
    except Exception as e:
        print(f"Error: {e}")
print(f"Score: {score}/3")
A24:
# List, Tuple, Dict, Set operations
students=["Alice","Bob","Carol","Alice"]
print("List:",students)
print("Unique (set):",set(students))
scores={"Alice":90,"Bob":72,"Carol":88}
print("Dict:",scores)
print("Sorted by score:",sorted(scores.items(),key=lambda x:-x[1]))
passed=tuple(n for n,s in scores.items() if s>=75)
print("Passed (tuple):",passed)
from collections import Counter
print("Name letter freq:",Counter("".join(students)))
A25:
-- Full school database workflow
-- 1. Design
CREATE TABLE Classes(CID INT PRIMARY KEY, ClassName VARCHAR(20));
CREATE TABLE Students(SID INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(100), CID INT, FOREIGN KEY(CID) REFERENCES Classes(CID));
CREATE TABLE Subjects(SubID INT PRIMARY KEY, SubName VARCHAR(50));
CREATE TABLE Marks(MID INT PRIMARY KEY AUTO_INCREMENT, SID INT, SubID INT, Score INT, FOREIGN KEY(SID) REFERENCES Students(SID));
-- 2. Queries
SELECT S.Name, C.ClassName, AVG(M.Score) AS Avg
FROM Students S JOIN Classes C ON S.CID=C.CID JOIN Marks M ON S.SID=M.SID
GROUP BY S.SID HAVING AVG(M.Score)>75 ORDER BY Avg DESC;
A26:
import time, random
data=random.sample(range(1000),100)
def bubble(lst):
    a=lst[:]
    for i in range(len(a)-1):
        for j in range(len(a)-i-1):
            if a[j]>a[j+1]: a[j],a[j+1]=a[j+1],a[j]
    return a
def insertion(lst):
    a=lst[:]
    for i in range(1,len(a)):
        k=a[i]; j=i-1
        while j>=0 and a[j]>k: a[j+1]=a[j]; j-=1
        a[j+1]=k
    return a
for name,fn in [("Bubble",bubble),("Insertion",insertion),("Built-in",sorted)]:
    t=time.time(); fn(data); t=time.time()-t
    print(f"{name:12}: {t*1000:.3f} ms")
A27:
checks={
    "Strong password (8+ chars, mixed)":True,
    "2FA enabled":True,
    "Software updated":True,
    "Antivirus installed":True,
    "Using HTTPS sites":True,
    "VPN on public WiFi":False,
    "Regular data backup":True,
    "Privacy settings reviewed":False,
}
passed=sum(checks.values())
total=len(checks)
score=passed/total*100
print(f"Security Score: {score:.0f}% ({passed}/{total})")
print("\n✓ Done:",[k for k,v in checks.items() if v])
print("\n✗ Todo:",[k for k,v in checks.items() if not v])
A28:
import csv, io, json, os
# 1. CSV
data=[["Name","Score"],["Alice","90"],["Bob","72"]]
buf=io.StringIO()
csv.writer(buf).writerows(data)
print("CSV:\n",buf.getvalue())
# 2. JSON
json_data=json.dumps({"students":["Alice","Bob"],"pass_rate":75})
print("JSON:",json_data)
# 3. OS
print("CWD:",os.getcwd())
print("Python files:",len([f for f in os.listdir(".") if f.endswith(".py")]))
A29:
import random
topics=["Python Functions","File Handling","MySQL","Networking","Cyber Security"]
marks_q=[(10,"MCQ"),(6,"Short Answer"),(4,"Long Answer")]
print("="*50)
print("CBSEMOCK CS Practice Exam — Class 12")
print("="*50)
total=0
for marks,qtype in marks_q:
    print(f"\nSection: {qtype}")
    topic=random.choice(topics)
    print(f"  Q: Explain key concepts in {topic}")
    print(f"  Marks: {marks}")
    total+=marks
print(f"\nTotal Marks: {total}")
A30:
import json, csv, io, os, datetime
# Student Management System - Mini Version
class StudentSystem:
    def __init__(self): self.students=[]
    def add(self,name,score):
        self.students.append({"id":len(self.students)+1,"name":name,"score":score,"date":str(datetime.date.today())})
    def report(self):
        if not self.students: return
        avg=sum(s["score"] for s in self.students)/len(self.students)
        return {"count":len(self.students),"avg":round(avg,1),"top":max(self.students,key=lambda x:x["score"])["name"]}
    def to_json(self): return json.dumps(self.students,indent=2)
    def to_csv(self):
        buf=io.StringIO()
        w=csv.DictWriter(buf,fieldnames=["id","name","score","date"])
        w.writeheader(); w.writerows(self.students)
        return buf.getvalue()
sys=StudentSystem()
for name,score in [("Alice",90),("Bob",72),("Carol",88)]:
    sys.add(name,score)
print("Report:",sys.report())
print("JSON:",sys.to_json()[:80])
print("CSV:",sys.to_csv())
Advertisement

📝 Board Exam Simulator

Practice in CBSE exam conditions. Choose your exam type and start — timer begins immediately. Questions are drawn from all 34 topics with real board exam difficulty and PYQ tagging.

CBSE Style
Full Mock Test
MCQ + Output + Programs · 2 hours · All units
Quick Practice
15 MCQ · 30 min · Core topics
Python Focus
20 MCQ · 50 min · Python topics
SQL & Databases
MCQ + SQL programs · 40 min · DB topics
🏆Achievement unlocked!
Advertisement
Advertisement