🏅 Your Badges
📊 Topic Progress
What is a Computer System?
1.1e.g. 85, 90, 70 (data) → Average = 81.67 (information)
IPO Cycle & Block Diagram
1.2Memory Hierarchy
1.3Memory Units
1.4| Unit | Symbol | Value | Example |
|---|---|---|---|
| Bit | b | Smallest unit (0 or 1) | 1 binary digit |
| Nibble | — | 4 bits | Half a byte |
| Byte | B | 8 bits | 1 character = 1 Byte |
| Kilobyte | KB | 1024 Bytes | Small text file |
| Megabyte | MB | 1024 KB | A song (~4MB) |
| Gigabyte | GB | 1024 MB | A movie (~2GB) |
| Terabyte | TB | 1024 GB | Laptop HDD |
| Petabyte | PB | 1024 TB | Google stores ~15 Exabytes |
Input & Output Devices
1.5ALU (Arithmetic Logic Unit) — does calculations & comparisons.
Registers — tiny ultra-fast storage in CPU.
- 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
PPTopic 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)
- (a) Control Unit
- (b) ALU
- (c) Register
- (d) Cache
- (a) 1000 GB
- (b) 1024 GB
- (c) 1024 MB
- (d) 1000 MB
- (a) ROM
- (b) Flash Drive
- (c) RAM
- (d) HDD
- (a) CPU and HDD
- (b) RAM and HDD
- (c) CPU and RAM
- (d) ROM and RAM
- (a) Monitor
- (b) Printer
- (c) Keyboard
- (d) Speaker
- (a) Binary Input Output System
- (b) Basic Input Output System
- (c) Base Integrated OS
- (d) Built-in OS
- (a) ALU
- (b) CU
- (c) Memory
- (d) Register
- (a) Volatile
- (b) Non-volatile
- (c) Part of CPU
- (d) Faster than RAM
- (a) Hard Disk
- (b) RAM
- (c) CPU
- (d) Cache
- (a) Address bus
- (b) Control bus
- (c) Data bus
- (d) System bus
Section B — Predict the Output (2 marks each)
What is the storage hierarchy from fastest to slowest?
Convert 2 KB to bytes.
Name the three buses in a computer system.
What does the Control Unit NOT do?
If RAM is 4 GB, how many bytes is that?
What is the difference between primary and secondary memory?
What is the role of the accumulator register?
Name two input devices and two output devices.
What is clock speed and its unit?
Expand: ALU, CU, MAR, MDR.
Section C — Write Programs (3 marks each)
kb=float(input("Enter KB: "))
print("Bytes:",kb*1024)
print("MB:",kb/1024)
print("GB:",kb/1024**2)units=["Byte","KB","MB","GB","TB","PB"]
for i,u in enumerate(units):
print(f"{u} = 2^{10*i} bytes = {2**(10*i):,}")acc=0
for val in [10,20,30,40]:
acc+=val
print(f"ACC after adding {val}: {acc}")cpu="Intel i5"
ram="8 GB"
hdd="512 GB SSD"
print(f"CPU: {cpu}\nRAM: {ram}\nStorage: {hdd}")b=int(input("Bytes: "))
print(f"KB: {b/1024:.2f}\nMB: {b/1024**2:.4f}\nGB: {b/1024**3:.6f}")instructions=["FETCH","DECODE","EXECUTE","STORE"]
for step in instructions:
print(f"→ {step}")modules=[4,8,4]
print("Total RAM:",sum(modules),"GB =",sum(modules)*1024**3,"bytes")buses={"Address bus":32,"Data bus":64,"Control bus":8}
for b,w in buses.items():
print(f"{b}: {w}-bit ({2**w:,} combinations)")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")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")Software Classification
2.1Compiler vs Interpreter vs Assembler
2.2| Feature | Compiler | Interpreter | Assembler |
|---|---|---|---|
| Input Language | High-level (C, C++) | High-level (Python, BASIC) | Assembly language |
| Translation | Entire program at once | Line by line | Mnemonic → Machine code |
| Speed | Faster execution | Slower execution | Very fast (near hardware) |
| Error detection | Shows all errors together | Stops at first error | Shows errors after scan |
| Output | Object file (.exe) | No separate object file | Machine code |
| Example use | C, Java | Python, JavaScript | Embedded systems |
- 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)
- (a) MS Word
- (b) VLC Player
- (c) Operating System
- (d) Tally
- (a) One line at a time
- (b) Entire program at once
- (c) Only syntax
- (d) Only semantics
- (a) Device Driver
- (b) BIOS
- (c) Antivirus
- (d) MS Excel
- (a) After full compilation
- (b) Line by line
- (c) Only functions
- (d) Binary directly
- (a) Utility
- (b) OS
- (c) Assembler
- (d) Compiler
- (a) High-level to machine code
- (b) Assembly to machine code
- (c) Machine to assembly
- (d) Object to exe
- (a) Disk Defragmenter
- (b) Antivirus
- (c) File Compressor
- (d) Python IDE
- (a) Free software only
- (b) Source code is publicly available
- (c) No license needed
- (d) Runs on any OS
- (a) Application software
- (b) System software
- (c) Malware
- (d) Firmware
- (a) Interpreter
- (b) Compiler
- (c) Both same
- (d) Depends on OS
Section B — Predict the Output (2 marks each)
Name three types of system software.
What is the difference between freeware and open source?
Which translator is used for Python?
Give two advantages of a compiler over an interpreter.
Name two utility programs and their purposes.
What is firmware? Give one example.
Difference between system software and application software (two points).
What is proprietary software?
Name the translation process in an assembler.
Give two examples each of system and application software.
Section C — Write Programs (3 marks each)
types={"OS":"System","Driver":"System","Word":"Application","Compiler":"System Tool"}
name=input("Enter software name: ")
print(types.get(name,"Unknown type"))statements=["print(1+2)","print('Hello')","print(2**8)"]
for s in statements:
print(f"Executing: {s}")
exec(s)data={"System":["OS","Driver","BIOS"],"Application":["Word","Excel","VLC"],"Utility":["Antivirus","Zip","Defrag"]}
for cat,exs in data.items():
print(f"{cat}: {', '.join(exs)}")sw={"Windows":"System","Photoshop":"Application","BIOS":"System","Chrome":"Application"}
for s,t in sw.items():
print(f"{s} → {t}")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}")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")}")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.")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}")software={"name":"CBSEMOCK Suite","version":"2.5.1","type":"Application","license":"Freeware"}
for k,v in software.items():
print(f"{k.capitalize():12}: {v}")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")Functions of Operating System
3.1Types of Operating Systems
3.2| Type | Description | Example |
|---|---|---|
| Batch OS | Jobs collected in batches, processed without interaction | Early IBM mainframes |
| Time-Sharing OS | Multiple users share CPU time simultaneously | UNIX, Linux servers |
| Real-Time OS (RTOS) | Processes data instantly with strict time constraints | Air traffic control, pacemakers |
| Multi-User OS | Multiple users access the same computer simultaneously | Linux, Windows Server |
| Multi-Tasking OS | Multiple programs run concurrently | Windows 10/11, macOS |
| Distributed OS | Multiple computers work together as one system | Google's infrastructure |
| Mobile OS | Designed for smartphones and tablets | Android, iOS |
| Embedded OS | Built into devices, minimal, specific purpose | Smart TV OS, ATM OS |
- 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)
- (a) Large Area Network
- (b) Local Area Network
- (c) Linked Area Network
- (d) Light Area Network
- (a) Ring
- (b) Bus
- (c) Star
- (d) Mesh
- (a) Hub
- (b) Switch
- (c) Router
- (d) Repeater
- (a) HyperText Transfer Protocol
- (b) HyperText Transmission Protocol
- (c) High Transfer Protocol
- (d) Hyper Terminal Protocol
- (a) FTP
- (b) SMTP
- (c) HTTP
- (d) JPEG
- (a) Speeding up internet
- (b) Blocking unauthorised access
- (c) Compressing data
- (d) Routing packets
- (a) LAN
- (b) MAN
- (c) WAN
- (d) PAN
- (a) A virus
- (b) Small data stored by browser
- (c) A network protocol
- (d) A type of firewall
- (a) Physical
- (b) Data Link
- (c) Network
- (d) Transport
- (a) A fishing game
- (b) Fraudulent attempt to steal credentials
- (c) A network protocol
- (d) A type of encryption
Section B — Predict the Output (2 marks each)
What is the difference between LAN, MAN, and WAN?
Name the 7 layers of the OSI model.
What is an IP address? Give an example.
Difference between hub and switch.
What is a MAC address?
What is the difference between HTTP and HTTPS?
What is bandwidth?
Name two types of network topology and their advantages.
What is DNS?
What is a VPN?
Section C — Write Programs (3 marks each)
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")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}")url=input("URL: ")
if url.startswith("https"): print("Secure (HTTPS)")
elif url.startswith("http"): print("Not secure (HTTP)")
else: print("Unknown protocol")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}")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}")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")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.")devices=["PC1","PC2","Laptop1","Printer"]
print("Star Topology:")
print("Hub")
for d in devices:
print(f" └─ {d}")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}")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}")The Four Number Systems
4.1Conversion Methods — Step by Step
4.2Example: 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
Example: 11001₂ → Decimal?
1×2⁴ + 1×2³ + 0×2² + 0×2¹ + 1×2⁰
= 16 + 8 + 0 + 0 + 1 = 25
Example: 255 → Hex?
255÷16 = 15 R 15=F
15÷16 = 0 R 15=F
Read upward: FF
Example: 2A₁₆ → Binary?
2 → 0010
A (=10) → 1010
Combine: 00101010
Example: 101010₂ → Octal?
101 | 010
5 | 2
Result: 52
Example: 11111111₂ → Hex?
1111 | 1111
F | F
Result: FF
Hexadecimal Digit Table
4.3| Decimal | Binary | Octal | Hex |
|---|---|---|---|
| 0 | 0000 | 0 | 0 |
| 1 | 0001 | 1 | 1 |
| 2 | 0010 | 2 | 2 |
| 3 | 0011 | 3 | 3 |
| 4 | 0100 | 4 | 4 |
| 5 | 0101 | 5 | 5 |
| 6 | 0110 | 6 | 6 |
| 7 | 0111 | 7 | 7 |
| 8 | 1000 | 10 | 8 |
| 9 | 1001 | 11 | 9 |
| 10 | 1010 | 12 | A |
| 11 | 1011 | 13 | B |
| 12 | 1100 | 14 | C |
| 13 | 1101 | 15 | D |
| 14 | 1110 | 16 | E |
| 15 | 1111 | 17 | F |
- 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)
- (a) 1010
- (b) 1100
- (c) 1001
- (d) 1011
- (a) 14
- (b) 15
- (c) 16
- (d) 13
- (a) 14
- (b) 15
- (c) 16
- (d) 13
- (a) 14
- (b) 15
- (c) 16
- (d) 17
- (a) 8
- (b) 10
- (c) 16
- (d) 2
- (a) EF
- (b) FF
- (c) FE
- (d) F0
- (a) 1111
- (b) 10000
- (c) 1010
- (d) 10010
- (a) 4
- (b) 8
- (c) 16
- (d) 2
- (a) 1010
- (b) 1001
- (c) 1010
- (d) 1001
- (a) 0.01
- (b) 0.1
- (c) 0.11
- (d) 0.001
Section B — Predict the Output (2 marks each)
Convert 42 decimal to binary.
Convert binary 11001101 to decimal.
Convert hex 2A to decimal.
Convert decimal 100 to octal.
Add binary 1101 + 1011.
Find 2's complement of 10110.
Convert hex FF to binary.
Convert octal 77 to decimal.
Convert decimal 0.625 to binary.
Subtract binary 1010 - 0011 using 2's complement.
Section C — Write Programs (3 marks each)
n=int(input("Decimal: "))
b=""
while n>0:
b=str(n%2)+b
n//=2
print("Binary:",b or "0")n=int(input("Decimal: "))
o=""
while n>0:
o=str(n%8)+o
n//=8
print("Octal:",o or "0")n=int(input("Decimal: "))
h="0123456789ABCDEF"
s=""
while n>0:
s=h[n%16]+s
n//=16
print("Hex:",s or "0")b=input("Binary: ")
d=0
for bit in b:
d=d*2+int(bit)
print("Decimal:",d)n=int(input("Enter decimal: "))
print(f"Binary : {bin(n)[2:]}")
print(f"Octal : {oct(n)[2:]}")
print(f"Hex : {hex(n)[2:].upper()}")a=input("Binary 1: ")
b=input("Binary 2: ")
result=bin(int(a,2)+int(b,2))[2:]
print("Sum:",result)b=input("Binary: ")
comp="".join("1" if c=="0" else "0" for c in b)
print("1's complement:",comp)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)))h=input("Hex: ")
d=int(h,16)
b=bin(d)[2:]
print(f"Hex {h} = Binary {b}")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}")Logic Gates — Symbols & Truth Tables
5.1- 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)
- (a) Any input is 1
- (b) All inputs are 1
- (c) All inputs are 0
- (d) Any input is 0
- (a) A'·B'
- (b) A'+B'
- (c) A'·B
- (d) A+B'
- (a) OR
- (b) AND
- (c) XOR
- (d) NOR
- (a) Both inputs same
- (b) Both inputs different
- (c) Both inputs 0
- (d) Both inputs 1
- (a) 0
- (b) 1
- (c) A
- (d) A'
- (a) AND
- (b) OR
- (c) NAND
- (d) XOR
- (a) 0
- (b) 1
- (c) A
- (d) A'
- (a) Any input is 1
- (b) All inputs are 0
- (c) Both inputs differ
- (d) All inputs 1
- (a) 0
- (b) 1
- (c) A
- (d) A'
- (a) 0
- (b) 1
- (c) A
- (d) A'
Section B — Predict the Output (2 marks each)
Draw the truth table for XOR gate (2 inputs).
Simplify: A·B + A·B'
State De Morgan's theorems.
What is a minterm? Give example for 2 variables.
Simplify: (A+B)·(A+B')
Name all Boolean laws.
What is a canonical SOP form?
Truth table for: F = A'B + AB'
Convert F(A,B,C) = Σm(1,3,5,7) to SOP.
What is the difference between SOP and POS?
Section C — Write Programs (3 marks each)
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}")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}")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)}")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}")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}")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)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}")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}")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)}") 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))}")Why Encoding?
6.1Computers 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.
ASCII, ISCII, and Unicode
6.2| Feature | ASCII | ISCII | Unicode (UTF-8/UTF-32) |
|---|---|---|---|
| Full name | American Standard Code for Information Interchange | Indian Script Code for Information Interchange | Universal Character Set |
| Bits | 7-bit (128 chars) or 8-bit (256 chars) | 8-bit (256 chars) | UTF-8: 1–4 bytes; UTF-32: 4 bytes |
| Languages | English only | Indian scripts (Hindi, Bengali, Tamil...) | All languages + emoji (143,000+ chars) |
| A (uppercase) | 65 (01000001) | Same as ASCII for English | U+0041 |
| a (lowercase) | 97 (01100001) | Same | U+0061 |
| Space | 32 | 32 | U+0020 |
| 0 (digit) | 48 | 48 | U+0030 |
| Use today | Legacy systems | Limited — replaced by Unicode | ✅ Standard for the web (HTML, Python, etc.) |
a–z : 97–122
0–9 : 48–57
Space: 32
Enter: 13
Difference (A to a): 32
chr(65) = 'A'
UTF-32: Fixed 4 bytes per character. Simpler to process but wastes memory for English.
ord('A') → 65 (char to number)chr(65) → 'A' (number to char)ord('a') - ord('A') → 32Python 3 uses Unicode (UTF-8) by default for all strings.
- 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)
- (a) Infinite
- (b) Finite
- (c) Hardware-specific
- (d) In Python
- (a) Rectangle
- (b) Oval
- (c) Diamond
- (d) Parallelogram
- (a) Definiteness
- (b) Finiteness
- (c) Ambiguity
- (d) Input
- (a) Process
- (b) Decision
- (c) Terminal
- (d) I/O
- (a) Actual programming code
- (b) Machine code
- (c) Informal high-level description
- (d) Assembly language
- (a) Merge Sort
- (b) Quick Sort
- (c) Bubble Sort
- (d) All of these
- (a) O(1)
- (b) O(log n)
- (c) O(n)
- (d) O(n²)
- (a) Any list
- (b) Sorted list only
- (c) Unsorted list only
- (d) Linked list
- (a) Programming language
- (b) Graphical algorithm representation
- (c) Only for loops
- (d) Only for decisions
- (a) Rectangle
- (b) Oval
- (c) Arrow/Line
- (d) Diamond
Section B — Predict the Output (2 marks each)
Write an algorithm to find the largest of three numbers.
List 5 characteristics of a good algorithm.
Trace bubble sort on: [5,3,1,4,2]
What is time complexity? Why does it matter?
Write pseudocode to check if a number is prime.
Describe binary search algorithm step by step.
Name flowchart symbols and their meanings.
Trace linear search for key=4 in [2,7,4,1,9].
Write algorithm for factorial of N.
What is the difference between algorithm and program?
Section C — Write Programs (3 marks each)
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}")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")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")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}")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}")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}")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}")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")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")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}")Steps in Problem Solving
7.1Algorithm Properties & Flowchart Symbols
7.2• Finite — must terminate
• Definite — each step is clear
• Input — zero or more inputs
• Output — at least one output
• Effective — steps are feasible
▱ Parallelogram — Input / Output
▭ Rectangle — Process / Calculation
◇ Diamond — Decision (Yes/No)
○ Circle — Connector
→ Arrow — Flow direction
BEGIN
INPUT num
IF num > 0 THEN
PRINT "Positive"
ELSE
PRINT "Non-positive"
END IF
ENDFlowchart: Sum of N Numbers
7.3- 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)
- (a) function
- (b) def
- (c) define
- (d) fun
- (a) <class 'int'>
- (b) <class 'float'>
- (c) <class 'str'>
- (d) <class 'double'>
- (a) 2name
- (b) my_name
- (c) my-name
- (d) class
- (a) Compiled only
- (b) Interpreted only
- (c) Both compiled and interpreted
- (d) Neither
- (a) Division
- (b) Floor division
- (c) Modulo
- (d) Power
- (a) str()
- (b) float()
- (c) int()
- (d) chr()
- (a) Optional
- (b) For readability only
- (c) Mandatory — defines blocks
- (d) Only for comments
- (a) 3
- (b) 1
- (c) 3.33
- (d) 0
- (a) // comment
- (b) /* comment */
- (c) # comment
- (d) <!-- comment -->
- (a) Hello3
- (b) Hello Hello Hello
- (c) HelloHelloHello
- (d) Error
Section B — Predict the Output (2 marks each)
What is the output? a = 5 b = 2 print(a**b, a//b, a%b)
Find the output: x = "Python" print(x[0], x[-1], x[1:4])
What is printed?
for i in range(2,10,3):
print(i, end=" ")Predict output: a,b = 10,3 print(a/b, a//b)
What is the output?
print(bool(0), bool(""), bool([]))Find the output:
x = 5
if x > 3:
print("A")
elif x > 1:
print("B")Output?
n = 4
result = 1
while n > 0:
result *= n
n -= 1
print(result)What does this print?
print(type(10), type(10.0), type("10"))Output?
for i in range(3):
for j in range(3):
if i == j:
print(i, end=" ")Find the output: x = [1,2,3] x.append(4) print(len(x), x[-1])
Section C — Write Programs (3 marks each)
a=int(input("a: "))
b=int(input("b: "))
a,b=b,a
print(f"a={a}, b={b}")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")n=int(input("Terms: "))
a,b=0,1
for _ in range(n):
print(a,end=" ")
a,b=b,a+bdef 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))s=input("String: ")
if s==s[::-1]:
print("Palindrome")
else:
print("Not a palindrome")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}")n=int(input("Table of: "))
for i in range(1,11):
print(f"{n} x {i:2} = {n*i:3}")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}")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]])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")Python Data Types
8.1Variables, Keywords, Operators
8.2Rules: start with letter/underscore, only letters/digits/underscore, case-sensitive, cannot be a keyword.
Valid:
name, _age, num1Invalid:
2num, my-var, for
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
x = 5 + 2.0 → 7.0 (int→float)Explicit: You convert manually
int("42") → 42float(5) → 5.0str(99) → "99"bool(0) → False
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| Type | Operators | Example | Result |
|---|---|---|---|
| Arithmetic | + - * / // % ** | 17 // 5 17 % 5 2**3 | 3 2 8 |
| Comparison | == != > < >= <= | 5 != 3 4 >= 4 | True True |
| Logical | and or not | True and False not True | False False |
| Assignment | = += -= *= /= //= %= **= | x=5; x+=3 | x becomes 8 |
| Bitwise | & | ^ ~ << >> | 5 & 3 5 | 3 | 1 7 |
| Identity | is is not | x is None | True/False |
| Membership | in not in | 'a' in 'cat' | True |
/ 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.4input()always returns a string. Useint(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)
- (a) True
- (b) False
- (c) Error
- (d) None
- (a) ==
- (b) is
- (c) !=
- (d) in
- (a) 20
- (b) 14
- (c) 24
- (d) 9
- (a) Identity
- (b) Membership
- (c) Arithmetic
- (d) Assignment
- (a) True
- (b) False
- (c) None
- (d) Error
- (a) 20
- (b) 100
- (c) 1024
- (d) 512
- (a) True
- (b) False
- (c) Error
- (d) None
- (a) 5
- (b) 10
- (c) 15
- (d) Error
- (a) +
- (b) -
- (c) **
- (d) *
- (a) 3
- (b) 3.75
- (c) 4
- (d) 3.5
Section B — Predict the Output (2 marks each)
Evaluate: 3 + 4 * 2 - 1 ** 2 / 1
What is (True and False) or (not False)?
Output: x=5; print(x>3, x==5, x!=4)
Evaluate: 17 % 5 + 2 ** 3 // 3
What is the result? a = [1,2,3] print(2 in a, 4 not in a)
Find: x=10; y=3; print(x&y, x|y, x^y)
Evaluate: bool(0) or bool("hello") and bool([])Output? x=7; x//=2; x**=2; print(x)
What does x is y return when x=y=[]?
Operator precedence order (highest to lowest) for: **, *, +, //, %, -, comparisons
Section C — Write Programs (3 marks each)
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}")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}")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}")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}")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}")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}")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)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)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}")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)}")if / elif / else
9.1if condition1:
# block 1
elif condition2:
# block 2
else:
# block 3Indentation (4 spaces) is mandatory in Python — it defines the block.
if x > 0:
if x % 2 == 0:
print("Positive Even")
else:
print("Positive Odd")
else:
print("Non-positive")result = "Even" if n%2==0 else "Odd"Equivalent to:
if n%2==0: result="Even"
else: result="Odd"for Loop & range()
9.2while Loop, break, continue, pass
9.3| Statement | Purpose | Example |
|---|---|---|
while cond: | Repeats while condition is True | while n > 0: n -= 1 |
break | Exits the loop immediately | Exit when found |
continue | Skips rest of current iteration | Skip even numbers |
pass | Do nothing placeholder | Empty function/if body |
for...else | else runs if loop NOT broken by break | Search and report if not found |
while...else | else runs if condition becomes False normally | Countdown then launch |
🐍 Python Runner — Control Flow Programs
9.4- 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 abreaksomewhere to exit.
🔁 Loops & Nested Loops — Deep Dive
9.3Loop variable takes each value one by one.
print(i) # 1 2 3 4 5
while i <= 5:
print(i)
i += 1
for j in range(3):
print(i, j)
range(5) → 0–4range(1,6) → 1–5range(1,10,2) → 1,3,5,7,9range(10,0,-1) → 10 down to 1print(end=' ') to stay on same line. print() moves to next row.for j in range(i):
print('*', end=' ')
print()
Total iterations = outer × inner
Loops Programs
9.4Topic 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)
- (a) break
- (b) continue
- (c) pass
- (d) return
- (a) Skips current iteration
- (b) Exits the loop
- (c) Pauses loop
- (d) Does nothing
- (a) 1,3,5,7,9
- (b) 1,2,3...9
- (c) 2,4,6,8
- (d) 1,3,5,7
- (a) for
- (b) while
- (c) do-while
- (d) for-else
- (a) 0 1 2
- (b) 1 2 3
- (c) Nothing
- (d) Error
- (a) 4
- (b) 3
- (c) 2
- (d) 5
- (a) else only if for fails
- (b) else runs if loop completes without break
- (c) Always runs else
- (d) else runs on error
- (a) while True
- (b) while False
- (c) for i in []
- (d) for i in range(0)
- (a) 1 to 5
- (b) 0 to 5
- (c) 0 to 4
- (d) 1 to 4
- (a) 3
- (b) 6
- (c) 9
- (d) 12
Section B — Predict the Output (2 marks each)
Trace: for i in range(1,6): print(i*i, end=" ")
Output?
i=10
while i>0:
print(i,end=" ")
i-=3What prints?
for i in range(5):
if i%2==0: continue
print(i,end=" ")Output?
for i in range(3):
for j in range(3):
print(i*j,end=" ")
print()Trace?
n=1
while n<100:
n*=2
print(n)Output?
for i in range(1,6):
if i==3: break
else:
print("Done")
print(i)What prints?
for i in range(5):
pass
print(i)Count: how many times does this loop run? for i in range(2,20,3): pass
Output?
sum=0
for i in range(1,11):
if i%2!=0: sum+=i
print(sum)Trace nested loop?
for i in "AB":
for j in "12":
print(i+j,end=" ")Section C — Write Programs (3 marks each)
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=" ")for i in range(1,6):
print("*"*i)n=int(input("Number: "))
print(sum(int(d) for d in str(abs(n))))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()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=" ")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))n=input("Number: ")
for d in "0123456789":
c=n.count(d)
if c: print(f"Digit {d}: {c} time(s)")n=5
num=1
for i in range(1,n+1):
for j in range(i):
print(num,end=" ")
num+=1
print()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!")for i in range(1,6):
print(*range(1,i+1))String Basics — Indexing & Slicing
10.1String Methods — Quick Reference
10.2| Method | What it does | Example → 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 string | len('hello') → 5 |
in / not in | Membership check | 'py' in 'python' → True |
ord(c) / chr(n) | Char ↔ ASCII | ord('A')=65, chr(65)='A' |
▶ String Methods — Click to Run
10.3Click any method row to see it execute live:
🐍 Python Runner — String Programs
10.4- 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 supportinoperator.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)
- (a) Mutable
- (b) Immutable
- (c) Both
- (d) Neither
- (a) Hel
- (b) ell
- (c) ello
- (d) Hell
- (a) up()
- (b) upper()
- (c) toUpper()
- (d) capitalize()
- (a) 2
- (b) 3
- (c) 4
- (d) -1
- (a) Splits at comma
- (b) Splits at space/whitespace
- (c) Splits each character
- (d) Splits at tab only
- (a) HELLO
- (b) Hello
- (c) hello
- (d) hELLO
- (a) 2+2=2+2
- (b) 2+2={4}
- (c) 2+2=4
- (d) Error
- (a) +
- (b) *
- (c) **
- (d) //
- (a) " hello "
- (b) hello
- (c) hello
- (d) hello
- (a) 5
- (b) 6
- (c) 7
- (d) Error
Section B — Predict the Output (2 marks each)
Output? s="CBSEMOCK" print(s[0],s[-1],s[5:])
What prints? s="hello world" print(s.title(), s.upper())
Find the output:
s="banana"
print(s.count("a"), s.index("n"))Output?
print(",".join(["a","b","c"]))
print("a,b,c".split(","))What prints?
s="Python 3.11"
print(s.replace("3.11","3.12"))Output?
for ch in "abc":
print(ch.upper(),end="-")Find:
print("hello".center(11,"*"))Output? s="abcdef" print(s[::-1], s[::2])
What prints?
print("is" in "This is Python")Output?
n=42
print(f"Number: {n:05d}, Hex: {n:#x}")Section C — Write Programs (3 marks each)
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}")s=input("Sentence: ")
result=" ".join(w[::-1] for w in s.split())
print(result)a=input("String 1: ").lower().replace(" ","")
b=input("String 2: ").lower().replace(" ","")
print("Anagram" if sorted(a)==sorted(b) else "Not anagram")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)")s=input("String: ")
seen=set()
result="".join(c for c in s if c not in seen and not seen.add(c))
print(result)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)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}")import re
s=input("String: ")
nums=re.findall(r"\d+",s)
print("Numbers found:",[int(n) for n in nums])s=input("String: ")
result=" ".join(w[0].upper()+w[1:].lower() if w else "" for w in s.split())
print(result)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)")List Structure & Indexing
11.1List Methods
11.2| Method | What it does | Example |
|---|---|---|
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 list | b = a.copy() |
clear() | Remove all elements | [1,2,3].clear() → [] |
del lst[i] | Delete element at index i | del a[0] |
len(lst) | Number of elements | len([1,2,3]) → 3 |
min/max/sum | Min, max, sum of list | min([3,1,2])=1, sum([1,2,3])=6 |
[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📊 2D Lists & Nested Lists
11.4matrix[0] → [1, 2, 3]
matrix[1][2] → 6
m = [[0]*3 for _ in range(3)]
# ⚠️ [[0]*3]*3 is WRONG
# (all rows same object!)
m[-1][-1] # last element
m[0][:] # entire first row
for val in row:
print(val, end=' ')
print()
🐍 Python Runner — List Programs
11.5- 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 = amakes b point to same list. Useb = a.copy()orb = 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)
- (a) Immutable
- (b) Mutable
- (c) Fixed size
- (d) Only integers
- (a) [1,2,3]
- (b) [4,1,2,3]
- (c) [1,2,3,4]
- (d) Error
- (a) del
- (b) pop()
- (c) remove()
- (d) discard()
- (a) [1,2]
- (b) [1,2,3]
- (c) Error
- (d) [1,2,3,1,2,3]
- (a) Same
- (b) sorted() returns new list
- (c) sort() returns new list
- (d) Both modify in place
- (a) [1,9,8,4,5]
- (b) [1,9,8,3,4,5]
- (c) [9,8,1,4,5]
- (d) Error
- (a) [1,2,3]
- (b) [1,2,1,2,1,2]
- (c) Error
- (d) 6
- (a) list2=list1
- (b) list2=list1.copy()
- (c) list2=list1[:]
- (d) Both b and c
- (a) [1]
- (b) None
- (c) 1
- (d) Error
- (a) [0,1,4,9]
- (b) [1,4,9,16]
- (c) [0,1,2,3]
- (d) Error
Section B — Predict the Output (2 marks each)
Output? lst=[10,20,30,40,50] print(lst[1:4], lst[-2:])
What prints? lst=[1,2,3] lst.insert(1,99) print(lst)
Find: lst=[3,1,4,1,5,9,2,6] print(lst.count(1), lst.index(4))
Output? lst=list(range(0,10,2)) lst.reverse() print(lst)
What prints? a=[1,2,3] b=[4,5,6] a.extend(b) print(a,b)
Find the output: lst=[5,3,1,4,2] print(sorted(lst),lst)
Output? m=[[1,2],[3,4],[5,6]] print(m[1][0], m[2][1])
What prints? lst=[1,2,3,4,5] print([x*2 for x in lst if x%2!=0])
Output?
nested=[[1,2,3],[4,5,6]]
for row in nested:
print(sum(row))Find: lst=[10,20,30] lst[1]=99 del lst[0] print(lst)
Section C — Write Programs (3 marks each)
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)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)matrix=[[1,2,3],[4,5,6],[7,8,9]] flat=[x for row in matrix for x in row] print(flat)
lst=[1,2,3,4,5]
k=int(input("Rotate by: "))%len(lst)
print(lst[k:]+lst[:k])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)))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)
words=input("Words: ").split()
words.sort(key=len)
print(words)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)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)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)
Tuple vs List — Key Comparison
12.1| Feature | Tuple | List |
|---|---|---|
| Syntax | (1, 2, 3) | [1, 2, 3] |
| Mutability | ❌ Immutable (cannot change) | ✅ Mutable (can change) |
| Speed | Faster (fixed size) | Slower |
| Memory | Less memory | More memory |
| Use as dict key | ✅ Yes (hashable) | ❌ No |
| Methods | Only count(), index() | Full set of methods |
| Use when | Data should not change (coordinates, RGB) | Data changes (shopping cart) |
Tuple Operations
12.2t1 = (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.
point = 3, 4 → tuple (3,4)Unpacking:
x, y = point → x=3, y=4Extended 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
t.count(x) → count x in tt.index(x) → first index of xlen(t) → number of elementsmin(t) → minimum valuemax(t) → maximum valuesum(t) → sum of elementssorted(t) → returns sorted listt1 + t2 → concatenationt * 3 → repetitionx in t → membership
🐍 Python Runner — Tuple Programs
12.3- Tuples are immutable — once created, elements cannot be added, removed, or changed.
- A singleton tuple must have a trailing comma:
(5,). Writing(5)is just5(integer). - Tuples have only 2 methods:
count()andindex(). - 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)
- (a) Mutable
- (b) Immutable
- (c) Ordered and mutable
- (d) Unordered
- (a) ()
- (b) tuple
- (c) (,)
- (d) {}
- (a) (1)
- (b) (1,)
- (c) [1]
- (d) {1}
- (a) Index of x
- (b) Number of x occurrences
- (c) Removes x
- (d) Error if not found
- (a) Indexing
- (b) Slicing
- (c) append()
- (d) Concatenation
- (a) (10,2,3)
- (b) Error
- (c) (1,2,3)
- (d) (10,10,10)
- (a) 1
- (b) 2
- (c) 3
- (d) Error
- (a) (1,2,3,4,5)
- (b) Error
- (c) (5,7)
- (d) (1,2,3)(4,5)
- (a) More features
- (b) Less memory + immutable
- (c) Larger size
- (d) No reason
- (a) list()
- (b) tuple()
- (c) (list)
- (d) toTuple()
Section B — Predict the Output (2 marks each)
Output? t=(10,20,30,40,50) print(t[1:3], t[-1], t[::-1])
What prints? t=(1,2,3,2,4,2) print(t.count(2), t.index(3))
Find the output: a,b,*c=(1,2,3,4,5) print(a,b,c)
Output? t=(3,1,4,1,5,9) print(min(t), max(t), sum(t), sorted(t))
What prints? t=(1,2) t=t+(3,) print(t)
Output?
coords=[(1,2),(3,4),(5,6)]
for x,y in coords:
print(x+y,end=" ")Find: t1=(1,2,3) t2=(3,4,5) print(set(t1)&set(t2))
Output? t=((1,2),(3,4),(5,6)) print(t[1][1])
What prints? x=(1,2,3) print(list(enumerate(x)))
Output? t=(5,3,8,1,9,2) print(sorted(t)[:3])
Section C — Write Programs (3 marks each)
t=tuple(x**2 for x in range(1,11)) print(t)
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")data=[("name","Alice"),("age",16),("grade","A")]
d=dict(data)
print(d)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}")keys=("name","age","city")
vals=("Alice",16,"Durgapur")
for k,v in zip(keys,vals):
print(f"{k}: {v}")data=[(3,"banana"),(1,"apple"),(2,"cherry")]
data.sort(key=lambda x:x[1])
for item in data:
print(item)t=((1,2),(3,4),(5,6))
for a,b in t:
print(f"{a}+{b}={a+b}")t1=(1,2,3,4,5)
t2=(3,4,5,6,7)
common=tuple(set(t1)&set(t2))
print("Common:",common)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))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}")Dictionary Structure
13.1Dictionary Methods
13.2| Method | What it does | Example → 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) pairs | d.items() → dict_items([...]) |
get(key,default) | Returns value; default if key missing | d.get('age',0) → 0 |
update(d2) | Add/overwrite from another dict | d.update({'age':17}) |
pop(key) | Remove key and return value | d.pop('age') → 17 |
popitem() | Remove and return last (k,v) pair | d.popitem() → ('grade','A+') |
setdefault(k,v) | Get value; set default if key missing | d.setdefault('age',16) → 16 |
copy() | Shallow copy of dict | d2 = d.copy() |
clear() | Remove all items | d.clear() → {} |
del d[key] | Delete a key-value pair | del d['name'] |
key in d | Check membership (checks KEYS) | 'name' in d → True |
len(d) | Number of key-value pairs | len({'a':1,'b':2}) → 2 |
dict.fromkeys(seq,v) | Create dict from sequence of keys | dict.fromkeys(['a','b'],0) → {'a':0,'b':0} |
▶ Dictionary Methods — Click to Run
13.3📦 Nested Dictionaries
13.4'name': 'Alice',
'marks': {'Maths':90,'Sci':85},
'address': {'city':'Durgapur'}
}
student.get('marks',{}).get('Sci',0)
student['address'].update({'state':'WB'})
print(sub, ':', mark)
🐍 Python Runner — Dictionary Programs
13.5- 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]raisesKeyErrorif key is absent.d.get(key, default)is safer.inoperator 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)
- (a) Index-value
- (b) Key-value
- (c) Position-element
- (d) Tag-content
- (a) 0
- (b) Error
- (c) None
- (d) False
- (a) {}
- (b) dict
- (c) []
- (d) ()
- (a) A list
- (b) A tuple
- (c) A dict_keys view
- (d) A set
- (a) {"a":1}
- (b) {"a":1,"b":2}
- (c) {"b":2}
- (d) Error
- (a) .remove()
- (b) del
- (c) .pop()
- (d) discard()
- (a) Unordered
- (b) Ordered by insertion
- (c) Sorted by key
- (d) Random order
- (a) Replaces d
- (b) Adds/updates keys in d
- (c) Returns new dict
- (d) Deletes old keys
- (a) [1,2]
- (b) (1,2)
- (c) {"a":1}
- (d) All
- (a) 3
- (b) 6
- (c) 2
- (d) Error
Section B — Predict the Output (2 marks each)
Output?
d={"x":10,"y":20,"z":30}
print(d["y"], d.get("w",0))What prints?
d={}
for i in range(3):
d[i]=i**2
print(d)Find:
d={"a":1,"b":2,"c":3}
for k,v in d.items():
print(k,v,end="|")Output?
d={"a":1,"b":2,"c":3}
d.pop("b")
print(sorted(d.keys()))What prints?
d={"one":1,"two":2,"three":3}
print({v:k for k,v in d.items()})Find the output:
d1={"a":1,"b":2}
d2={"b":3,"c":4}
d1.update(d2)
print(d1)Output?
d={"marks":[85,90,78]}
d["marks"].append(92)
print(d)What prints?
d={"a":1,"b":2,"c":3}
print(max(d, key=d.get))Find:
words="hello world hello python"
freq={}
for w in words.split():
freq[w]=freq.get(w,0)+1
print(freq)Output?
d={i:i**2 for i in range(1,6)}
print(sum(d.values()))Section C — Write Programs (3 marks each)
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}")d={"a":1,"b":2,"c":3}
inverted={v:k for k,v in d.items()}
print(inverted)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"}")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}")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)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))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}")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]}")d={"banana":3,"apple":1,"cherry":2}
for k,v in sorted(d.items(),key=lambda x:x[1]):
print(f"{k}: {v}")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}")Import Mechanisms
14.1import math → use as math.sqrt()from math import sqrt → use as sqrt()from math import sqrt, pi → multiplefrom math import * → all (avoid!)import math as m → alias: m.sqrt()from math import sqrt as sq → aliased function
math.pi = 3.14159…math.e = 2.71828…math.sqrt(x) → √xmath.ceil(x) → ⌈x⌉math.floor(x) → ⌊x⌋math.factorial(n) → n!math.pow(x,y) → x^y (float)math.log(x) → ln xmath.log10(x) → log₁₀ xmath.sin/cos/tan(x) → trig (radians)math.degrees(r) / math.radians(d)
random.random() → [0.0, 1.0)random.randint(a,b) → int [a,b]random.randrange(start,stop,step)random.choice(seq) → random itemrandom.choices(seq,k=n) → n items (with replacement)random.sample(seq,k) → k unique itemsrandom.shuffle(lst) → in-place shufflerandom.seed(n) → reproducible resultsrandom.uniform(a,b) → float [a,b]
statistics & Other Key Modules
14.2| Module | Key Functions/Attributes | Use case |
|---|---|---|
statistics | mean(), median(), mode(), stdev(), variance() | Statistical analysis |
os | getcwd(), listdir(), mkdir(), path.exists(), path.join() | File system operations |
sys | argv, path, version, exit(), stdin, stdout | System information |
datetime | date.today(), datetime.now(), timedelta | Date/time operations |
string | ascii_letters, digits, punctuation, ascii_uppercase | String constants |
time | time(), sleep(), strftime(), localtime() | Time operations |
collections | Counter, defaultdict, OrderedDict, deque, namedtuple | Specialised containers |
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.3import maththen usemath.sqrt(); ORfrom math import sqrtthen usesqrt()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)
- (a) func
- (b) define
- (c) def
- (d) function
- (a) First parameter
- (b) Last parameter
- (c) After non-defaults
- (d) Before non-defaults
- (a) Keyword arguments
- (b) Variable positional arguments
- (c) Only one arg
- (d) Dictionary args
- (a) 0
- (b) None
- (c) Error
- (d) False
- (a) Can have multiple statements
- (b) Are anonymous one-liners
- (c) Require def keyword
- (d) Cannot take arguments
- (a) Global
- (b) Local
- (c) Both
- (d) Class-level
- (a) A loop
- (b) A base case
- (c) Two functions
- (d) Global variables
- (a) Positional args
- (b) Keyword arguments as dict
- (c) One keyword arg
- (d) Variable loops
- (a) Create global var
- (b) Access/modify global var inside function
- (c) Delete global var
- (d) Pass global to function
- (a) Modifies global state
- (b) Has side effects
- (c) Returns same output for same input
- (d) Reads from file
Section B — Predict the Output (2 marks each)
Output?
def f(a,b=10):
return a+b
print(f(5), f(5,3))What prints?
def f(*args):
return sum(args)
print(f(1,2,3,4,5))Find the output:
def f(n):
if n<=1: return n
return f(n-1)+f(n-2)
print(f(6))Output?
x=10
def f():
x=20
print(x)
f()
print(x)What prints? fn=lambda x,y: x if x>y else y print(fn(5,8), fn(10,3))
Find:
def f(lst=[]):
lst.append(1)
return lst
print(f(), f(), f())Output?
def outer(x):
def inner(y):
return x+y
return inner
add5=outer(5)
print(add5(3))What prints?
def f(a,b,*c,**d):
print(a,b,c,d)
f(1,2,3,4,x=5,y=6)Output?
def fact(n):
return 1 if n==0 else n*fact(n-1)
print([fact(i) for i in range(6)])Find: fns=[lambda x:x+i for i in range(3)] print([f(0) for f in fns])
Section C — Write Programs (3 marks each)
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)}")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}")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))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)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))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")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)])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")def fib_gen(n):
a,b=0,1
for _ in range(n):
yield a
a,b=b,a+b
print(list(fib_gen(10)))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)) # 32Digital Society — Key Concepts
15.1Types:
• 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
• 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
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| Concept | Definition | Examples / Facts |
|---|---|---|
| E-Waste | Discarded electronic devices/components | Old phones, batteries, CRTs, printers, keyboards |
| Toxic materials | Hazardous substances in electronics | Lead (CRT glass), Mercury (LCD), Cadmium (batteries), Arsenic |
| E-Waste disposal | Safe recycling and disposal methods | Authorised recyclers, take-back programmes, refurbishment |
| Digital health | Maintaining wellbeing in digital life | Screen time limits, eye care, posture, digital detox |
| Technomania | Excessive dependence on technology | FOMO, nomophobia (fear of no phone), internet addiction |
- 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)
- (a) try
- (b) except
- (c) finally
- (d) raise
- (a) ValueError
- (b) TypeError
- (c) ZeroDivisionError
- (d) ArithmeticError
- (a) Runs only on error
- (b) Runs only on success
- (c) Always runs
- (d) Skips on error
- (a) throw
- (b) raise
- (c) except
- (d) error
- (a) Key not found in dict
- (b) Wrong key type
- (c) Empty dict
- (d) List index out of range
- (a) Error
- (b) Exception
- (c) BaseException
- (d) RuntimeError
- (a) Ignores exception
- (b) Catches and stores exception in e
- (c) Raises e
- (d) Renames exception
- (a) Wrong type index
- (b) Index out of range
- (c) Empty list
- (d) Negative index
- (a) Exception occurs
- (b) No exception occurs
- (c) Always
- (d) finally runs
- (a) Wrong operation on type
- (b) Division by zero
- (c) Missing key
- (d) File not found
Section B — Predict the Output (2 marks each)
What is output?
try:
print(10/0)
except ZeroDivisionError:
print("Cannot divide")Output?
try:
x=int("abc")
except ValueError as e:
print("Error:",e)What prints?
try:
print("try")
finally:
print("finally")Output?
try:
lst=[1,2,3]
print(lst[5])
except IndexError:
print("Out of range")
else:
print("OK")What is printed?
try:
raise ValueError("bad value")
except ValueError as e:
print(type(e).__name__, str(e))Output?
def safe_div(a,b):
try:
return a/b
except ZeroDivisionError:
return None
print(safe_div(10,2), safe_div(5,0))What prints?
try:
d={"a":1}
print(d["b"])
except KeyError as e:
print(f"Key {e} missing")Output?
try:
print("A")
except:
print("B")
else:
print("C")
finally:
print("D")What is output?
for i in [2,1,0]:
try:
print(10//i,end=" ")
except ZeroDivisionError:
print("Err",end=" ")Output?
class CustomError(Exception): pass
try:
raise CustomError("oops")
except CustomError as e:
print("Custom:",e)Section C — Write Programs (3 marks each)
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))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})")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)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()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")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__)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.")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")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))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())Types of Intellectual Property
16.1| Type | Protects | Duration | Example |
|---|---|---|---|
| Copyright | Original creative works (books, music, code) | Author's life + 60 years (India) | A novel, a song, software code |
| Patent | New inventions and innovations | 20 years | A new algorithm, a hardware device |
| Trademark | Brand names, logos, symbols | 10 years (renewable) | Apple™, Microsoft™ |
| Trade Secret | Confidential business processes | As long as kept secret | Coca-Cola formula, Google's algorithm |
Software Licensing Categories
16.2Cannot 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
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
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 = 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.
- 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)
- (a) "w"
- (b) "r"
- (c) "a"
- (d) "x"
- (a) Overwrites file
- (b) Appends to file
- (c) Reads file
- (d) Creates only
- (a) read()
- (b) readline()
- (c) readlines()
- (d) readall()
- (a) Deletes file
- (b) Moves to start
- (c) Moves to end
- (d) Closes file
- (a) open()
- (b) close()
- (c) with open()
- (d) end()
- (a) Appends to it
- (b) Raises error
- (c) Overwrites (truncates) it
- (d) Opens read-only
- (a) File size
- (b) Current pointer position
- (c) Number of lines
- (d) File name
- (a) "rw"
- (b) "r+"
- (c) "ra"
- (d) "rx"
- (a) "b" suffix like "rb","wb"
- (b) Only for images
- (c) Only for exe files
- (d) Default mode
- (a) IOError
- (b) OSError
- (c) FileNotFoundError
- (d) NotFoundError
Section B — Predict the Output (2 marks each)
Write code to write "Hello World" to a file.
How do you read a file line by line?
What is the difference between read() and readlines()?
What does tell() and seek() do?
What happens when you open a file with "x" mode?
Output?
with open("t.txt","w") as f:
f.write("line1\nline2\nline3")
with open("t.txt") as f:
print(len(f.readlines()))Difference between "w" and "a" mode.
What is "rb" mode used for?
How do you copy contents of one file to another?
What does writelines() do?
Section C — Write Programs (3 marks each)
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")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}")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())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")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())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}")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())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(","))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())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())Types of Cybercrime
17.1| Crime | Description | Example |
|---|---|---|
| Hacking | Unauthorised access to systems | Breaking into a server to steal data |
| Phishing | Fake emails/websites to steal credentials | Fake bank email asking for password |
| Vishing | Voice phishing via phone calls | Fake bank customer care call |
| Smishing | SMS phishing | Fake prize SMS with malicious link |
| Identity theft | Stealing someone's personal information | Using stolen Aadhaar/PAN for fraud |
| Cyberstalking | Online harassment of an individual | Repeatedly messaging/tracking someone |
| Cyberbullying | Bullying using digital technology | Spreading rumours on social media |
| Ransomware | Encrypts files, demands ransom | WannaCry attack (2017) |
| DoS/DDoS | Overwhelming server to make it unavailable | Flooding a website with fake requests |
| Piracy | Illegal copying and distribution of software | Downloading paid software for free |
Malware Types & Cyber Safety
17.2Worm: 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)
✅ 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
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
- 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)
- (a) object
- (b) class
- (c) def
- (d) struct
- (a) Manually only
- (b) When object is created
- (c) When class is defined
- (d) When object is deleted
- (a) The class
- (b) Current instance
- (c) Parent class
- (d) None
- (a) One class to use methods of another
- (b) Multiple returns
- (c) Static typing
- (d) Automatic documentation
- (a) Encapsulation
- (b) Polymorphism
- (c) Compilation
- (d) Abstraction
- (a) Public
- (b) Protected
- (c) Private (name-mangled)
- (d) Static
- (a) Delete parent
- (b) Call parent class method
- (c) Create child
- (d) Override only
- (a) Many classes
- (b) One interface multiple implementations
- (c) Multiple inheritance
- (d) Many files
- (a) self
- (b) cls
- (c) None
- (d) class
- (a) Instance variable
- (b) Local variable
- (c) Class variable
- (d) Global variable
Section B — Predict the Output (2 marks each)
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())What prints?
class A:
x=10
a=A()
b=A()
a.x=20
print(a.x, b.x, A.x)Find output:
class Animal:
def sound(self):
return "..."
class Cat(Animal):
def sound(self):
return "Meow"
print(Cat().sound())Output?
class Counter:
count=0
def __init__(self):
Counter.count+=1
Counter()
Counter()
Counter()
print(Counter.count)What prints?
class Shape:
def __init__(self,color="red"):
self.color=color
def __str__(self):
return f"Shape({self.color})"
print(Shape(), Shape("blue"))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))Find:
class Base:
def hello(self): return "Base"
class Child(Base):
def hello(self): return super().hello()+" Child"
print(Child().hello())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"))What prints?
for cls in [int,float,str,list]:
print(cls.__name__, cls.__bases__[0].__name__)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())Section C — Write Programs (3 marks each)
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()}")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}")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)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())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())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()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)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")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])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__)Information Technology Act, 2000
18.1| Section | Offence | Punishment |
|---|---|---|
| Sec 43 | Unauthorised access to computer/network; downloading data; introducing virus | Civil penalty — compensation up to ₹1 crore |
| Sec 65 | Tampering with computer source code (altering/destroying) | Imprisonment up to 3 years OR fine up to ₹2 lakh OR both |
| Sec 66 | Computer-related offences (hacking, stealing data) | Imprisonment up to 3 years AND/OR fine up to ₹5 lakh |
| Sec 66A | Sending offensive/false messages online (struck down by SC in 2015) | — (no longer in force) |
| Sec 66B | Receiving stolen computer resource | Imprisonment up to 3 years AND/OR fine ₹1 lakh |
| Sec 66C | Identity theft (using others' password, digital signature) | Imprisonment up to 3 years AND fine up to ₹1 lakh |
| Sec 66D | Cheating by impersonating using computer resource | Imprisonment up to 3 years AND fine up to ₹1 lakh |
| Sec 66E | Violation of privacy (publishing private images) | Imprisonment up to 3 years OR fine up to ₹2 lakh OR both |
| Sec 66F | Cyber terrorism (targeting critical infrastructure) | Life imprisonment |
| Sec 67 | Publishing obscene material electronically | Imprisonment up to 5 years AND fine up to ₹10 lakh |
| Sec 72 | Breach of confidentiality and privacy | Imprisonment up to 2 years OR fine up to ₹1 lakh OR both |
| Sec 79 | Intermediary not liable if follows due diligence (safe harbour) | Protection for ISPs/platforms |
E-Waste Management
18.2Extended 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
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
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
- 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)
- (a) FIFO
- (b) LIFO
- (c) LILO
- (d) FILO
- (a) LIFO
- (b) FIFO
- (c) FILO
- (d) LILO
- (a) enqueue
- (b) push
- (c) insert
- (d) add
- (a) pop
- (b) dequeue
- (c) remove
- (d) delete
- (a) Pop from empty
- (b) Push to full
- (c) Access middle
- (d) Dequeue from empty
- (a) tuple
- (b) dict
- (c) list
- (d) set
- (a) ab+c*
- (b) abc*+
- (c) ab*c+
- (d) abc+*
- (a) Stack
- (b) Queue
- (c) Tree
- (d) Graph
- (a) Removes top
- (b) Shows top without removing
- (c) Inserts at top
- (d) Clears stack
- (a) Only queues
- (b) Only stacks
- (c) Both stack and queue (efficient)
- (d) Sorting
Section B — Predict the Output (2 marks each)
Trace: push 1,2,3 then pop twice from stack.
Enqueue 5,10,15 then dequeue twice. What remains?
Convert infix A+B*C to postfix.
Output? stack=[] for x in [1,2,3,4]: stack.append(x) while stack: print(stack.pop(),end=" ")
Output? from collections import deque q=deque() for x in [10,20,30]: q.append(x) print(q.popleft(), q.popleft())
Evaluate postfix: 5 3 2 * +
Output?
stack=[]
for c in "({[": stack.append(c)
print(len(stack), stack[-1])What is the use of stack in function calls?
Output? from collections import deque dq=deque([1,2,3]) dq.appendleft(0) dq.append(4) print(list(dq))
Trace balanced parentheses check on "({[]})".Section C — Write Programs (3 marks each)
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())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())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'}")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"))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.0def reverse_str(s):
stack=list(s)
result=""
while stack: result+=stack.pop()
return result
print(reverse_str("Hello Python"))
print(reverse_str("CBSEMOCK"))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())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)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())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)Scope & Arguments
1.1Global: 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
def f(a, b) → f(1, 2)Default:
def f(a, b=10) → f(5) worksKeyword:
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}
square = lambda x: x**2add = lambda x,y: x+ymap(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
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- LEGB rule: Python looks for variable in Local → Enclosing → Global → Built-in order.
global xinside 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)
- (a) import math
- (b) from math import sqrt
- (c) import math.sqrt
- (d) load math.sqrt
- (a) Math help
- (b) All attributes/functions in math
- (c) Math source code
- (d) Math version
- (a) math
- (b) os
- (c) numpy
- (d) sys
- (a) 3
- (b) 4
- (c) 3.9
- (d) Error
- (a) 1 to 5
- (b) 1 to 6
- (c) 0 to 6
- (d) 0 to 5
- (a) Module is imported
- (b) Script runs directly
- (c) Any time
- (d) Never
- (a) Current file name
- (b) Current working directory path
- (c) OS version
- (d) Home directory
- (a) time
- (b) date
- (c) datetime
- (d) calendar
- (a) Running Python
- (b) Installing packages
- (c) Debugging
- (d) Compiling
- (a) Single .py file
- (b) Directory with __init__.py
- (c) Function collection
- (d) Module alias
Section B — Predict the Output (2 marks each)
Output? import math print(math.sqrt(144), math.ceil(4.1), math.floor(4.9))
What prints? import random random.seed(42) print(random.randint(1,10))
Find: import os print(type(os.getcwd()))
Output? from datetime import date today=date.today() print(type(today).__name__)
What prints? print(abs(-5), round(3.567,2), pow(2,10))
Find the output:
s="Hello World"
print(s.upper(), len(s), s.count("l"))Output? import math print(math.pi, math.e)
What prints? print(list(range(0,20,5)))
Find: print(divmod(17,5))
Output? import sys print(sys.version[:6])
Section C — Write Programs (3 marks each)
# 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)}")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}")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})")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)")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}")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())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")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=" ")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}")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)Exception Handling Syntax
2.1try:# 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)
ValueError — wrong value type (int('abc'))TypeError — wrong type operation ('a'+1)ZeroDivisionError — divide by zeroIndexError — list index out of rangeKeyError — dict key not foundFileNotFoundError — file missingNameError — variable not definedAttributeError — attribute doesn't existImportError — module not foundRecursionError — max depth exceededStopIteration — iterator exhaustedOverflowError — number too large
raise ValueError("must be positive")Re-raise:
except Exception:raise # re-raises same exceptionCustom exception class:
class AgeError(Exception):def __init__(self, age):self.age = agesuper().__init__(f"Invalid: {age}")raise AgeError(-5)
🐍 Python Runner — Exception Programs
2.2- else in try-except runs ONLY if no exception occurred. finally ALWAYS runs.
- Order: most specific exception before more general. Put
Exceptionlast. 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
AssertionErrorif 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)
- (a) BaseException
- (b) Exception
- (c) Error
- (d) AnyError
- (a) assert statement when False
- (b) raise statement
- (c) try block
- (d) import statement
- (a) Multiple except blocks
- (b) raise e from original_e
- (c) try-except-try
- (d) Nested try
- (a) ExitError
- (b) SystemExit
- (c) RuntimeError
- (d) KeyboardInterrupt
- (a) print()
- (b) raise
- (c) warnings.warn()
- (d) except
- (a) List is empty
- (b) Iterator is exhausted
- (c) Loop breaks
- (d) Generator returns
- (a) Too many imports
- (b) RAM is full / allocation fails
- (c) Disk is full
- (d) CPU overload
- (a) Function returns twice
- (b) Maximum recursion depth exceeded
- (c) Recursive import
- (d) None
- (a) try-except block
- (b) Object with __enter__/__exit__ (used in with)
- (c) Module for errors
- (d) Debugger
- (a) KeyboardInterrupt
- (b) CtrlCError
- (c) InterruptException
- (d) SystemInterrupt
Section B — Predict the Output (2 marks each)
Output?
try:
assert 5>10, "5 is not > 10"
except AssertionError as e:
print("Assertion failed:",e)What prints?
def gen():
yield 1; yield 2
g=gen()
print(next(g))
print(next(g))
try: print(next(g))
except StopIteration: print("Done")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)Output?
import warnings
warnings.warn("Deprecated!")
print("After warning")What prints?
try:
x=[][0]
except (IndexError, KeyError) as e:
print(type(e).__name__,"caught")Find output:
def risky():
raise ValueError("bad")
try:
try:
risky()
except ValueError:
print("Inner caught")
raise
except ValueError:
print("Outer caught")Output?
class CM:
def __enter__(self): print("Enter"); return self
def __exit__(self,*args): print("Exit"); return False
with CM() as c:
print("Inside")What is __exit__ return value meaning?
Output?
def f(n):
if n==0: return
f(n-1)
try: f(1000)
except RecursionError: print("Recursion limit hit")
else: print("OK")Find:
try:
open("nonexistent.xyz")
except OSError as e:
print(e.errno, type(e).__name__)Section C — Write Programs (3 marks each)
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}")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}")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())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)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())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}")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)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__}")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)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}")File Modes & Operations
3.1'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)
f.read() → entire file as one stringf.read(n) → read n charactersf.readline() → one line (with \n)f.readlines() → list of all linesIterate directly:
for line in f:print(line.strip())Position methods:
f.tell() → current position (bytes)f.seek(0) → go to startf.seek(n) → go to position n
f.write(str) → writes string, returns char countf.writelines(list) → writes list of stringsNote: write() does NOT add \n automatically. You must add it:
f.write('Hello\n')Flush:
f.flush() — force write to diskCheck if closed:
f.closed → True/FalseFile name:
f.nameMode:
f.mode
🐍 Python Runner — Text File Programs
3.2- 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\nexplicitly.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)
- (a) file
- (b) csv
- (c) pandas
- (d) io
- (a) Read text files
- (b) Serialise Python objects to binary
- (c) Handle CSV
- (d) Compress files
- (a) Converting object to bytes/string for storage
- (b) Sorting a list
- (c) Compressing a file
- (d) Encrypting data
- (a) List of strings
- (b) Iterator of rows (lists)
- (c) String
- (d) Dict
- (a) "w"
- (b) "wb"
- (c) "bw"
- (d) "wbin"
- (a) JSON string to dict
- (b) Python object to JSON string
- (c) File to JSON
- (d) Dict to CSV
- (a) Reads CSV as list rows
- (b) Reads CSV rows as dicts (header as keys)
- (c) Reads JSON
- (d) Reads binary
- (a) dump
- (b) load
- (c) dumps
- (d) write
- (a) Same
- (b) load reads from file, loads from string
- (c) loads reads from file
- (d) Both from string
- (a) readline()
- (b) readlines()
- (c) read()
- (d) for line in file
Section B — Predict the Output (2 marks each)
Output?
import json
d={"name":"Alice","age":16}
s=json.dumps(d)
print(type(s).__name__, s)What prints?
import json
s='{"x":10,"y":20}'
d=json.loads(s)
print(d["x"]+d["y"])Find: import pickle data=[1,2,3,"hello"] b=pickle.dumps(data) loaded=pickle.loads(b) print(loaded)
Output of csv.reader on "a,b,c\n1,2,3"?
What does with open("f.csv","r",newline="") do?Difference between pickle and json serialisation.
Output? import io, csv buf=io.StringIO() w=csv.writer(buf) w.writerow(["Name","Age"]) w.writerow(["Alice",16]) print(buf.getvalue())
What is the danger of pickle from untrusted sources?
Output? import json print(json.dumps([1,2,3], indent=2))
Difference between text mode and binary mode files.
Section C — Write Programs (3 marks each)
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)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']}")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__)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"])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))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))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())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}")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}")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}")Binary Files & pickle
4.1Binary 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 binaryopen('file.bin', 'wb') — write binaryopen('file.bin', 'ab') — append binary
Deserialization: bytes → Python object
import pickleWrite (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)
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:breakOR dump entire list at once:
pickle.dump(students_list, f)
🐍 Python Runner — Binary File Programs
4.2- 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)
- (a) Text lines
- (b) Raw bytes
- (c) CSV rows
- (d) JSON objects
- (a) "r"
- (b) "rb"
- (c) "br"
- (d) "binary"
- (a) "r"
- (b) "w"
- (c) "rb"
- (d) "wb"
- (a) Comma Separated Values
- (b) Comma String Values
- (c) Character Separated Values
- (d) Column String Values
- (a) csv.reader
- (b) csv.writer
- (c) csv.DictReader
- (d) csv.DictWriter
- (a) Tab
- (b) Space
- (c) Comma
- (d) Semicolon
- (a) writerow()
- (b) write()
- (c) writerows()
- (d) writeall()
- (a) No
- (b) Yes
- (c) Only on Windows
- (d) Only on Linux
- (a) OOP structures
- (b) Packing/unpacking binary data
- (c) Database
- (d) Sorting
- (a) Go to start
- (b) Go to last byte
- (c) Go to byte -1
- (d) Error
Section B — Predict the Output (2 marks each)
Write and read an integer as binary.
What does tell() return after writing 10 bytes?
Output? import csv, io buf=io.StringIO() w=csv.writer(buf) w.writerow([1,2,3]) buf.seek(0) print(buf.read())
Difference between csv.reader and csv.DictReader.
What is the use of newline="" when opening CSV files?
How do you write a binary file containing bytes [65,66,67]?
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())What is struct format string "3s2i"?
How do you append to a binary file?
CSV quoting: when are fields automatically quoted?
Section C — Write Programs (3 marks each)
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"])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])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})")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())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")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)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())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)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}")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)CSV Module
5.1import csvRead:
with open('f.csv','r',newline='') as f:reader = csv.reader(f)for row in reader:print(row) # list of stringsWrite:
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.
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.reader(f, delimiter=';')csv.reader(f, delimiter='\t') — TSVquotechar: char to quote fields containing delimiter
quoting: QUOTE_ALL, QUOTE_MINIMAL, QUOTE_NONE
Skip header:
next(reader) # skip first rowGet header:
reader.fieldnames on DictReaderWrite with quote:
csv.writer(f, quoting=csv.QUOTE_ALL)
🐍 Python Runner — CSV File Programs
5.2- 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)
- (a) QUOTE_MINIMAL
- (b) QUOTE_ALL
- (c) QUOTE_NONNUMERIC
- (d) QUOTE_NONE
- (a) str
- (b) int
- (c) float
- (d) bool
- (a) sep="\t"
- (b) delimiter="\t"
- (c) tab=True
- (d) sep=tab
- (a) fieldnames parameter
- (b) auto headers
- (c) header=True
- (d) column list
- (a) Creates CSV
- (b) Detects CSV dialect
- (c) Validates CSV
- (d) Sorts CSV
- (a) DictReader with restval
- (b) reader with default
- (c) writer with fill
- (d) None
- (a) Adds extra columns
- (b) Handles extra keys in dict (ignore/raise)
- (c) Extends file
- (d) None
- (a) Only UTF-8
- (b) Any encoding with proper open()
- (c) Only ASCII
- (d) Auto-detects encoding
- (a) csv.reader
- (b) csv.DictReader
- (c) pandas
- (d) All same
- (a) Total lines
- (b) Current line number
- (c) Blank lines count
- (d) Header line
Section B — Predict the Output (2 marks each)
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)What does QUOTE_ALL produce for ["hello",42]?
Find the sniffer output on "a;b;c\n1;2;3".
DictReader with missing column: what does restval do?
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)How to read a CSV with ";" delimiter?
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())
What is a CSV dialect?
DictWriter with extrasaction="ignore": what happens with extra keys?
How to skip the header row when using csv.reader?
Section C — Write Programs (3 marks each)
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}")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())
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)}")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']}%")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}")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())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']}") 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())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)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)Stack — LIFO Structure
6.1class 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) == 0def size(self):return len(self.items)
• 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.
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- 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)
- (a) Files only
- (b) Only SQL
- (c) Organised data with access control
- (d) Only tables
- (a) MongoDB
- (b) Cassandra
- (c) MySQL
- (d) Redis
- (a) Can be NULL
- (b) Must be unique and NOT NULL
- (c) Can repeat
- (d) Optional
- (a) Primary key of same table
- (b) Unique key
- (c) References PK of another table
- (d) Any column
- (a) Standard Query Language
- (b) Structured Query Language
- (c) Simple Query Language
- (d) Sequential Query Language
- (a) INSERT
- (b) UPDATE
- (c) SELECT
- (d) DELETE
- (a) Speed up queries
- (b) Remove redundancy
- (c) Add tables
- (d) Delete duplicates
- (a) SELECT
- (b) INSERT
- (c) CREATE
- (d) UPDATE
- (a) A column
- (b) A row/record
- (c) A table
- (d) A key
- (a) 1NF
- (b) 2NF
- (c) 3NF
- (d) BCNF
Section B — Predict the Output (2 marks each)
What is ACID in databases?
Difference between DDL and DML.
What is a candidate key?
Explain 1NF with example.
What is referential integrity?
Difference between INNER JOIN and LEFT JOIN.
What are the 4 properties of a relation (table)?
What is a surrogate key?
What is a view in SQL?
Difference between WHERE and HAVING.
Section C — Write Programs (3 marks each)
# 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")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)")erd="""
[STUDENT]---(enrolled in)---[COURSE]
| |
<StudentID> <CourseID>
<Name> <CourseName>
<DOB> <Credits>
| |
[STUDENT] has MARKS
[MARKS]--<StudentID FK, CourseID FK, Score>
"""
print(erd)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])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)])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"])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}")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}")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")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}")Queue — FIFO Structure
7.1class 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.
from collections import dequeq = deque()q.append(val) → enqueue (rear) O(1)q.popleft() → dequeue (front) O(1)q[0] → peek frontq[-1] → peek rearlen(q) == 0 → is emptydeque is double-ended:
q.appendleft(val) → add to frontq.pop() → remove from rear
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- 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)
- (a) NoSQL DB
- (b) Relational DBMS
- (c) Object DB
- (d) File system
- (a) MAKE TABLE
- (b) CREATE TABLE
- (c) ADD TABLE
- (d) NEW TABLE
- (a) Exactly 50 chars
- (b) Up to 50 chars
- (c) 50 bytes
- (d) 50 numbers
- (a) NOT NULL
- (b) PRIMARY KEY
- (c) UNIQUE
- (d) DEFAULT
- (a) Dates
- (b) Auto-increasing integer PK
- (c) Floats
- (d) Boolean
- (a) SHOW ALL
- (b) SHOW TABLES
- (c) LIST TABLES
- (d) DISPLAY TABLES
- (a) Same
- (b) INT: 4 bytes (-2B to 2B); BIGINT: 8 bytes (±9×10¹⁸)
- (c) BIGINT is for decimals
- (d) INT is larger
- (a) All rows
- (b) Column definitions (name,type,constraints)
- (c) Row count
- (d) All databases
- (a) TEXT
- (b) STRING
- (c) CHARACTER
- (d) ALPHABET
- (a) Column constraint
- (b) Fallback value when INSERT omits column
- (c) Data type
- (d) Index
Section B — Predict the Output (2 marks each)
Write SQL to create a Students table.
Write SQL to insert 3 student records.
Write SQL to select all students with Grade A.
How do you update a student's grade?
Write SQL to delete a student record.
What does DESC Students; show?
Write SQL to add a new column Phone to Students.
What is the output of SELECT COUNT(*) FROM Students;?
Write SQL to find the student with highest marks.
Difference between CHAR and VARCHAR.
Section C — Write Programs (3 marks each)
-- 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;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;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;-- 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;
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
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";
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;
-- 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;
-- 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);
-- 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;
Sorting — Algorithm Comparison
8.1Largest 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.
After pass i, first i elements are sorted.
def selection_sort(arr):n = len(arr)for i in range(n-1):min_idx = ifor j in range(i+1, n):if arr[j] < arr[min_idx]:min_idx = jarr[i], arr[min_idx] = arr[min_idx], arr[i]
Like sorting playing cards in hand.
def insertion_sort(arr):for i in range(1, len(arr)):key = arr[i]j = i - 1while j >= 0 and arr[j] > key:arr[j+1] = arr[j]j -= 1arr[j+1] = key
🐍 Python Runner — Sorting Programs
8.2- 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)
- (a) INSERT
- (b) SELECT
- (c) ALTER
- (d) UPDATE
- (a) Same
- (b) TRUNCATE: removes all rows faster, no rollback; DELETE: can have WHERE, rollback
- (c) DELETE is faster
- (d) TRUNCATE keeps rows
- (a) All rows only
- (b) All rows and table structure
- (c) Only columns
- (d) Table from another DB
- (a) Cancels transaction
- (b) Saves all changes permanently
- (c) Drops table
- (d) Starts transaction
- (a) NOT NULL
- (b) UNIQUE
- (c) CHECK
- (d) FOREIGN KEY
- (a) Committed transactions
- (b) Uncommitted changes in current transaction
- (c) All table data
- (d) Indexes
- (a) Prevent delete if child exists
- (b) Delete child rows when parent is deleted
- (c) Set child to NULL
- (d) Error on delete
- (a) INSERT
- (b) UPDATE
- (c) SELECT
- (d) DELETE
- (a) End transaction
- (b) Create a rollback point within transaction
- (c) Commit part
- (d) Delete rows
- (a) DDL
- (b) DML
- (c) DCL
- (d) TCL
Section B — Predict the Output (2 marks each)
Write DDL to create Products table with constraints.
What does ALTER TABLE ... MODIFY do?
Write SQL to add UNIQUE constraint to existing column.
Difference between DROP TABLE and TRUNCATE TABLE.
What is a transaction? Give its properties.
Write a transaction with SAVEPOINT.
What is ON DELETE SET NULL vs ON DELETE CASCADE?
Write SQL to grant and revoke privileges.
What does DESCRIBE (or DESC) show?
Difference between WHERE and HAVING with GROUP BY.
Section C — Write Programs (3 marks each)
-- 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)
);-- 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;-- 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;
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;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;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;
-- 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;
-- 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 );
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()) );
-- 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;
Linear vs Binary Search
9.1def linear_search(arr, target):for i, val in enumerate(arr):if val == target:return ireturn -1Best: O(1) — found at index 0.
Average: O(n/2) = O(n)
Worst: O(n) — not found or at end.
Works on unsorted lists.
def binary_search(arr, target):low, high = 0, len(arr)-1while low <= high:mid = (low + high) // 2if arr[mid] == target: return midelif arr[mid] < target: low = mid+1else: high = mid-1return -1All cases: O(log n). Requires sorted list.
• 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- 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)
- (a) COUNT(*)
- (b) COUNT(col)
- (c) Both same
- (d) Neither
- (a) Highest mark
- (b) Sum of marks
- (c) Sum divided by count (ignoring NULLs)
- (d) Median
- (a) Distinct column values
- (b) Row number
- (c) Primary key
- (d) Table name
- (a) WHERE is slower
- (b) WHERE cannot filter aggregate results
- (c) HAVING is shorter
- (d) No difference
- (a) COUNT
- (b) MAX
- (c) SUM
- (d) AVG
- (a) Highest salary row
- (b) Just the highest salary value
- (c) All salaries sorted
- (d) Error
- (a) COUNT(*)
- (b) COUNT(DISTINCT col)
- (c) SUM(DISTINCT col)
- (d) AVG(DISTINCT col)
- (a) Groups rows
- (b) Concatenates grouped values into a string
- (c) Counts groups
- (d) Sums strings
- (a) Filters groups
- (b) Adds subtotals and grand total
- (c) Sorts groups
- (d) Removes NULLs
- (a) SUM
- (b) AVG
- (c) UPPER
- (d) COUNT
Section B — Predict the Output (2 marks each)
Write SQL: count students per grade.
Write SQL: average marks by subject.
Write SQL: find departments with more than 5 employees.
Write SQL: total sales per month.
Write SQL: find the second highest salary.
Write SQL: count distinct cities in a table.
Write SQL: show percentage of total for each dept.
Write SQL: grades with average > 80.
Write SQL: MIN and MAX per subject.
Write SQL using GROUP_CONCAT.
Section C — Write Programs (3 marks each)
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}")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;
-- 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;
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;
SELECT COALESCE(Department,"ALL") AS Dept, COALESCE(Job,"ALL JOBS") AS Job, SUM(Salary) AS TotalSal FROM Employees GROUP BY Department, Job WITH ROLLUP;
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}")-- 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;
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}%)")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;
-- 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;Network Types
10.1Network Topologies
10.2Switch: 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.
• 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)
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.
- 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)
- (a) All rows from both tables
- (b) Only matching rows from both tables
- (c) All left + matching right
- (d) All right + matching left
- (a) Only matching rows
- (b) All left rows + matching right (NULL for non-matches)
- (c) All right rows
- (d) Cartesian product
- (a) INNER
- (b) LEFT
- (c) RIGHT
- (d) FULL OUTER
- (a) INNER JOIN
- (b) NATURAL JOIN
- (c) CROSS JOIN
- (d) LEFT JOIN
- (a) Different tables
- (b) Same table with alias
- (c) Related tables
- (d) Foreign keys
- (a) All columns
- (b) Columns with same name and type
- (c) Primary keys only
- (d) Foreign keys only
- (a) Use DISTINCT
- (b) Use USING(col) to specify join column
- (c) Use WHERE
- (d) Use HAVING
- (a) INNER JOIN
- (b) LEFT JOIN with WHERE manager IS NULL
- (c) CROSS JOIN
- (d) RIGHT JOIN
- (a) <, > operators
- (b) = operator
- (c) LIKE
- (d) BETWEEN
- (a) INNER JOIN
- (b) LEFT JOIN
- (c) CROSS JOIN
- (d) NATURAL JOIN
Section B — Predict the Output (2 marks each)
Write INNER JOIN: students with their marks.
Write LEFT JOIN: all students even without marks.
Write SELF JOIN: find employee and their manager.
Write query to find students with no marks.
Write a 3-table join.
CROSS JOIN: how many rows from 5×3 tables?
Write FULL OUTER JOIN in MySQL (simulation).
Write query: common students in two classes.
Write JOIN with aggregate.
Difference between ON and WHERE in a LEFT JOIN.
Section C — Write Programs (3 marks each)
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"])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}")-- 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);
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;
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
)
);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;
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)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;
-- 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;
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;
Transmission Modes
11.1Receiver: 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.
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).
• 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.
- 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)
- (a) pymysql
- (b) mysql
- (c) connector
- (d) dbconn
- (a) All rows
- (b) First row as tuple
- (c) Row count
- (d) Column names
- (a) cursor.run()
- (b) cursor.query()
- (c) cursor.execute()
- (d) cursor.sql()
- (a) Close connection
- (b) Send query
- (c) Save DML changes permanently
- (d) Rollback
- (a) f-strings
- (b) str.format()
- (c) %s placeholders
- (d) String concatenation
- (a) One row
- (b) Last row
- (c) List of all remaining rows
- (d) Row count
- (a) Mouse cursor
- (b) Object for executing SQL and navigating results
- (c) Database connection
- (d) SQL file
- (a) Slow queries
- (b) Unsanitised user input in SQL strings
- (c) Too many rows
- (d) Wrong datatype
- (a) Columns updated
- (b) Rows affected
- (c) Table size
- (d) 0
- (a) mysql.open()
- (b) mysql.connector.connect(host=...,user=...,password=...,database=...)
- (c) mysql.login()
- (d) connector.start()
Section B — Predict the Output (2 marks each)
Write Python code to connect to MySQL.
Write code to fetch and display all students.
Write code to insert a student record.
Write safe UPDATE with parameterized query.
What does cursor.description contain?
Write DELETE with parameter.
How to get column names from cursor?
What is the danger of string formatting in SQL?
Write code to fetch one row.
Write proper connection close code.
Section C — Write Programs (3 marks each)
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()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()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()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()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()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()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])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()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()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()TCP/IP Protocol Stack
12.1HTTPS — 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).
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).
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.
- 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)
- (a) Bus
- (b) Ring
- (c) Star
- (d) Mesh
- (a) Class A
- (b) Class B
- (c) Class C
- (d) Class D
- (a) IP to MAC
- (b) Domain names to IP addresses
- (c) HTTP to HTTPS
- (d) URLs to paths
- (a) HTTP
- (b) FTP
- (c) SMTP
- (d) POP3
- (a) Physical
- (b) Data Link
- (c) Transport
- (d) Application
- (a) Hub
- (b) Switch
- (c) Router
- (d) Repeater
- (a) Same
- (b) TCP: reliable, connection-oriented; UDP: fast, connectionless
- (c) UDP is reliable
- (d) TCP is faster
- (a) Signal strength
- (b) Maximum data transfer rate of a channel
- (c) Network delay
- (d) IP range
- (a) Virtual Public Network
- (b) Very Private Node
- (c) Virtual Private Network
- (d) Verified Public Node
- (a) IP address type
- (b) Divides IP into network and host portions
- (c) Password
- (d) Router IP
Section B — Predict the Output (2 marks each)
What is the OSI model and its layers?
Difference between LAN, MAN and WAN.
What is the full form and use of HTTPS?
What is MAC address?
Explain the TCP 3-way handshake.
What is an IP address? Differentiate IPv4 and IPv6.
What are the functions of a router?
What is the difference between a hub and a switch?
Explain FTP and its use.
What is latency/ping?
Section C — Write Programs (3 marks each)
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")}")# 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()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")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}")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)")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)}")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}")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}")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']}")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)Security Threats & Defences
13.1Session 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.
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.
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.
- 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)
- (a) Malware type
- (b) Fake emails/sites to steal credentials
- (c) DDoS attack
- (d) SQL injection
- (a) Disk Denial of Service
- (b) Distributed Denial of Service
- (c) Data Denial of Service
- (d) Double Denial of Service
- (a) Antivirus
- (b) Firewall
- (c) VPN
- (d) Router
- (a) Tracks keystrokes
- (b) Encrypts files and demands payment
- (c) Steals passwords
- (d) Slows computer
- (a) 80
- (b) 8080
- (c) 443
- (d) 21
- (a) Password only
- (b) Two passwords
- (c) Password + another factor (OTP/biometric)
- (d) Biometric only
- (a) Malware
- (b) Phishing
- (c) Encryption
- (d) Man-in-the-middle
- (a) Weak passwords
- (b) Unsanitised database queries
- (c) Outdated antivirus
- (d) Open ports
- (a) Network traffic
- (b) Keystrokes typed by user
- (c) Screen images
- (d) File accesses
- (a) Only letters
- (b) Only numbers
- (c) Mix of uppercase, lowercase, numbers, symbols, 8+ chars
- (d) Easy to remember words
Section B — Predict the Output (2 marks each)
What is malware? Name 5 types.
What is the CIA triad in cyber security?
What is a firewall and its types?
Explain social engineering.
What is encryption and how does it protect data?
What is a VPN and how does it work?
Explain man-in-the-middle attack.
What is a digital certificate?
What is zero-day vulnerability?
What is the principle of least privilege?
Section C — Write Programs (3 marks each)
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}")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()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"]))# 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"))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']}")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}")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]}")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}")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)")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)Relational Database Model
14.11. 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.
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.
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
- 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)
- (a) Splitting a hard drive
- (b) Gap between those with/without technology access
- (c) Digital copyright
- (d) Network partition
- (a) Privacy loss
- (b) Cybercrime
- (c) Global communication and information access
- (d) E-waste
- (a) Electronic newspapers
- (b) Discarded electronic devices
- (c) Digital garbage
- (d) Error messages
- (a) Costs more
- (b) Source code is freely available and modifiable
- (c) Is always better
- (d) Requires license
- (a) Ideas
- (b) Facts
- (c) Expressions (code, text, images)
- (d) Hardware
- (a) Fast Open Source Software
- (b) Free and Open Source Software
- (c) Free Operating System Software
- (d) File Open Source Standard
- (a) Job displacement
- (b) Bias in algorithms
- (c) Faster computation
- (d) Privacy invasion
- (a) Keeping data fast
- (b) Right of individuals to control their personal data
- (c) Encrypting all data
- (d) Making data public
- (a) Use more power
- (b) Reduce environmental impact of computing
- (c) Increase processing speed
- (d) Use green-coloured computers
- (a) Is easier to detect only
- (b) Is only a physical crime
- (c) Includes copying digital content without credit
- (d) Has no consequences
Section B — Predict the Output (2 marks each)
What are 4 positive and 4 negative impacts of IT on society?
Explain cyber ethics.
What is net neutrality?
What is the IT Act 2000 (India)?
Explain digital footprint.
What is assistive technology?
What is cyberbullying and prevention?
What is intellectual property in computing?
What is the impact of social media on society?
What are the ethical issues of AI?
Section C — Write Programs (3 marks each)
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")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")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₂")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}")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}")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}")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.")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}")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}")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.")SQL Command Categories
15.1CREATE 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.
INSERT INTO student VALUES (101,'Aarav',85,'A');INSERT INTO student (roll,name) VALUES (102,'Priya');UPDATE studentSET marks = marks + 5WHERE grade = 'C';DELETE FROM student WHERE marks < 33;DELETE FROM student; — deletes all rows (use TRUNCATE instead).⚠️ Always use WHERE in UPDATE and DELETE!
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- 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)
- (a) GROUP BY
- (b) HAVING
- (c) ORDER BY
- (d) WHERE
- (a) First 5 rows
- (b) Rows 6-10
- (c) Rows 11-15
- (d) Last 5 rows
- (a) TODAY()
- (b) NOW()
- (c) CURDATE()
- (d) DATE()
- (a) Names starting with A
- (b) Any 2-char string starting with A
- (c) Names with A anywhere
- (d) Names ending with A
- (a) Same
- (b) UNION removes duplicates; UNION ALL keeps all rows
- (c) UNION is faster
- (d) UNION ALL is newer
- (a) = NULL
- (b) == NULL
- (c) IS NULL
- (d) LIKE NULL
- (a) 10 to 20 exclusive
- (b) 10 and 20 inclusive
- (c) 11 to 19
- (d) None of these
- (a) Insert one row
- (b) Copy rows from one table to another
- (c) Update and insert
- (d) Delete and insert
- (a) INNER JOIN
- (b) OUTER JOIN
- (c) SIDE JOIN
- (d) CROSS JOIN
- (a) Explains the database
- (b) Shows query execution plan
- (c) Lists columns
- (d) Shows indexes only
Section B — Predict the Output (2 marks each)
Write SQL for pagination (page 2, 10 per page).
Write SQL: students enrolled this year.
Write SQL using CASE for conditional logic.
Write SQL: names starting with a vowel.
Write SQL: update multiple rows with CASE.
Write SQL: last 30 days records.
Write SQL: combine results from two tables.
Write SQL: find duplicate emails.
Write SQL: top student per class.
Write SQL: running total using variable.
Section C — Write Programs (3 marks each)
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;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;
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;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;
-- 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;
-- 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;
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;
-- 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;
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;
-- 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"
Python-MySQL Connectivity
16.1import mysql.connectormydb = 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.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'))
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.colFROM table_a aINNER JOIN table_b bON a.id = b.id;
🐍 Python Runner — SQL & MySQL Programs
16.2- 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)
- (a) Tuple
- (b) String
- (c) List
- (d) Set
- (a) NULL values
- (b) Duplicate rows from result
- (c) Empty strings
- (d) Indexed rows
- (a) Network
- (b) Session
- (c) Transport
- (d) Data Link
- (a) except
- (b) error
- (c) raise
- (d) throw
- (a) Network Interface Card
- (b) New Internet Connection
- (c) Network IP Configuration
- (d) None
- (a) SIZE()
- (b) LEN()
- (c) LENGTH()
- (d) COUNT()
- (a) 8
- (b) 10
- (c) 12
- (d) 14
- (a) path
- (b) sys
- (c) os
- (d) filesystem
- (a) Repeating groups
- (b) Partial dependencies
- (c) Transitive dependencies
- (d) NULL values
- (a) 192.168.1.1
- (b) 2001:db8::1
- (c) 127.0.0.1
- (d) 10.0.0.1
Section B — Predict the Output (2 marks each)
Output?
def mystery(lst):
return [x**2 for x in lst if x%2==0]
print(mystery([1,2,3,4,5,6]))Write SQL: find 3rd highest salary.
Output?
try:
d={"a":1}
print(d["b"])
except KeyError as e:
print(f"KeyError: {e}")
finally:
print("Done")What is output?
class Dog:
species="Canis"
def __init__(self,name): self.name=name
d=Dog("Rex")
print(d.name,Dog.species)Write SQL: count students per grade with HAVING.
Output?
s="Python Programming"
print(s[7:],s[:6].upper(),s.count("m"))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))Write SQL: students with marks in all subjects.
Output?
stack=[]
for x in [1,2,3,4,5]:
if x%2: stack.append(x)
while stack:
print(stack.pop(),end=" ")Ping vs traceroute: what is the difference?
Section C — Write Programs (3 marks each)
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()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()}")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")# 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)))-- 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;
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")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])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")]))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}")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())📝 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.