0% found this document useful (0 votes)
3 views33 pages

CBSE Python Functions Mastery

The document outlines the CBSE Class XII Computer Science curriculum focusing on Python functions, emphasizing their importance in programming through concepts like reusability, abstraction, and isolation. It includes detailed explanations of built-in, module, and user-defined functions, along with syntax rules, properties, and common errors. Additionally, it provides practical examples and exercises to reinforce understanding of function usage in Python.

Uploaded by

antasrao1234
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views33 pages

CBSE Python Functions Mastery

The document outlines the CBSE Class XII Computer Science curriculum focusing on Python functions, emphasizing their importance in programming through concepts like reusability, abstraction, and isolation. It includes detailed explanations of built-in, module, and user-defined functions, along with syntax rules, properties, and common errors. Additionally, it provides practical examples and exercises to reinforce understanding of function usage in Python.

Uploaded by

antasrao1234
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CBSE CLASS XII — COMPUTER SCIENCE 083

Unit 1B | Computational Thinking & Programming | 40 Marks

PYTHON FUNCTIONS
Complete Board Mastery · Layers 0–13 · 200+ Examples

150+ Code Examples · 30 Output Predictions · 30 MCQs · 20 Hard Qs · 15 Dry-Run Programs


All Comparison Tables · Every Error Type · Multiple Methods · Integration Programs
Target: 100 / 100
LAYER 0 — MENTAL FOUNDATION & CONCEPT ORIENTATION
0.1 The Problem Functions Solve
▶ Without Functions — The Pain ▶ Restaurant Recipe Card Analogy
• Same 5-line formula pasted 50× = 250 lines; one bug needs 50 R def make_pasta(): ← card has a name Params = ingredients list = inputs Args = chef's actual quantities today Def
fixes E
CI
told' return = send dish to table Local var = counter space while cooking Global var = master pantry stock READ
• No logic names — reader must trace every line to find intent P cook. You MUST CALL to produce output!
• Testing impossible — can't isolate one piece E

• Parallel development impossible on monolithic code


• Features grow exponentially; maintenance cost doubles each ▶ Three Design Principles
sprint
▸ SRP — Single Responsibility: one function = one job
▸ DRY — Don't Repeat Yourself: zero duplicate logic
▶ What Functions Provide ▸ KISS — Keep It Simple: 5–10 lines is ideal per function
▸ DRY — Write once, call N times — single source of truth
▸ Abstraction — Caller sees WHAT, not HOW — clean interfaces
▸ Isolation — Local scope: inside changes never break outside
▸ Testability — Known inputs → known outputs — unit testable
▸ Composition — f(g(x)) — build complex from simple primitives

0.2 Complete Visual Map


┌─────────────────────────────────────────────────────────────────────────────┐
│ PYTHON FUNCTIONS — UNIT 1B UNIVERSE │
└────────────────────────────┬────────────────────────────────────────────────┘
┌─────────────────┼─────────────────────────┐
┌─────▼──────┐ ┌──────▼──────┐ ┌────────────▼───────────┐
│ BUILT-IN │ │ MODULE │ │ USER-DEFINED (def) │
│print() │ │[Link]() │ │ ┌────────────────────┐ │
│len() int() │ │[Link]()│ │ │ PARAMETERS │ │
│abs() max() │ │[Link]() │ │ │ positional:def f(a)│ │
│min() sum() │ │[Link]()│ │ │ default: def f(a=5)│ │
│sorted() │ │[Link]() │ │ └────────┬───────────┘ │
│round() │ │[Link] │ │ │ │
└────────────┘ └─────────────┘ │ ┌────────▼───────────┐ │
│ │ RETURN VALUES │ │
EXECUTION ENGINE: │ │ single/tuple/None │ │
each call → new FRAME pushed on stack │ └────────┬───────────┘ │
return → frame POPPED (vars gone) │ │ │
LIFO: Last In, First Out │ ┌────────▼───────────┐ │
│ │ SCOPE │ │
CONNECTS TO: │ │ Local / Global │ │
1C Exception Handling: try in fns │ │ LEGB lookup │ │
1D File Handling: fns wrap file ops │ └────────────────────┘ │
1E Stack DS: call stack IS a stack └────────────────────────┘
Unit3 SQL: execute/commit are methods

0.3 One-Sentence Definitions — Exam Ready


Marks Write exactly this Keyword checklist
1m A function is a named, reusable block of code that performs a specific task. named · reusable · block · task
2m + It accepts input via parameters and returns output via return statement. parameters · return
3m + Syntax: def name(params): body; return value. + One complete working example. def · colon · indented · example
5m + All 3 types + scope (local/global) + flow of execution + full program 3 types · local/global · flow · code

LAYER 1 — THEORETICAL DEPTH


1.1 Three Types — Exhaustive Reference
Type Definition + 20 Examples Import? Key Limitation
Built-in Compiled in C; always available; fastest. Never Only ~70; cannot
print() len() input() int() float() str() bool() modify
list() dict() tuple() set() abs() max() min()
sum() round() sorted() reversed() range()
enumerate() zip() type() isinstance() id()
hash() hex() bin() oct() chr() ord() open()
vars() globals() locals() callable() dir()
Module Written in .py; stored in stdlib; explicit import. import 3rd-party: must install
math: sqrt ceil floor pow log sin cos factorial pi e gcd needed
random: randint random choice shuffle sample uniform seed
csv: writer reader DictWriter DictReader
pickle: dump load dumps loads
Type Definition + 20 Examples Import? Key Limitation
os: getcwd listdir [Link] [Link]
string: ascii_letters digits
sys: argv exit stdin stdout
time: time sleep strftime
User- Programmer-created with def keyword. None No built-in
defined def add(a,b) def greet(name) def is_prime(n) needed optimization; bugs
def factorial(n) def get_grade(marks) possible
def push(stack,item) def pop(stack)
def connect_db() def insert_student()
def safe_divide(a,b) def validate_age(n)
def word_count(text) def binary_search()
def export_csv() def bf_add() def menu()

1.2 Properties — With Proof and Violation


Property Rule Proof Violation
Reusability Define once; call infinitely def sq(x):return x*x → sq(3),sq(7),sq(100) Without: 3 lines × 100 calls = 300 duplicate lines
Local scope Each call gets fresh frame; locals die def f(): x=10; print(x) outside → NameError Without: global naming conflicts everywhere
on return
Def ≠ Execute def stores body; call runs it def f():print('X') → nothing; f() → X printed Students write def and wonder why nothing
prints
Positional bind Args bind L→R at call time def f(a,b,c):print(a,b,c) → f(1,2,3)=1 2 3 f(3,2,1) prints 3 2 1 — order matters!
Implicit None No/bare return → None to caller def g():pass; result=g() → result is None result=g() then use result → None causes errors
Default once Default computed at def time, not def f(x=2):return x**2 → created once for Mutable defaults (list) persist — major bug
call all calls
Independent frames Each call has own copy of locals fact(5) creates 5 independent frames Without: recursive fns overwrite each other
return exits Code after return never runs def f(): return 1; print('never') → Dead code after return = wasted lines; confuses
unreachable readers

1.3 Rules — Structural and Calling


▶ Structural Rules ▶ Calling Rules
▸ def before call — Must DEFINE before CALL in execution flow — ▸ Too many args — TypeError: takes 2 positional arguments but 3
NameError if violated given
▸ Name rules — Start: letter or _; Body: letters/digits/_; No ▸ Too few required — TypeError: missing 1 required positional
spaces; Not keyword argument: 'b'
▸ Colon mandatory — def name(): — missing colon → ▸ Keyword order — f(1,x=2) ✔ f(x=1,2) ✗ SyntaxError
SyntaxError ▸ Duplicate keyword — f(1,a=2) when a=param[0] → TypeError:
▸ Body indented — 4 spaces standard; all lines equal; mixed got multiple values
tab/space → TabError ▸ Unknown keyword — f(z=5) when no param z → TypeError:
▸ Defaults after positional — def f(a,b=5) ✔ def f(b=5,a) ✗ unexpected keyword
SyntaxError ▸ After return — Code after return = dead code; no error but never
▸ return in body — return outside def → SyntaxError: 'return' runs
outside function ▸ No global kw — x+=1 inside fn without global x →
▸ global before use — global x MUST precede x=value inside fn UnboundLocalError

LAYER 2 — SYNTAX MASTERY


2.1 Master Annotated Syntax Template
def function_name ( param1 , param2 , param3=default ) : ← HEADER
│ │ │ │ │ │ │
kw name positional positional opt value colon

'''Docstring — optional; first string literal in body'''


local_var = expression ← 4-space indent; ALL body lines same
return value ← optional; omit → returns None
return a, b, c ← multiple → packed as tuple

2.2 All 12 Valid Syntax Forms


Form Syntax Call Example Returns
1. No def hello(): print('Hi') hello() None (side effect only)
params,
no
return
2. def add(a,b): return a+b add(10,20) 30
Position
al +
return
3. Single def power(base,exp=2): return base**exp power(5) or power(2,10) 25 or 1024
Form Syntax Call Example Returns
default
4. def greet(name,msg='Hi',end='!'): greet('Rahul') None (prints)
Multiple print(msg,name+end)
defaults
5. All def box(w=10,h=5,d=3): return w*h*d box() or box(20) 150 or 300
defaults
6. def stats(lst): return min(lst),max(lst),sum(lst) a,b,c=stats([1,5,3]) tuple
Multiple
return
7. Tuple def pr(): return 1,2,3 r=pr(); r[0] r[1] (1,2,3) as tuple
unboxe
d
8. def inc(): global c; c+=1 inc(); inc() None; side-effect
Global
modify
9. def f(a,b,c): return a-b-c f(c=1,a=10,b=3) 6
Keywor
d call
10. def f(a,b,c=5): return a+b+c f(1,2) or f(1,b=2) 8
Mixed
call
11. def log(msg): print(msg); return log('done') None
Explicit
None
return
12. Full def full(a,b=2): full(3) or full(3,4) 5 or 7
produc '''Adds a+b.'''
tion return a+b

2.3 Invalid Syntax — 12 Cases with Exact Errors


Bad Code Error Root Cause Fix
def 2times(x): SyntaxError: invalid syntax Digit start def times2(x):
def my func(): SyntaxError: invalid syntax Space in name def my_func():
def add(a,b) SyntaxError: expected ':' No colon def add(a,b):
def f(b=5,a): SyntaxError: non-default arg follows Default before positional def f(a,b=5):
default
def f(): IndentationError Body not indented return 1 (4 spaces)
return 1
add(1,2,3) #add(a,b) TypeError: takes 2 args but 3 given Too many add(1,2)
add(1) #add(a,b) TypeError: missing 1 required arg 'b' Too few add(1,2)
f(a=1,2) SyntaxError: positional after keyword Order wrong f(1,2) or f(a=1,b=2)
f(1,a=1) #f(a,b) TypeError: multiple values for 'a' Arg given twice f(1,2) only
return 5 # outside fn SyntaxError: 'return' outside function Wrong placement Put inside def body
x+=1 #no global UnboundLocalError: local 'x' before assign Py treats as local global x first
import Math ModuleNotFoundError Case sensitive import math

2.4 Parameter Patterns — Every Combination


# DEFINITION FORMS # CALL FORMS for f8(a,b,c=3,d=4)
def f1(): pass f8(1,2) # c=3,d=4 defaults
def f2(a): pass f8(1,2,9) # c=9,d=4 one ovr
def f3(a,b): pass f8(1,2,9,8) # both overridden
def f4(a,b,c): pass f8(1,b=2) # keyword b
def f5(a=1): pass f8(1,2,d=8) # skip c give d
def f6(a=1,b=2): pass f8(a=1,b=2) # all keyword
def f7(a,b=2): pass
def f8(a,b,c=3,d=4): pass # RECEIVE MULTIPLE RETURNS
def f9(a,b): return a,b a,b = f9(1,2) # unpack 2
def f10(a,b,c): return a,b,c x,y,z = f10(1,2,3) # unpack 3
r = f9(1,2) # r=(1,2) tuple
x,_ = f9(1,2) # _ = discard
LAYER 3 — CODE LABORATORY: PROGRAMS 1–8
Programs 1–4: Foundation Patterns

Prog 1 — Zero-Knowledge: Minimal Function


# Minimal working function — 5 lines DRY RUN:
def greet(): L1: def greet() → stores fn object
print('Hello from a function!') L4: greet() called → new frame
body executes → print runs
greet() # → Hello from a function! frame destroyed → done
greet() # → Hello from a function! (reuse!) NOTE: callable infinite times
def ≠ call (critical concept)

Prog 2 — Parameters + Return + Dry Run


def add(a, b): # a, b = POSITIONAL params
result = a + b # result = LOCAL to this frame
return result # sends value back; frame destroyed

x=10; y=20
total = add(x, y) # x=10→a, y=20→b; get 30 back
print('Sum:', total) # → Sum: 30
print(add(3.5, 1.5)) # → 5.0 (floats work)
print(add('Hi', '!')) # → Hi! (strings — concatenation)
print(add([1,2],[3,4]))# → [1,2,3,4] (list concatenation!)
Line Code Global Scope add() Frame Output
1 def add(a,b): add=<fn> (not yet)
5 x=10; y=20 add,x=10,y=20 (not yet)
6 total=add(x,y) calling… a=10,b=20
2 result=a+b unchanged a=10,b=20,result=30
3 return result frame destroyed (a,b,result gone)
6 total=… add,x,y,total=30 destroyed
7 print(…) unchanged Sum: 30

Prog 3 — Default Parameters — All Scenarios


def power(base, exp=2): return base ** exp
def describe(name, age=17, city='Delhi', grade='A'):
return f'{name},{age}yr,{city},Grade:{grade}'

print(power(5)) # 25 (exp=2 default)


print(power(5,3)) # 125 (exp=3 override)
print(power(2,10)) # 1024
print(power(exp=3,base=2)) # 8 (keyword order swap)
print(power(base=3)) # 9 (keyword, exp=2 default)

print(describe('Rahul')) # 3 defaults used


print(describe('Priya',16)) # age overridden
print(describe('Arjun',grade='B+')) # skip city, give grade
print(describe('Meera',18,'Mumbai','A+')) # all given
print(describe('Dev',city='Pune')) # skip age, give city

Prog 4 — Multiple Return Values — 3 Methods


# METHOD A: tuple unpack # METHOD B: dict return
def minmax(lst): def circle(r):
return min(lst),max(lst) import math
lo,hi=minmax([3,1,7,5]) return {
# lo=1, hi=7 'area':round([Link]*r*r,3),
'perim':round(2*[Link]*r,3)}
def stats(lst): c=circle(5)
return min(lst),max(lst),sum(lst)//len(lst) print(c['area']) # 78.54
mn,mx,avg=stats([10,20,30])
# 10,30,20 # METHOD C: namedtuple style
def div_rem(a,b):
return a//b,a%b
q,r=div_rem(17,5) # 3,2

Programs 5–8: Scope, Flow, Exceptions, Modules

Prog 5 — Local vs Global — All 6 Scenarios


g = 100
def s1(): print(g) # READ global — no keyword needed → 100
def s2(): g=999; print(g) # SHADOW — new local; global g unchanged → 999
def s3(): global g; g+=1 # MODIFY global — keyword required; g→101
def s4(): # ⚠ TRAP: assign makes var LOCAL throughout fn
print(g) # ← UnboundLocalError! (g=50 below makes it local)
g = 50 # Python sees this → x is local in WHOLE fn
def s5(): # Mix: one local, one global
x = 'local'
print(x, g) # 'local' + global g
def s6(): # global keyword CREATES var if it doesn't exist
global new_var
new_var = 'born here' # new_var now at global scope

s1() # → 100
s2() # → 999 (global g still 100!)
s3() # g becomes 101
#s4() → UnboundLocalError
s5() # → local 101
s6() # new_var created globally

Prog 6 — Flow of Execution — Critical


print('A') # L1: runs E 1→A 2→L3-L6 STORED (no output) 3→L8-L9 STORED (no output) 4→B 5→alpha() → D 6→alpha calls beta() →
X
E
FINAL: A B D E F G ⚠ def lines are ALWAYS SKIPPED until function is explicitly called!
def alpha(): # L3: STORED
C
print('D') O
beta() R
print('F') D
E
R
def beta(): # L8: STORED
print('E')

print('B') # L11: runs


alpha() # L12: NOW executes
print('G') # L13: runs

Prog 7 — Exception Handling Inside Functions


def safe_divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print(f'Error: cannot divide {a} by 0'); return None
except TypeError as e:
print(f'Type error: {e}'); return None
finally: # ALWAYS runs — even with return!
print(f' [done: {a}/{b}]')

print(safe_divide(10,2)) # → 5.0 [done:10/2] 5.0


print(safe_divide(10,0)) # Error msg [done:10/0] None
print(safe_divide(10,'x')) # Type err [done:10/x] None

Prog 8 — math + random — Complete CBSE Reference


import math, random

# ── math ─────────────────────────────────────────────────────────
print([Link](144)) # → 12.0 (ALWAYS float — never int!)
print([Link](4.1)) # → 5 (smallest int ≥ x)
print([Link](-4.9)) # → -4 ⚠ TRAP: ceil goes UP not toward 0
print([Link](4.9)) # → 4 (largest int ≤ x)
print([Link](-4.1)) # → -5 ⚠ TRAP: floor goes DOWN
print(round(4.5)) # → 4 ⚠ TRAP: banker's rounding to even!
print(round(5.5)) # → 6 (5.5 → 6, both even endpoint: 6)
print(round(3.14159,3)) # → 3.142
print([Link](0)) # → 1 (0! = 1 by definition)
print([Link](2,10)) # → 1024.0 (float; 2**10 gives int 1024)
print([Link](100,10)) # → 2.0 (log base 10)
print([Link](48,18)) # → 6
print([Link]) # → 3.141592653589793

# ── random ───────────────────────────────────────────────────────
print([Link](1,6)) # → 1..6 INCLUSIVE both ends (CBSE dice)
print([Link]()) # → 0.0 <= x < 1.0 (upper EXCLUDED)
print([Link](1,10)) # → float 1.0–10.0
lst=['a','b','c','d']
print([Link](lst)) # → one random element
print([Link](lst,2)) # → 2 unique (without replacement)
[Link](lst) # → in-place; returns None
[Link](42) # → fixes sequence for reproducibility
LAYER 3 — CODE LABORATORY: PROGRAMS 9–15
Programs 9–11: Modular, Stack, File-Integrated

Prog 9 — Modular Student System (Function Composition)


def get_pct(marks): return sum(marks)/len(marks)
def get_grade(p): return 'A+' if p>=90 else 'A' if p>=80 else 'B+' if p>=70 else 'B' if p>=60 else 'C'
if p>=33 else 'F'
def is_pass(p): return p >= 33
def get_rank(p): return 'I' if p>=60 else 'II' if p>=50 else 'III' if p>=33 else 'FAIL'

def print_report(name, marks):


p = get_pct(marks) # function composition: fn calls fn
print(f'{name:<16} Pct:{p:5.1f}% Grade:{get_grade(p):<3} Div:{get_rank(p):4} {"PASS" if is_pass(p)
else "FAIL"}')

students = [('Rahul Sharma',[85,78,92,88,76,90]),('Priya Singh',[45,50,38,55,60,48]),


('Arjun Mehta', [22,28,30,25,18,15]),('Sunita Rao', [95,98,92,97,99,100])]
print(f'{'NAME':<16} {'PCT':>7} GR DIV STATUS'); print('-'*52)
for name,marks in students: print_report(name,marks)
# Rahul Sharma Pct: 84.8% Grade:A Div:I PASS
# Priya Singh Pct: 49.3% Grade:C Div:III PASS
# Arjun Mehta Pct: 23.0% Grade:F Div:FAIL FAIL
# Sunita Rao Pct: 96.8% Grade:A+ Div:I PASS

Prog 10 — Stack Implementation — 3 Methods


# METHOD A: Global stack # METHOD B: Parameter stack # METHOD C: Menu-driven
stack=[] def push2(s,x): [Link](x) def stack_menu():
def push(x): def pop2(s): s=[]
[Link](x) return [Link]() if s else None while True:
def pop(): def peek2(s): ch=input('[Link] [Link]
if not stack: return s[-1] if s else None [Link] [Link] [Link]: ')
print('UNDERFLOW!');return if ch=='1':
None # TEST METHOD A: push2(s,input('Val:'))
return [Link]() push(10); push(20); push(30) elif ch=='2':
def peek(): display() # [30,20,10] print(pop2(s))
return stack[-1] if stack print(peek()) # 30 elif ch=='3':
else None pop(); pop() print(peek2(s))
def is_empty(): return pop() # UNDERFLOW! elif ch=='4':
len(stack)==0 print(list(reversed(s)))
def display(): elif ch=='5': break
# COMPLEXITY:
print('Stack:',list(reversed(st # push: O(1) amortized
ack))) # pop: O(1) always
# peek: O(1) always

Prog 11 — Binary + CSV + SQL — Complete CRUD


import pickle, csv; DAT='[Link]'; CSV='[Link]'

# ── BINARY FILE CRUD ──────────────────────────────────────────────────


def bf_add(roll,name,marks):
with open(DAT,'ab') as f: [Link]({'r':roll,'n':name,'m':marks},f)

def bf_all():
out=[]
try:
with open(DAT,'rb') as f:
while True:
try: [Link]([Link](f))
except EOFError: break # normal end of pickle stream
except FileNotFoundError: pass
return out

def bf_search(roll): return next((r for r in bf_all() if r['r']==roll),None)


def bf_delete(roll): _overwrite([r for r in bf_all() if r['r']!=roll])
def bf_update(roll,m):
recs=bf_all()
for r in recs:
if r['r']==roll: r['m']=m
_overwrite(recs)
def _overwrite(recs):
with open(DAT,'wb') as f:
for r in recs: [Link](r,f)

# ── CSV EXPORT ──────────────────────────────────────────────────────


def export_csv():
recs=bf_all()
with open(CSV,'w',newline='') as f:
w=[Link](f)
[Link](['Roll','Name','Marks']) # header first
[Link]([[r['r'],r['n'],r['m']] for r in recs])
print(f'Exported {len(recs)} records.')

# ── SQL CRUD ────────────────────────────────────────────────────────


import [Link]
DB=dict(host='localhost',user='root',password='',database='school')
def con(): return [Link](**DB)

def sql_insert(roll,name,marks):
c=con(); cur=[Link]()
[Link]('INSERT INTO student VALUES(%s,%s,%s)',(roll,name,marks))
[Link](); print([Link],'inserted.'); [Link]()

def sql_select(where=None):
c=con(); cur=[Link]()
[Link]('SELECT * FROM student'+(f' WHERE {where}' if where else ''))
rows=[Link](); [Link](); return rows

def sql_update(roll,marks):
c=con(); cur=[Link]()
[Link]('UPDATE student SET marks=%s WHERE roll=%s',(marks,roll))
[Link](); print([Link],'updated.'); [Link]()

def sql_delete(roll):
c=con(); cur=[Link]()
[Link]('DELETE FROM student WHERE roll=%s',(roll,))
[Link](); print([Link],'deleted.'); [Link]()

Programs 12–15: Integration + Complete Systems

Prog 12 — Text File — All 5 CBSE Operations


def words_with_hash(fname):
with open(fname,'r') as f:
for line in f:
if [Link](): print('#'.join([Link]().split()))

def count_lines_words_chars(fname):
lines=words=chars=0
with open(fname,'r') as f:
for line in f:
lines+=1; words+=len([Link]()); chars+=len(line)
return lines,words,chars

def count_vowcons(fname):
v=co=0
with open(fname,'r') as f:
for ch in [Link]():
if [Link]():
v+=1 if [Link]() in 'aeiou' else 0
co+=1 if [Link]() not in 'aeiou' else 0
return v,co

def remove_a_lines(src,dst):
with open(src,'r') as fi, open(dst,'w') as fo:
count=sum(1 for line in fi if 'a' not in [Link]() and not [Link](line))
print(f'Lines written to {dst}.')

def copy_uppercase(src,dst):
with open(src,'r') as fi, open(dst,'w') as fo:
[Link]([Link]().upper())

# Create test file + run all ops:


with open('[Link]','w') as f: [Link]('The quick brown fox\njumps over the lazy dog\nPython is fun')
words_with_hash('[Link]') # → The#quick#brown#fox etc.
print(count_lines_words_chars('[Link]')) # → (3, 12, 52)
print(count_vowcons('[Link]')) # → (12, 22)
remove_a_lines('[Link]','[Link]') # → Lines written
copy_uppercase('[Link]','[Link]')

Prog 13 — CSV DictWriter + DictReader


import csv; FILE='[Link]'
FIELDS=['UserID','Password','Name','Email']

def create(users): # users = list of dicts


with open(FILE,'w',newline='') as f:
w=[Link](f,fieldnames=FIELDS)
[Link]() # writes header row
[Link](users) # writes all records
print(f'{len(users)} records written.')

def read_all():
try:
with open(FILE,'r') as f:
return list([Link](f)) # auto-uses header as keys
except FileNotFoundError: return []

def search(uid): return next((r for r in read_all() if r['UserID']==uid),None)


def delete_user(uid): _save([r for r in read_all() if r['UserID']!=uid])
def update_pwd(uid,pwd):
rows=read_all()
for r in rows:
if r['UserID']==uid: r['Password']=pwd
_save(rows)
def _save(rows):
with open(FILE,'w',newline='') as f:
w=[Link](f,fieldnames=FIELDS)
[Link](); [Link](rows)

create([{'UserID':'r01','Password':'pass123','Name':'Rahul','Email':'r@[Link]'},
{'UserID':'p02','Password':'secret','Name':'Priya','Email':'p@[Link]'}])
print(search('p02')) # → {'UserID':'p02','Password':'secret','Name':'Priya',...}
update_pwd('r01','newpass')
delete_user('p02')

Prog 14 — Complete Integration: All Units in One


import pickle,csv; LOG=[] # LOG = operation stack

def push_log(op): [Link](op)


def pop_log(): return [Link]() if LOG else None
def show_log(): [print(f' {i+1}. {h}') for i,h in enumerate(reversed(LOG))]

def bf_add(fname,rec):
try:
with open(fname,'ab') as f: [Link](rec,f)
push_log(f'ADD roll={[Link]("r")}'); return True
except Exception as e: print('Error:',e); return False

def bf_all(fname):
out=[]
try:
with open(fname,'rb') as f:
while True:
try: [Link]([Link](f))
except EOFError: break
except FileNotFoundError: pass
return out

def export_csv(fname,csvname):
recs=bf_all(fname)
with open(csvname,'w',newline='') as f:
w=[Link](f); [Link](['Roll','Name','Marks'])
[Link]([[r['r'],r['n'],r['m']] for r in recs])
push_log(f'CSV_EXPORT {len(recs)} recs to {csvname}')

def menu():
DAT='[Link]'
while True:
print('\[Link] [Link] [Link] CSV [Link] [Link]-log [Link]')
ch=input('> ')
if ch=='1':
try:
r=int(input('Roll:')); n=input('Name:'); m=float(input('Marks:'))
bf_add(DAT,{'r':r,'n':n,'m':m})
except ValueError: print('Invalid — numbers required!')
elif ch=='2': [print(x) for x in bf_all(DAT)]
elif ch=='3': export_csv(DAT,'[Link]')
elif ch=='4': show_log()
elif ch=='5': print('Undone:',pop_log())
elif ch=='6': break
menu()

Prog 15 — Recursive Functions — 5 Classic Implementations


# 1. Factorial — iterative vs recursive comparison
def fact_iter(n): # O(n) time, O(1) space
r=1
for i in range(2,n+1): r*=i
return r

def fact_rec(n): # O(n) time, O(n) space (call stack!)


if n<=1: return 1 # BASE CASE — must always have this
return n*fact_rec(n-1) # RECURSIVE CASE

# 2. Fibonacci — memoized vs naive


_fib_cache={}
def fib_memo(n):
if n in _fib_cache: return _fib_cache[n]
if n<=1: return n
_fib_cache[n]=fib_memo(n-1)+fib_memo(n-2)
return _fib_cache[n]

# 3. Sum of digits
def sum_digits(n): return n if n<10 else n%10+sum_digits(n//10)
print(sum_digits(1234)) # 10

# 4. Power
def power_rec(base,exp): return 1 if exp==0 else base*power_rec(base,exp-1)
print(power_rec(2,10)) # 1024

# 5. GCD — Euclidean
def gcd(a,b): return a if b==0 else gcd(b,a%b)
print(gcd(48,18)) # 6

print(fact_iter(10),fact_rec(10)) # 3628800 3628800 (same result)


print([fib_memo(i) for i in range(10)]) # [0,1,1,2,3,5,8,13,21,34]
150+ SHORT EXAMPLES — Every Concept, Every Pattern
Section A: Built-in Functions — 50 Micro-Examples
# TYPE CONVERSION (12 examples)
int('42')=42 int(3.9)=3 int(-3.9)=-3 int('3.14')→ValueError
float('3.14')=3.14 str(100)='100' bool(0)=False bool('')=False
bool([])=False bool(None)=False bool(1)=True bool('0')=True # ⚠ non-empty!
bool(' ')=True # ⚠ space is truthy! bool([0])=True # non-empty list!
list((1,2,3))=[1,2,3] tuple([1,2,3])=(1,2,3) list('abc')=['a','b','c']
set([1,2,2,3])={1,2,3} dict([('a',1)])={'a':1}

# MATH (12 examples)


abs(-15)=15 abs(-3.7)=3.7 max(3,1,7)=7 max([3,1,7])=7
min(3,1,7)=1 min('abc')='a' sum([1,2,3,4,5])=15 sum(range(101))=5050
round(3.14159,2)=3.14 round(2.5)=2 ⚠ round(3.5)=4 ⚠ round(0.5)=0 ⚠
pow(2,10)=1024 divmod(17,5)=(3,2) hex(255)='0xff' bin(10)='0b1010'
oct(8)='0o10' chr(65)='A' ord('A')=65 abs(complex(3,4))=5.0

# SEQUENCE (12 examples)


len('hello')=5 len([1,2,3])=3 len({})=0 len(())=0
sorted([3,1,7])=[1,3,7] sorted([3,1,7],reverse=True)=[7,3,1]
sorted('hello')=['e','h','l','l','o'] sorted(['b','a','c'])=['a','b','c']
list(reversed([1,2,3]))=[3,2,1] # reversed() returns ITERATOR not list!
list(range(5))=[0,1,2,3,4] list(range(2,10,2))=[2,4,6,8]
list(enumerate(['a','b','c']))=[(0,'a'),(1,'b'),(2,'c')]
list(zip([1,2],[3,4]))=[(1,3),(2,4)] ''.join(['h','i'])='hi'

# TYPE & IDENTITY (8 examples)


type(42)=<class 'int'> type('hi')=<class 'str'> type([1])=<class 'list'>
isinstance(42,int)=True isinstance(42,(int,float))=True isinstance('hi',str)=True
callable(print)=True callable(42)=False
id(42) # memory address hasattr([1],'append')=True

# STRING METHODS called as functions (6 examples)


'Hello World'.lower()='hello world' 'hello'.upper()='HELLO'
' hello '.strip()='hello' 'a,b,c'.split(',')=['a','b','c']
','.join(['a','b','c'])='a,b,c' 'hello'.replace('l','L')='heLLo'

Section B: User-Defined — 50 Short Programs


# 1. even/odd 2. palindrome 3. count vowels
def is_even(n): return n%2==0
def is_pal(s): return s==s[::-1]
def vowels(s): return sum(1 for c in [Link]() if c in 'aeiou')

# 4. prime check 5. count digits 6. digit sum


def is_prime(n): return n>1 and all(n%i!=0 for i in range(2,int(n**0.5)+1))
def ndigits(n): return len(str(abs(n)))
def dsum(n): return sum(int(d) for d in str(abs(n)))

# 7. factorial iter 8. fibonacci 9. gcd/lcm


def fact(n): r=1; [r:=r*i for i in range(2,n+1)]; return r
def fib(n): a,b=0,1; [a:=b-(a:=a-b) for _ in range(n)]; return a
def gcd(a,b): return a if b==0 else gcd(b,a%b)
def lcm(a,b): return a*b//gcd(a,b)

# 10. reverse string 11. title case 12. word count


def rev(s): return s[::-1]
def titlecase(s): return ' '.join([Link]() for w in [Link]())
def wcount(s): return len([Link]())

# 13. max in list 14. min without min() 15. list sum
def mymax(lst): return max(lst[0],mymax(lst[1:])) if len(lst)>1 else lst[0]
def mymin(lst): m=lst[0]; [m:=x for x in lst if x<m]; return m
def mysum(lst): return 0 if not lst else lst[0]+mysum(lst[1:])

# 16. temp convert 17. BMI calc 18. grade fn


def c2f(c): return c*9/5+32
def bmi(w,h): b=w/h**2; return b,('Under' if b<18.5 else 'Normal' if b<25 else 'Over')
def grade(p): return 'A+' if p>=90 else 'A' if p>=80 else 'B' if p>=60 else 'C' if p>=33 else 'F'

# 19. even nums list 20. primes list 21. squares dict
def evens(n): return [x for x in range(n) if x%2==0]
def primes(n): return [x for x in range(2,n) if is_prime(x)]
def sq_dict(n): return {x:x*x for x in range(1,n+1)}
# 22. char frequency 23. binary search 24. bubble sort
def cfreq(s): return {c:[Link](c) for c in set(s)}
def bsearch(lst,t): lo,hi=0,len(lst)-1; [None for _ in [None] if lo<=hi and (lo:=(lo+hi)//2 if
lst[(lo+hi)//2]!=t else -1)>=0]; return -1
def bsort(lst): lst=[*lst]; [lst.__setitem__(j,lst[j+1]) or lst.__setitem__(j+1,lst[j]) for i in
range(len(lst)) for j in range(len(lst)-i-1) if lst[j]>lst[j+1]]; return lst

# 25. power sets 26. flatten list 27. unique list


def mypower(b,e): return 1 if e==0 else b*mypower(b,e-1)
def flatten(lst): return [x for sub in lst for x in (flatten(sub) if isinstance(sub,list) else [sub])]
def unique(lst): return list([Link](lst))

# TESTS:
print(is_even(4),is_pal('madam'),vowels('Hello World')) # True True 3
print(is_prime(17),ndigits(12345),dsum(999)) # True 5 27
print(gcd(48,18),lcm(4,6)) # 6 12
print(rev('Python'),wcount('hello world foo')) # nohtyP 3
print(c2f(100),bmi(70,1.75),grade(87)) # 212.0 (22.9,'Normal') A
print(primes(20)) # [2,3,5,7,11,13,17,19]
print(cfreq('banana')) # {'b':1,'a':3,'n':2}
print(flatten([[1,[2,3]],[4,[5,[6]]]])) # [1,2,3,4,5,6]

Section C: Scope Patterns — 25 Examples


# PATTERN 1-5: Read global — all safe, no keyword
x=10; def f1(): print(x) # → 10 (reads global)
y=[1,2]; def f2(): print(y[0]) # → 1 (reads global list item)
S='hi'; def f3(): return [Link]() # → 'HI' (uses global)
D={'k':5}; def f4(): return D['k'] # → 5 (reads global dict)
def f5(): return x+1 if x else 0 # → 11 (uses global in expression)

# PATTERN 6-10: Write global — keyword required


c=0; def inc(): global c; c+=1; return c # ✔ correct way
lst=[]; def add(v): global lst; [Link](v) # ✔ rebind: needs global
def reset(): global c,lst; c=0; lst=[] # multiple globals in one statement
def toggle(): global flag; flag=not flag # boolean toggle
name=''; def set_name(n): global name; name=n # string update

# PATTERN 11-15: Common traps


n=10
def bad1(): print(n); n=20 # ✗ UnboundLocalError (n=20 makes n local in whole fn)
def good1(): global n; print(n); n=20 # ✔ reads then modifies global
def bad2(): return n+1; n=5 # ✗ n=5 AFTER return — n still local! dead code
def scope_shadow(): n=99; print(n) # → 99 (local shadows global; global n=10 safe)
def reads_after(): global m; m=50 # ✔ creates global m even if m didn't exist before

# PATTERN 16-20: Mutable globals — no keyword for mutation!


items=[]; def append_item(x): [Link](x) # ✔ no global needed — mutation not rebind
scores={}; def record(k,v): scores[k]=v # ✔ dict update — no global needed
data=[1,2,3]; def clear(): [Link]() # ✔ .clear() mutates, not rebind
def replace(): global data; data=[9,8,7] # ✔ but this REBINDS — needs global!
# KEY RULE: mutation(append/clear/update) ≠ rebind (=); only rebind needs global

# PATTERN 21-25: LEGB in action


x='G'
def outer(): x='E'; inner = lambda: x; print(inner()) # → 'E' (E before G)
def check_legb():
x='L' # LOCAL x
print(x) # → 'L' (L found first — never reaches G)
check_legb() # → L
del x; print(len) # 'len' found in BUILTIN scope

Section D: Return Patterns — 20 Examples


# 1. Return int 2. Return float 3. Return string
def area(r): return 3.14*r*r
def quadrant(x,y): return ('I' if x>0 and y>0 else 'II' if x<0 and y>0 else 'III' if x<0 else 'IV')
def sign(n): return 'pos' if n>0 else 'neg' if n<0 else 'zero'

# 4. Return bool 5. Return list 6. Return dict


def contains(lst,x): return x in lst
def evens_to(n): return [x for x in range(n+1) if x%2==0]
def freq(s): return {c:[Link](c) for c in set(s)}

# 7. Return tuple (2) 8. Return tuple (3) 9. Unpack


def minmax(lst): return min(lst),max(lst)
def div_rem_sign(a,b): return a//b, a%b, 'pos' if a//b>=0 else 'neg'
q,r,s = div_rem_sign(17,5) # q=3,r=2,s='pos'

# 10. Return None (explicit) 11. Return None (implicit) 12. Bare return
def no_return(): x=10 # implicit None return
def explicit_none(): return None # same result
def early_exit(lst): return if not lst; return lst[0] # bare return exits early

# 13. Return function result 14. Return conditional


def apply(f,x): return f(x) # higher-order: pass fn as arg
def safe_sqrt(x): return x**0.5 if x>=0 else None

# 15. Chain returns 16. Return from loop 17. Return generator (adv)
def double(x): return x*2
def quad(x): return double(double(x)) # quad(3)=12
def first_gt(lst,t): return next((x for x in lst if x>t),None)

# 18-20: Multi-return patterns


def swap(a,b): return b,a # swap via multiple return
def minmax_avg(lst): return min(lst),max(lst),sum(lst)/len(lst)
def first_last(lst): return (lst[0],lst[-1]) if lst else (None,None)

print(area(5)) # 78.5
print(sign(-5),sign(0)) # neg zero
print(first_gt([1,5,3,9],4)) # 5 (first element > 4)
a,b = swap(10,20); print(a,b) # 20 10
x,_=first_last([1,2,3,4,5]) # x=1, _ discarded (=5)

Section E: Exception Patterns — 20 Examples


# 1. Basic try-except-return-None
def safe_div(a,b):
try: return a/b
except ZeroDivisionError: return float('inf')

# 2. Multiple except clauses


def convert(s):
try: return int(s)
except ValueError: return float(s) if '.' in s else None
except TypeError: return None

# 3. finally always runs


def with_cleanup():
try: return 1
finally: print('cleanup!') # prints BEFORE return delivers value
print(with_cleanup()) # cleanup!\n1

# 4. ⚠ finally return OVERRIDES try return


def tricky():
try: return 'try'
finally: return 'finally' # WINS!
print(tricky()) # 'finally'

# 5. else runs only if NO exception


def safe_open(fname):
try: f=open(fname)
except FileNotFoundError: return None
else: content=[Link](); [Link](); return content # only if no exception

# 6. Raise custom message


def positive(n):
if n<0: raise ValueError(f'{n} must be ≥ 0')
return n

# 7. Try-except inside loop (continues on error)


def parse_all(items):
results=[]
for x in items:
try: [Link](int(x))
except ValueError: [Link](None) # keep going on error
return results
print(parse_all(['1','two','3','4x'])) # [1,None,3,None]

# 8. Validated input with retries


def get_int(prompt,lo=None,hi=None,retries=3):
for _ in range(retries):
try:
v=int(input(prompt))
if lo and v<lo: raise ValueError(f'Must be >={lo}')
if hi and v>hi: raise ValueError(f'Must be <={hi}')
return v
except ValueError as e: print(' Bad:',e)
return None

# 9. Exception in exception handler


def nested_exc():
try: 1/0
except: print('caught'); 1/0 # NEW exception in handler
finally: print('finally') # still runs; new exc propagates

# 10. Try-finally without except (always cleanup)


def acquire_resource():
resource=open('[Link]','w') # acquire
try: [Link]('data') # use
finally: [Link]() # ALWAYS release (even if exception!)

Section F: Multiple Methods Comparison — 15 Problems


Problem Method 1 (Basic) Method 2 (Pythonic) Method 3 (Functional/Advanced)
Max of list def mx(lst): def mx(lst): import functools
m=lst[0] return max(lst) mx=lambda lst:[Link](lambda
for x in lst: a,b:a if a>b else b,lst)
if x>m: m=x
return m
Check prime def prime(n): def prime(n): def prime(n):
if n<2: return False if n<2: return False return n>1 and not any(n%i==0 for i in
for i in range(2,n): return all(n%i for i in range(2,int(n**0.5)+1))
if n%i==0: return False range(2,int(n**0.5)+1))
return True
Reverse string def rev(s): def rev(s): return s[::-1] def rev(s): return ''.join(reversed(s))
r=''
for c in s: r=c+r
return r
Count vowels def v(s): def v(s): return sum(c in 'aeiou' for c in def v(s): return len(list(filter(lambda c:c in
count=0 [Link]()) 'aeiou',[Link]())))
for c in [Link]():
if c in 'aeiou': count+=1
return count
Flatten list def flat(lst): def flat(lst): import itertools
r=[] return [x for sub in lst for x in (flat(sub) if flat=lambda
for x in lst: isinstance(sub,list) else [sub])] lst:list([Link].from_iterable(lst))
if isinstance(x,list): r+=flat(x)
else: [Link](x)
return r
LAYER 4 — MEMORY ARCHITECTURE & EXECUTION ENGINE
4.1 Memory Diagrams — 5 Critical Scenarios
══════════════════════════════════════════════════════════════
SCENARIO 1: Call + return (immutable int)
══════════════════════════════════════════════════════════════
code: x=10; y=add(x,5) BEFORE CALL: DURING add(): AFTER:
def add(a,b): GLOBAL: add() FRAME: GLOBAL:
result=a+b add=<fn> a=10 add=<fn>
return result x=10 b=5 x=10
result=15 y=15 ← NEW
FRAME DESTROYED on return
KEY: a, b, result are GONE after return. x unchanged.

══════════════════════════════════════════════════════════════
SCENARIO 2: Mutable list — mutation vs rebind
══════════════════════════════════════════════════════════════
def modify(lst): [Link](99) # MUTATES same object
def rebind(lst): lst=[1,2,3] # REBINDS local name only
a=[10,20]; modify(a); print(a) # → [10,20,99] CHANGED!
b=[10,20]; rebind(b); print(b) # → [10,20] UNCHANGED!
REASON: lst and a point to SAME object; append() mutates it.
lst=[1,2,3] makes lst point to NEW object; b unaffected.

══════════════════════════════════════════════════════════════
SCENARIO 3: Default parameter — created ONCE at def time
══════════════════════════════════════════════════════════════
def f(x=[]): When def executes: f.__defaults__=([], )
[Link](1) Call 1: f() → x=f.__defaults__[0] → appends→[1]
return x Call 2: f() → SAME list → appends→[1,1]
print(f()) # [1] Call 3: f() → SAME list → appends→[1,1,1]
print(f()) # [1,1] FIX: def f(x=None): if x is None: x=[]
print(f()) # [1,1,1]

══════════════════════════════════════════════════════════════
SCENARIO 4: Multiple return — tuple creation on heap
══════════════════════════════════════════════════════════════
def pr(): return 1,'hello',True # Python creates tuple obj on heap
a,b,c = pr() # tuple unpacked: a=1,b='hello',c=True
result = pr() # result → tuple object addr
print(type(pr())) # → <class 'tuple'> ⚠ EXAM TRAP

══════════════════════════════════════════════════════════════
SCENARIO 5: Call stack depth (recursion)
══════════════════════════════════════════════════════════════
def fact(n): fact(4) call stack (LIFO):
if n<=1: return 1 ┌───────────────┐
return n*fact(n-1) │ fact(1)=1 │ ← TOP, returns 1
print(fact(4)) # 24 │ fact(2)=2×1=2 │
│ fact(3)=3×2=6 │
│ fact(4)=4×6=24│
│ global │ ← BOTTOM
└───────────────┘
5 frames for fact(4); each destroyed as return propagates up.

4.2 LEGB Rule — Complete with All Scenarios


# LEGB = Local→Enclosing→Global→Builtin # global keyword changes WRITE target
# Python searches this order on name lookup x = 100

x = 'GLOBAL' # G scope def no_kw(): x=999 # new LOCAL; global=100 safe


def with_kw(): global x; x=999 # GLOBAL changed
def outer():
x = 'ENCLOSING' # E scope (for inner only) no_kw(); print(x) # → 100 (global unchanged)
def inner(): with_kw(); print(x) # → 999 (global changed!)
x = 'LOCAL' # L scope
print(x) # → LOCAL (L found first) # global keyword: only needed to WRITE
inner() # to READ a global: no keyword needed
print(x) # → ENCLOSING
outer() # SCOPE LOOKUP TABLE:
print(x) # → GLOBAL # Name in fn body? Look in L first
print(len) # → <builtin> (B scope) # Not local? Look in E (nested fn)
# Not enclosing? Look in G (module)
# Not global? Look in B (builtins)
# Not builtin? NameError!
4.3 Call Stack — 4 Scenarios
═══ SCENARIO A: Chain ═══════════════════════════════════════
def c(): return 'c' Stack at deepest:
def b(): return c()+'b' ┌──────────┐
def a(): return b()+'a' │ c() frame│ ← TOP
print(a()) # 'cba' │ b() frame│
│ a() frame│
│ global │ ← BOTTOM
└──────────┘
═══ SCENARIO B: Exception propagation ═══════════════════════
def deep(): 1/0
def mid(): deep()
def top(): try: mid(); except ZeroDivisionError: print('caught!')
top() # ZeroDivisionError propagates UP through deep()→mid()→caught at top()

═══ SCENARIO C: finally in call stack ═══════════════════════


def inner(): As each frame unwinds:
try: 1/0 inner finally runs → outer finally runs
finally: print('inner F') → then exception propagates
def outer():
try: inner()
finally: print('outer F')
outer() # inner F outer F ZeroDivisionError

═══ SCENARIO D: Recursion limit ════════════════════════════


import sys
print([Link]()) # 1000 (default)
# def f(): f() → RecursionError: maximum recursion depth exceeded
# Always have base case in recursive function!

LAYER 5 — MATHEMATICAL & LOGICAL ANALYSIS


5.1 Complexity Reference
Operation Time Space Reason CBSE context
def statement O(1) O(1) 1 op: create fn object Defines fn; no code runs
Call (n params) O(n) O(1) n arg-bind ops n usually small ≤ 5
Return single O(1) O(1) 1 ref + frame destroy Always constant
Return k-tuple O(k) O(k) k values packed k usually small
LEGB lookup O(1) O(1) Hash table search Collision extremely rare
len(list) O(1) O(1) Stored as attribute Python caches length
max/min (n) O(n) O(1) Must visit all n Can't do better
sorted (n) O(n log n) O(n) Timsort algorithm Stable sort
Stack push (append) O(1)amort O(1) Append to end Resize rare
Stack pop (pop()) O(1) O(1) Remove from end Always O(1)
Recursion fact(n) O(n) O(n) n calls + n stack frames Stack overflow for large n
in (list n) O(n) O(1) Linear scan Use set for O(1) lookup

5.2 Truth Tables + Short-Circuit


A B A and B A or B not A # Short-circuit: AND stops at first False
x=0
T T T T F if x!=0 and 1/x>0: # 1/x NEVER evaluated!
T F F T F print('pos')
F T F T T
# Short-circuit: OR stops at first True
F F F F T
if x==0 or 1/x>0: # 1/x NEVER evaluated!
print('zero or pos')

# Falsy values — ALL evaluate as False:


# 0 0.0 '' [] {} () set() None

# Truthy: everything else including:


# '0' ' ' [0] {'':0} 1 -1 True

LAYER 6 — EXCEPTION HANDLING IN FUNCTIONS


6.1 15 Exception Types — Complete Reference
Exception Trigger In-Function Example Fix
TypeError Wrong arg type; wrong count add('x',5) on add(a,b) Validate type; fix arg count
Exception Trigger In-Function Example Fix
ValueError Right type, bad value int('hello'); [Link](-1) Validate range/format before convert
NameError Used before assignment print(x) before x defined Check scope; define first
(global)
UnboundLocalError Local var used before assign in def f(): print(n); n=5 (n=5 Add global n OR assign before use
same fn makes it local!)

ZeroDivisionError a/0 or a%0 or a//0 10/0 10%0 10//0 Check divisor ≠ 0 before dividing
IndexError Seq index out of range lst[5] when len(lst)=3 Check 0<=i<len(lst)
KeyError Dict key not found d['x'] when key 'x' absent Use [Link]('x') or 'x' in d
AttributeError Object lacks attribute 'hello'.append(1) — str has Check type; use correct method
no append
FileNotFoundError open() in 'r' on missing file open('[Link]','r') Check existence or use try-except
EOFError [Link]() at end of file [Link](f) after last Catch in while-True loop
record
ImportError Module not found import numpy (not installed) pip install; check name
IndentationError Mixed tabs/spaces; bad indent def f():\nreturn 1 (no 4 spaces; never mix tab+space
indent)
RecursionError No base case; depth>1000 def f(): return f() Add base case to every recursive fn
OperationalError DB offline or bad credentials [Link]() Verify DB running; check creds
fails
StopIteration next() on exhausted iterator next(iter([])) Use for loop; or catch StopIteration

6.2 All 7 Execution Paths


PATH 1 — No exception: try:print('T') except:print('E') else:print('L') finally:print('F')
OUTPUT: T L F (try runs fully; else runs; finally runs; except skipped)

PATH 2 — Caught exception: try:1/0 except ZeroDivisionError:print('E') else:print('L')


finally:print('F')
OUTPUT: E F (exception caught; else SKIPPED because exception occurred; finally runs)

PATH 3 — Uncaught exception: try:1/0 except ValueError:print('E') finally:print('F')


OUTPUT: F then ZeroDivisionError crash (wrong except type; finally still runs!)

PATH 4 — return inside try: def f(): try:return 1; finally:print('F')


OUTPUT: F\n1 (finally executes BEFORE value 1 actually returns)

PATH 5 — finally return overrides: def f(): try:return 'try'; finally:return 'finally'
OUTPUT: 'finally' (finally return WINS; try's return 'try' is discarded)

PATH 6 — Exception in except: try:1/0 except:print('E'); 1/0 finally:print('F')


OUTPUT: E F then new ZeroDivisionError propagates

PATH 7 — Nested try propagation: def i(): try:1/0; finally:print('iF')


def o(): try:i(); except ZeroDivisionError:print('caught');
finally:print('oF')
OUTPUT: iF caught oF (inner finally → inner exception propagates → outer catches → outer finally)

6.3 10 finally Output Predictions


# Code Output Key Rule
1 try:print(1) 1\n2 No exception; both run
finally:print(2)
2 try:1/0 E\nF Caught; finally after except
except:print('E')
finally:print('F')
3 try:1/0 F then ZeroDivErr finally runs; uncaught exc propagates
finally:print('F')
4 def f(): F\n1 finally before actual return; value still 1
try:return 1
finally:print('F')
print(f())
5 def f(): 2 finally return OVERRIDES try return
try:return 1
finally:return 2
print(f())
6 def f(): c finally ALWAYS wins
try:return 'a'
except:return 'b'
finally:return 'c'
print(f())
7 for i in [1,2]: 1\nF\n2\nF finally in each loop iteration
try:print(i)
finally:print('F')
# Code Output Key Rule
8 try:print('A') A\nC\nD No exception: try+else+finally; except skipped
except:print('B')
else:print('C')
finally:print('D')
9 try:raise ValueError E\nF Exception: try+except+finally; else skipped
except:print('E')
else:print('C')
finally:print('F')
10 def f(): x=10; try:return x; finally:x=99 10 x=99 in finally but return VALUE (10) already captured
print(f())
LAYERS 7 & 8 — FILE HANDLING & SQL THROUGH FUNCTIONS
7.1 File Mode Matrix
Mode Exists Missing Pointer R W Truncate? Use For
r Opens FileNotFoundError Start ✓ ✗ No Read existing
r+ Opens FileNotFoundError Start ✓ ✓ No Read+edit
w Opens,ERASES Creates Start ✗ ✓ YES Create/overwrite
w+ Opens,ERASES Creates Start ✓ ✓ YES Create+read
a Opens Creates END ✗ ✓ No Append to end
a+ Opens Creates End(W)/Beg(R) ✓ ✓ No Append+read
rb Opens FileNotFoundError Start ✓ ✗ No Read binary
wb Opens,ERASES Creates Start ✗ ✓ YES Write binary
ab Opens Creates END ✗ ✓ No Append binary

7.2 File Methods — Complete Reference


Method Returns Pointer After Empty File Critical Note
read() One str (all) End '' Loads ENTIRE file into RAM
read(n) str of n chars +n chars '' Efficient for large files
readline() One line incl \n End of line '' Last line may lack \n
readlines() List of strs End [] Each element has \n — don't forget!
write(s) Chars written (int) After s N/A NO auto-newline! Add \n manually
writelines(lst) None After all N/A NO auto-newlines! Add \n to each
seek(pos) None pos (absolute) N/A seek(0) rewinds to start
tell() Position (int) Unchanged 0 Returns byte offset from start
[Link](obj,f) None After obj N/A MUST use wb or ab mode!
[Link](f) Python object After obj EOFError MUST use rb mode!
[Link](f) writer obj N/A N/A Need newline='' in open()
[Link](r) Return val After row N/A r = list or tuple

8.1 Python-MySQL — Complete Function Reference


Function/Attr Purpose Returns Critical Error If Skipped
[Link](...) Open connection to MySQL Connection object OperationalError: DB offline
[Link]() Create cursor for SQL Cursor object AttributeError if conn is None
[Link](sql) Send SQL to server None ProgrammingError: bad SQL
[Link](sql,(v,)) Parameterized — SAFE None TypeError if params not tuple
[Link]() Save DML permanently None Data LOST if omitted after INSERT/UPDATE/DELETE!
[Link]() Next row Tuple or None Returns None (not []) if no rows
[Link]() All remaining rows List of tuples [] if no rows; memory risk on huge tables
[Link] Rows affected/found int May be -1 for SELECT on some drivers
[Link]() Release connection None Resource leak if omitted
%s placeholder Safe parameterized N/A NEVER concatenate: SQL injection risk
LAYER 10 — BOARD EXAM COMBAT: 30 MCQs
10.1 MCQ — 30 Questions
# Question A B C D ✓ Why wrong options fail
1 Keyword to define function: function def define func B A/C/D not Python keywords
2 No return statement returns: 0 '' C:None False C Python null=None; 0/False are
specific values
3 Which needs no import? [Link] [Link] C:len [Link] C len always built-in
dint
4 def f(a,b=5): b has? positional C:default keyword required B b=5 = default value 5
5 Variable inside fn has scope: global local universal module B Inside fn = local scope
6 How many values can fn return? 1 2 C:any 0 C Tuple packs any number
number
7 add(1,2,3) when def add(a,b): ValueError NameError C:TypeError IndexError C TypeError: takes 2 but 3 given
8 global keyword purpose: create read global C:modify delete C Read needs no keyword; modify
global global global does
9 def f(b=1,a): causes: TypeError NameError C:SyntaxErr Indentation C non-default arg follows default
or Error
10 [Link] without import: 4.0 C:NameErr auto-loads None B NameError: name 'math' not
or defined
11 x=10;def f():x=20;print(x);f();print(x) 20,20 10,10 C:20,10 Error C f's x=20 is LOCAL; global x=10
unchanged
12 def f():pass; print(f()): Error pass C:None 0 C pass→implicit return None;
print(None)→None
13 try:return 1 finally:return 2: 1 A:2 Error None B finally return OVERRIDES try return
14 return a,b is equivalent to: return [a,b] return (a,b) Error return a B Comma packs tuple
15 Always available without import: [Link] random C:print [Link] C print is built-in
16 def f(): return → returns: A:None 0 '' Error A Bare return = return None
17 def f(x=[]) across calls: New list Same list Error at call Depends B Default eval once; same obj
each all reused!
18 finally block runs: Only no Only Always Only if C Always — only [Link]() stops it
exception exception return
19 def f(a,b): return a,b; type(f(1,2)): list int str A:tuple D Multiple return = tuple
20 x=0;def f():x+=1;f() gives: x=1 TypeError C:Unbound SyntaxError C x+=1=assignment→x local→not
LocalError assigned yet
21 def f(a,b=5,c=10): f(1) gives: TypeError A:a=1,b=5,c a=1 only a=1,b=0 B b and c use defaults
=10
22 Module function defined in: interpreter module .py def in script class only B Module = .py file in library
file
23 Call stack is a: Queue Tree Graph A:Stack D LIFO: push on call, pop on return
(FIFO) (LIFO)
24 f(b=2,a=1) for def f(a,b): Error A:Valid Positional TypeError B All kwargs any order if all covered
keyword swap
25 After return, locals are: Saved for Moved to A:Destroye Stored C Frame destroyed; all locals gone
next global d heap
26 round(0.5) in Python 3: A:0 1 0.5 Error A Banker's rounding: half to even; 0
is even
27 [Link]() returns: str list A:writer None C writer obj with writerow method
object
28 [Link]: file must be: 'w' mode 'r' mode A:'wb' or 'r+' mode C Binary write/append mode
'ab' required
29 [Link]() no rows: [] 0 Empty str A:None D fetchone() returns None (not [])
30 [Link]() needed after: SELECT A:INSERT/ All queries None B DML changes need commit; SELECT
UPDATE/ doesn't modify
DELETE
LAYER 10 — OUTPUT PREDICTIONS (30 Questions)
10.2 Output Prediction — 30 Questions
1. ⚠ TRAP 11. ⚠ TRAP
x=10 def f(a): a=99
def f(): x=20; print(x) x=10; f(x); print(x)
f()
print(x)
12. ⚠ TRAP
def f(lst): [Link](99)
2. OUTPUT? a=[1,2]; f(a); print(a)
def f(a,b=5): return a+b
print(f(3))
print(f(3,10)) 13. ⚠ TRAP
print(f(b=2,a=8)) def f(lst): lst=[9,9]
a=[1,2]; f(a); print(a)

3. ⚠ TRAP
def f(): 14. OUTPUT?
try: return 1 for i in range(3):
finally: return 2 try: print(i)
print(f()) finally: print('F')

4. ⚠ TRAP
def m(): return 1,2,3
a,b,c=m()
print(type(m())) 15. ⚠ TRAP
print(b) g=0
def f():
global g; g+=10
5. ⚠ TRAP return g
x='global' print(f()+f())
def f():
print(x)
x='local' 16. OUTPUT?
f() def f(): return
print(f())
print(type(f()))
6. OUTPUT?
count=0
def inc(): 17. ⚠ TRAP
global count print(bool(0),bool(''),bool([]))
count+=1 print(bool(1),bool('0'),bool([0]))
return count
print(inc(),inc(),inc())

18. ⚠ TRAP
7. ⚠ TRAP def f(x,y=2,z=3): return x**y**z
def f(x=[]): print(f(2))
[Link](1)
return x
print(f())
19. ⚠ TRAP
print(f())
x=1
print(f())
def f(): return x+10
x=5
print(f())
8. OUTPUT?
def f():
try: print('A'); return 1
20. ⚠ TRAP
finally: print('C')
def f(a,b):
print(f())
a,b=b,a
x,y=10,20
f(x,y)
9. OUTPUT? print(x,y)
def f(a,b,c=3): print(a,b,c)
f(1,2)
f(1,2,9)
f(c=9,a=1,b=2)

10. ⚠ TRAP
import math
print([Link](-4.9))
print([Link](-4.1))
print(round(2.5))
print(round(3.5))

21. ⚠ TRAP 26. OUTPUT?


def f(): def f(a,b,c):
try: 1/0 return a+b, b+c, a+c
except: return 'E' x,y,z=f(1,2,3)
finally: return 'F' print(x,y,z)
print(f())

27. ⚠ TRAP
22. OUTPUT? print('A')
a=b=c=0 def f(): print('B')
def f(): global a,b; a=10; b=20 def g(): f(); print('C')
f(); print(a,b,c) print('D')
g()

23. OUTPUT?
def fact(n): return 1 if n<=1 else n*fact(n-1)
28. OUTPUT?
print(fact(0))
def f():
print(fact(1))
try: 1/0
print(fact(6))
except ValueError: return 'V'
except ZeroDivisionError: return 'Z'
print(f())
24. ⚠ TRAP
def f(x=None):
if x is None: x=[]
29. OUTPUT?
[Link](1)
def f(n):
return x
if n==0: return 0
print(f())
return n+f(n-1)
print(f())
print(f(5))

25. ⚠ TRAP
30. OUTPUT?
print(round(0.5))
n=5
print(round(1.5))
def f():
print(round(2.5))
n=10
print(round(3.5))
return n
print(f())
print(n)

⚠ Q5: Python sees x='local' anywhere in fn → x is LOCAL for ENTIRE fn → UnboundLocalError on read before assign Q7: Mutable default [] shared
KE
Y
across all calls — grows forever! Use x=None default instead Q10: ceil(-4.9)=-4 (ceiling goes UP toward 0); floor(-4.1)=-5 (floor goes DOWN
TR away from 0) Q10: round() uses banker's rounding: 0.5→0 (even), 1.5→2 (even), 2.5→2 (even), 3.5→4 (even) Q13: finally inside function:
A return in try prepares value; finally executes; if finally has return it wins Q15: f()+f() evaluates f() TWICE. First call: g=0→10, returns 10. Second
P call: g=10→20, returns 20. 10+20=30 Q18: ** is RIGHT-ASSOCIATIVE: x**y**z = x**(y**z) = 2**(2**3) = 2**8 = 256 (not (2**2)**3=64!) Q27:
EX
PL
def lines are ALWAYS SKIPPED (stored only); execution order = A → D → B → C
A
N
A
TI
O
N
S
LAYER 10 — HARD QUESTIONS & ERROR DETECTION
10.3 Hard Questions — 20 (★ = 5-mark difficulty)
H1. [5m] ★ What is the exact output? Explain each step. def f(x): x=x+1; return x a=5; b=f(a) print(a,b)
→ Output: 5 6
→ Why: int is IMMUTABLE. f(a) passes VALUE 5 to x. x=x+1 creates NEW local x=6. 'a' in global never touched.
→ Rule: immutable (int/str/float/tuple) → fn cannot modify caller's variable. Mutable (list/dict) → mutation IS visible.

H2. [5m] ★ Explain the UnboundLocalError precisely. x=10 def f(): print(x); x=20 f()
→ Output: UnboundLocalError: local variable 'x' referenced before assignment
→ Why: Python COMPILES entire fn body before executing. Seeing 'x=20' anywhere in fn body → Python classifies x as LOCAL for the ENTIRE
function — including lines BEFORE the assignment.
→ So at print(x), Python looks for LOCAL x (not global x), finds it unassigned → error.
→ Fix 1: Add 'global x' before print(x). Fix 2: Remove x=20 from function body.

H3. [5m] ★ Trace output step by step: def f(): try: print('A'); return 1 except: print('B'); return 2 finally: print('C'); return 3 print(f())
→ Step 1: try block → print('A') → output: A
→ Step 2: 'return 1' encountered → Python PREPARES to return 1 BUT...
→ Step 3: finally ALWAYS runs before actual return → print('C') → output: C
→ Step 4: finally has 'return 3' → this OVERRIDES try's prepared 'return 1'
→ Step 5: f() actually returns 3 → print(3) → output: 3
→ FINAL OUTPUT: A C 3
→ RULE: finally return always wins. Except block (B) never runs (no exception occurred).

H4. [5m] ★ Why does the list grow across calls? def f(x=[]): [Link](1); return x print(f()); print(f()); print(f())
→ Output: [1] then [1,1] then [1,1,1]
→ Why: The default value x=[] is evaluated ONCE when 'def' executes. The SAME list object is reused on every call where x is not passed.
→ After call 1: list=[1]. Call 2: same object, append→[1,1]. Call 3: same object→[1,1,1].
→ FIX: def f(x=None): if x is None: x=[] — creates fresh list each call.
→ ALL mutable defaults (list/dict/set) share this behavior. int/str/float/tuple are safe.

H5. [5m] ★ Find and fix ALL 5 errors: 1. def 2calc(x,y=0,z): 2. if z = 0: 3. return x+y 4. return x+y/z 5. print(calc(10))
→ E1 Line 1: SyntaxError — '2calc' starts with digit → fix: def calc(x,z,y=0):
→ E2 Line 1: SyntaxError — default y=0 before positional z → fix: reorder params
→ E3 Line 2: SyntaxError — 'z=0' uses assignment = not comparison == → fix: if z==0:
→ E4 Line 2-4: IndentationError — if/return must be indented inside fn body
→ E5 Line 5: TypeError — calc(10) only gives x=10; z has no default → missing required arg 'z'

H6. [3m] ★ Why do f() and g() give DIFFERENT results? def f(lst): [Link](99)
[Link] g(lst):
[3m] Whatlst=[99]
is the difference
a=[1,2]; f(a);
between
print(a)fetchone()
b=[1,2]; g(b);
andprint(b)
fetchall()?
→ f: lst and a point to SAME list object. [Link](99) MUTATES shared obj → a=[1,2,99]
fetchone(): Returns next row as tuple (None if no rows). Loads 1 row. Ideal for PK search.
→ g: lst=[99] makes local 'lst' point to NEW object [99]. Global 'b' still points to
→ old
fetchall():
[1,2]. Returns ALL rows as list of tuples ([] if empty). Loads entire result set.
→ Rule: Mutation(append/del/[i]=) affects caller. Rebinding(lst=…) only changes
→ fetchone()
local name.
called again → next row (or None). fetchall() called again → [] (already consumed).
→ MEMORY: fetchone() = O(1); fetchall() = O(n) — dangerous for huge tables
H7. [3m] Differentiate def vs lambda with examples.
[Link]
→ def: full definition; named; multiple statements; docstring; reusable across [3m] Explain: [Link]() is not needed after SELECT. Why?
→ lambda: anonymous; single expression only; no statements; inline use → commit() saves DML changes (INSERT/UPDATE/DELETE) permanently to disk.
→ double = lambda x: x*2 vs def double(x): return x*2 → SELECT is a DQL query — it only reads data, makes NO modifications to the database.
→ Use lambda for: sorted(lst,key=lambda x:x[1]) or filter(lambda x:x>0,lst) → Without commit() after INSERT: row appears in cursor but rolls back on disconnect — data LOST.
→ Use def for: complex logic, multiple lines, testing, documentation → Safe habit: always commit() after INSERT/UPDATE/DELETE; never needed for SELECT.

10.4 Error Detection — 20 Questions


# Buggy Code Error Fixed Code Root Cause
1 def 2func(x): return x SyntaxError def func2(x): Name can't start digit
2 def f(b=5,a): return a+b SyntaxError def f(a,b=5): Default before positional
3 def f(a,b): return a+b TypeError f(5,3) Missing required arg b
f(5)
4 g=0 UnboundLocalError global g before g+=1 Modify global needs keyword
def inc(): g+=1
inc()
5 import Math ModuleNotFoundError import math Module names are case-sensitive
[Link](4) [Link](4)
# Buggy Code Error Fixed Code Root Cause
6 def f(): IndentationError return 10 Body needs 4-space indent
return 10
7 result=compute(5) NameError Move def before call Define before call
def compute(n): return n*2
8 try: 1/0 ZeroDivisionError uncaught except ZeroDivisionError: Wrong exception type
except ValueError: print('caught')
9 with open('[Link]','r') as f: UnsupportedOperation open('[Link]','w') 'r' = read-only
[Link]('hi')
10 stack=[] IndexError if stack: item=[Link]() Check empty before pop
item=[Link]()
11 def f(a,b): return a,b IndexError print(x[0]+x[1]) Tuple has index 0,1 only
x=f(1,2)
print(x[0]+x[2])
12 import pickle TypeError open('[Link]','wb') Pickle needs binary mode
f=open('[Link]','w')
[Link]({'a':1},f)
13 import csv Blank lines (Windows) open('[Link]','w',newline='') Need newline='' in CSV open
f=open('[Link]','w')
[Link](f).writerow([1,2])
14 def f(x,y,x=5): pass SyntaxError def f(x,y,z=5): Duplicate parameter name x
15 [Link]('SELECT * FROM t TypeError [Link](sql,(1,)) Params must be tuple, not int
WHERE id=%s',1)
16 [Link]() NameError cursor=[Link]() Return value not stored
[Link]('SELECT...')
17 [Link]('INSERT INTO t Data not saved Add [Link]() before close DML needs commit
VALUES(1,2,3)')
[Link]()
18 with open('[Link]','rb') as f: Infinite loop/EOFError Add except EOFError: break Must catch EOFError at end
while True: print([Link](f))
19 def f(): Dead code (unreachable) Move print before return Code after return never runs
return
print('hi')
20 [Link](f).writerow(['a',' No error but f2 needs newline Both correct; writelines is fine writelines does NOT add newlines
b'])
[Link](['x\n','y'])
LAYER 10 — MEGA COMPARISON TABLES
10.5 All 8 Master Comparison Tables
▶ Built-in vs Module vs User-defined
Parameter Built-in Module-defined User-defined
Where defined Python interpreter (C source) A .py module file in stdlib Programmer's own .py file
Import needed Never — always available Yes: import math, import csv etc None; must write def first
20 examples (each) print len int str abs max min sum math:sqrt,ceil,floor,pow,log,factorial,pi,e,g def add() def grade() def push() def
round type sorted bool list open cd pop() def connect() def insert() def
range enumerate zip type isinstance random:randint,random,choice,shuffle,sam safe_divide() def word_count() def
id hash hex bin chr ord ple binary_search() def menu() def
csv:writer,reader,DictWriter export_csv() def bf_all()
pickle:dump,load
os:getcwd,listdir,[Link]
Performance Fastest (compiled C) Fast (optimized Python) Programmer-dependent
Can modify? No No Yes — full control
Error if unavailable Never (interpreter-level) NameError/ImportError NameError if called before def

▶ Positional vs Default Parameters


Parameter Positional Default
Definition No =; caller MUST provide Has =value; caller MAY omit
Syntax def f(a,b): — no = def f(a,b=10): — has = value
Position rule Must come FIRST Must come AFTER all positional
At call Mandatory Optional — omitting uses default
Override Caller's value always used Can override by passing argument
Error if omitted TypeError: missing required arg No error — default used
Example def add(a,b): → add(5,3) only def power(b,e=2): → power(3) or power(3,4)
Exam trap Order matters: f(1,2) ≠ f(2,1) def f(b=5,a) → SyntaxError!

▶ Local vs Global Scope


Parameter Local Global
Created Assignment inside fn body Assignment outside all functions
Lifetime Created on call; DESTROYED on return Entire program: creation to end
Accessible from Only that function Anywhere in program
To READ from inside fn Automatic (no keyword) Automatic (no keyword)
To MODIFY from inside fn Automatic (it's already local) MUST use: global x
Name conflict Local SHADOWS global (same name) Global used when no local exists
Example — create def f(): x=10 → x is local x=10 outside any def → x is global
Example — modify def f(): x=99 → new local; global x unchanged def f(): global x; x=99 → global now 99
Exam trap #1 Any assignment in fn = local throughout fn x=10;def f():print(x);x=20 → UnboundLocalError
Exam trap #2 Local x destroyed on return → can't use outside global needed only for WRITE not READ

▶ try vs except vs else vs finally


try except else finally

Runs when Always (the attempt) Matching exception occurs NO exception in try ALWAYS regardless
Can return Yes Yes Yes Yes — OVERRIDES all other
returns!
Can omit No Yes (need finally) Yes Yes (need except)
Multiple? One only Yes — multiple clauses One only One only
Common mistake try without except or finally Wrong exception type Expecting else to catch finally return overriding
exceptions intended return
Board trap Missing colon except ZeroDivisionError (not else runs even if except ran finally return 2 overrides
Exception) try return 1

▶ read() vs readline() vs readlines()


Parameter read() read(n) readline() readlines()
Reads Entire file Exactly n chars One line (incl \n) All lines
Returns One string One string One string List of strings
Pointer after End of file n chars forward End of that line End of file
Empty file '' empty string '' empty string '' empty string [] empty list
Use when Small files; need all Partial/streaming Line-by-line in loop Need list of all lines
Parameter read() read(n) readline() readlines()
Exam trap Not None but '' when read(0) = '' instantly Last line may lack \n Each string HAS \n — strip
empty it!

▶ dump() vs load() | write() vs writelines()


[Link](o,f) [Link](f) write(str) writelines(list)

Direction Python → bytes in file Bytes in fileWrites


→ Python Single string All strings in list
Operation Serialization Deserialization
Auto-newline No — add \n! No — add \n to each!
Mode needed wb or ab rb Returns Chars written (int) None
Returns None Python object
Type check Raises TypeError if not str Raises TypeError if not iterable of str
End of file N/A Raises EOFError
Example [Link]('Hi\n') [Link](['a\n','b\n'])
Exam trap Text mode → TypeError Forget try/except
Exam trap
EOFError → crash
write(123) → TypeError writelines(['a','b']) gives 'ab' (no newlines!)

▶ fetchone() vs fetchall() | execute() vs commit()


fetchone() fetchall() [Link]() [Link]()

Returns Next row as tuple All rows as listPurpose


of tuples Send SQL to server Save DML permanently
No rows None [] Called on cursor connection
Memory O(1) O(n) — loads After
ALL SELECT Yes (send query) No (SELECT = no change)
After call Pointer +1 Pointer at endAfter INSERT Yes (send query) YES — else data lost!
Again? Returns next row Returns [] (consumed)
Returns None None
Best for PK search; 0-1 rows Small-medium
Forgetting
datasets Nothing happens Data rolls back on disconnect
LAYERS 11–12 — PRACTICALS & RAPID REVISION
11.1 Practical Marks Breakdown
Practical Logic (6/10) Documentation (2/10) Code Quality (2/10) Viva Focus
P6: Dice [Link](1,6) correct; both Function named meaningfully Modular: roll() separate from What does randint(1,6)
ends inclusive; returns int (roll_dice); clear comments simulate(); no redundancy return? Diff from
[Link]()?
P7: Stack push=append(); pop with underflow is_empty/push/pop clearly Global stack declared; fn names What is underflow?
check; peek=lst[-1]; return correct separated; docstrings present match operation; prints state push/pop time complexity?
type LIFO meaning?
P8: Binary dump in ab mode; load with Function names: try-except present; with clause used; Why pickle? Why ab mode?
EOFError loop; search iterates all add_student,search_roll,update_ no leaked file handles What EOFError signals?
marks,display
P9: CSV [Link] with newline=''; header Function names match op: newline='' in open; DictWriter/writer Diff write/writelines? Why
written; reader with next() skip create,search,update,add consistent use newline=''? DictReader
advantage?

11.2 6 Quick-Reference Callout Cards


⚡ def keyword + name + (params): + indented body + return def STORES body; ⚡ name()
TypeError:
EXECUTES
wrong itarg
Notype
return
or count
/ bareZeroDivisionError:
return → returns None
a/0 or a%0 UnboundLocalError: local var before assign F
F E
U
Defaults after positional: def f(a,b=5) ✔ Multiple return: return a,b → tuple
X
→missing
unpackfile
a,b=f()
EOFError:
functions
[Link]()
are first-class
at endobjects
of file (can
NameError:
be passed!)
variable/fn not defined
N C
C E
TI P
O TI
N O
S N
S

⚡ Local: inside fn; created on call; DESTROYED on return Global: module level; lives whole program READ global: no keyword needed inside fn
S ⚡ x=10 in fn = NEW local; global x=10 unchanged def f(b=5,a) → SyntaxError (not TypeError!) f() no return → Non
C
MODIFY global: MUST use 'global x' first TRAP: any assignment in fn = localT THROUGHOUT fn Mutable mutation (append): no global needed
O O
finally:return 2 → returns 2 Mutable default ([]) shared across ALL calls [Link](-4.9)=-4 NOT -5 floor(-4.1)=-5
P P
E E
X
A
⚡ M
return val — exits fn immediately; sends val back return — bare; exits; sends
T
None (no return) — fn returns None at very end return a,b,c —
R
E
tuple; unpack as a,b,c=f() finally return ALWAYS OVERRIDES try/except return
R type(f()) where f returns a,b → <class 'tuple'>
T A
U P
R S
N
V
A ⚡ round(0.5)=0 round(1.5)=2 round(2.5)=2 round(3.5)=4 (banker's rounding — rounds to EVEN) int(3.9)=3 int
L B
U U
rounds!) sorted() returns NEW list; [Link]() modifies in-place reversed() returns ITERATOR not list [Link]()
E IL sqrt(4)=2.0 not 2
S T-
I
N
T
R
A
P
S

12.1 All Keywords + Functions — Flash Cards


Keyword/Fn Type One-line purpose Returns Critical Note
def Keyword Start function definition N/A STORES body; does NOT execute it
return Keyword Send value back; exit fn The value or None finally still executes after return in try
global Keyword Declare module-level var inside fn N/A Only needed to WRITE; reading global
works without
None Built-in const Python's null value N/A print(type(None))=<class 'NoneType'>
pass Keyword No-op placeholder None Allows empty fn body: def f(): pass
len() Built-in Length of sequence int O(1) — Python stores length as attribute
range() Built-in Integer sequence generator range object range(5)=[0..4]; range(1,6)=[1..5]
sorted() Built-in Return new sorted list list Does NOT modify original! [Link]()
modifies
max/min() Built-in Maximum/minimum element value Works on args: max(3,1) or list:
max([3,1])
abs() Built-in Absolute value int or float abs(-5)=5; abs(-3.7)=3.7;
abs(complex(3,4))=5.0
[Link]() Module fn Square root float ALWAYS float; sqrt(4)=2.0 not 2
[Link](a,b) Module fn Random int a to b inclusive int BOTH endpoints INCLUDED
[Link](o,f) Module fn Serialize to binary file None File MUST be wb or ab mode
Keyword/Fn Type One-line purpose Returns Critical Note
[Link](f) Module fn Deserialize from binary file Python obj Raises EOFError at end — use try/except
[Link](f) Module fn Create CSV writer object writer obj open() MUST have newline='' parameter
[Link](sql) Method Send SQL to DB server None Parameterized: execute(sql,(val,)) for
safety
[Link]() Method Save DML permanently None REQUIRED after INSERT/UPDATE/DELETE
[Link]() Method Get next row tuple or None None (not []) when no rows
[Link]() Method Get all rows list of tuples [] when no rows; memory cost O(n)
[Link] Attribute Rows affected/returned int May be -1 for SELECT

12.2 Mind Map — Complete Function Universe


╔═══════════════════════════════════════╗
║ PYTHON FUNCTIONS (Unit 1B) ║
╚══════════════╤════════════════════════╝
┌────────────────────────┼──────────────────────────┐
┌─────▼──────┐ ┌─────────────▼────────┐ ┌────────────▼──────────┐
│ 3 TYPES │ │ PARAMETERS │ │ SCOPE │
│ Built-in │ │ positional (required)│ │ LOCAL: inside fn │
│ Module │ │ default (optional) │ │ • created on call │
│ User-def │ │ keyword call syntax │ │ • DESTROYED on return │
└────────────┘ └──────────────────────┘ │ GLOBAL: outside fn │
│ • lives whole program │
┌────────────────────────────────────────┐ │ • global kw to modify │
│ RETURN VALUES │ └───────────────────────┘
│ single → any Python type │
│ multiple → return a,b → tuple │ ┌───────────────────────┐
│ none/bare return → None │ │ EXECUTION ENGINE │
│ finally return overrides try/except │ │ def → STORED in scope │
└────────────────────────────────────────┘ │ call → PUSHED to stack│
│ return→POPPED; done │
CONNECTS TO OTHER UNITS: │ LIFO: Last In, First │
1C Exception: try-except INSIDE functions │ Out — same as stack DS│
1D File: functions wrap all file operations └───────────────────────┘
1E Stack: CALL STACK is literally a stack
Unit3 SQL: connect/execute/commit are all method-functions

12.3 Last-Night Exam Checklist


M T □ x=10
□ def syntax — all 4 param types from memory □ Default params AFTER positional always
INSIDE□ fn
return
→ NEW a,b local;
createsglobal
tuple;
unchanged
unpack: a,b=f()
□ print(x)
□ NoBEFORE x=val in SAME fn → UnboundLocalError □
U R
S
return statement → function returns None □ Local var: inside fn; destroyedA
on(wrong
returnorder!)
□ Global
□ f()
var:
returns
outsideNone
fn; global
→ print(f())
keywordshows
to modify
None (not
□ crash) □ try:return 1; finally:return 2 → returns
T finally: ALWAYS executes — no exceptions □ finally return: OVERRIDES try/except
P reused return
every
□ call!
Flow:□def=stored;
[Link](-4.9)
call=executes;
= -4 (NOT -5LIFO
— goes
stacktoward
□ math:+∞) □ [Link](-4.1) = -5 (NOT -4 — goes tow
K sqrt,ceil,floor,factorial,pi,e,gcd □ [Link](1,6) INCLUSIVE both ends
S □round(1.5)=2
pickle: dump=wb/ab;
round(2.5)=2
load=rb;
(banker's!)
EOFError=end
□ int(3.9)=3
□ csv:(TRUNCATES);
writer with not round(3.9)=4 □ sorted() returns NEW list
N newline=''; writerow/writerows □ commit() after INSERT/UPDATE/DELETET— NOT type(f(1,2))
SELECTwhere
□ fetchone()→tuple
f returns a,b →or<class
None;'tuple'>
fetchall()→list
□ [Link]()
of tuples
ALWAYS returns float: sqrt(9)=3.0 □ print(None
O O
W A
not error)
✓ V
O
ID

LAYER 13 — CROSS-CONCEPT INTEGRATION PROGRAMS
W 5-mark board questions combine 2–3 units in one program. These mirror exact CBSE patterns: Functions+File+Exception+Stack+SQL in realistic
HY
TH
combinations.
IS
LA
YE
R

Int-1: Functions + Text File — All 5 CBSE Operations


def words_with_hash(fname):
with open(fname,'r') as f:
for line in f:
if [Link](): print('#'.join([Link]().split()))

def char_stats(fname):
v=co=up=lo=0
with open(fname,'r') as f:
for ch in [Link]():
if [Link]():
(v:=v+1) if [Link]() in 'aeiou' else (co:=co+1)
(up:=up+1) if [Link]() else (lo:=lo+1)
print(f'Vowels:{v} Cons:{co} Upper:{up} Lower:{lo}')

def count_lwc(fname): # lines, words, chars


with open(fname,'r') as f: data=[Link]()
return [Link]('\n')+1, len([Link]()), len(data)

def remove_lines_with(fname,out,word):
with open(fname,'r') as fi, open(out,'w') as fo:
for line in fi:
if [Link]() not in [Link](): [Link](line)

def copy_upper(src,dst):
with open(src,'r') as fi, open(dst,'w') as fo: [Link]([Link]().upper())

with open('[Link]','w') as f: [Link]('The quick brown fox\njumps over the lazy dog\nPython is fun!')
words_with_hash('[Link]') # The#quick#brown#fox ...etc
char_stats('[Link]') # Vowels:12 Cons:22 Upper:3 Lower:31
print(count_lwc('[Link]')) # (3, 12, 52)
remove_lines_with('[Link]','[Link]','the') # removes lines with 'the'

Int-2: Functions + Exception — Robust Validation System


def validated_input(prompt, type_fn=str, lo=None, hi=None, retries=3):
for attempt in range(1,retries+1):
try:
val=type_fn(input(f'{prompt} (try {attempt}/{retries}): '))
if lo is not None and val<lo: raise ValueError(f'Must be >={lo}')
if hi is not None and val>hi: raise ValueError(f'Must be <={hi}')
return val
except (ValueError,TypeError) as e: print(f' Bad: {e}')
return lo # exhausted retries — return minimum

def safe_file_op(fname, mode, operation):


try:
with open(fname,mode) as f: return operation(f), None
except FileNotFoundError: return None, f'Not found: {fname}'
except PermissionError: return None, f'Permission denied: {fname}'
except Exception as e: return None, f'Error: {e}'

def parse_batch(items, type_fn=int):


'''Convert list; None for each failed conversion.'''
results=[]
for item in items:
try: [Link](type_fn(item))
except (ValueError,TypeError): [Link](None)
return results

age = validated_input('Enter age',int,1,120)


content,err = safe_file_op('[Link]','r',lambda f:[Link]())
if err: print('Error:',err)
print(parse_batch(['1','two','3','4x'])) # [1,None,3,None]
Int-3: Functions + Stack — Operation History Tracker
history=[] # global stack = operation log

def push_log(op): [Link](op)


def pop_log(): return [Link]() if history else None
def show_log(): [print(f' {i+1}. {h}') for i,h in enumerate(reversed(history))]
def log_size(): return len(history)

def calculate(a, op, b):


try:
ops={'+':a+b,'-':a-b,'*':a*b,'/':a/b,'%':a%b,'**':a**b,'//':a//b}
if op not in ops: print('Unknown op'); return None
r=ops[op]
push_log(f'{a} {op} {b} = {r}') # push result to history stack
return r
except ZeroDivisionError: print('Cannot divide by zero!'); return None

def undo(): print('Undone:',pop_log() or 'Nothing to undo!')

print(calculate(10,'+',5)) # 15; pushed to history


print(calculate(20,'/',4)) # 5.0; pushed
print(calculate(7,'/',0)) # Error; NOT pushed (failed)
print(calculate(2,'**',10)) # 1024; pushed
show_log() # 3 entries newest-first
undo() # removes 2**10=1024
show_log() # 2 entries

Int-4: Functions + Binary + CSV — Dual Storage


import pickle, csv
DAT='[Link]'; CSV='[Link]'

def _load(): # private helper


recs=[]
try:
with open(DAT,'rb') as f:
while True:
try: [Link]([Link](f))
except EOFError: break
except FileNotFoundError: pass
return recs

def _overwrite(recs):
with open(DAT,'wb') as f: [[Link](r,f) for r in recs]

def add(roll,name,marks):
g=lambda m:'A+' if m>=90 else 'A' if m>=80 else 'B+'if m>=70 else 'B'if m>=60 else 'C'if m>=33 else
'F'
with open(DAT,'ab') as f: [Link]({'r':roll,'n':name,'m':marks,'g':g(marks)},f)
print(f'Added {name}')

def delete(roll): _overwrite([r for r in _load() if r['r']!=roll])


def search(roll): return next((r for r in _load() if r['r']==roll),None)
def update(roll,m): recs=_load(); [[Link]({'m':m}) for r in recs if r['r']==roll]; _overwrite(recs)
def display(): [print(r) for r in _load()] or print('No records.')

def export_csv():
recs=_load()
with open(CSV,'w',newline='') as f:
w=[Link](f,fieldnames=['r','n','m','g'])
[Link](); [Link](recs)
print(f'Exported {len(recs)} records to {CSV}')

add(1,'Rahul',88); add(2,'Priya',95); add(3,'Arjun',72)


print(search(2)) # {'r':2,'n':'Priya','m':95,'g':'A+'}
update(1,92) # Rahul's marks changed to 92
delete(3) # Arjun removed
export_csv() # 2 records (Rahul,Priya) exported
display() # shows remaining 2 records

Int-5: Complete Menu-Driven System — All 5 Units


# Combines: User-defined Functions + Binary File + CSV + Stack + Exception Handling
import pickle, csv; LOG=[] # LOG = operation history stack

# Stack ops for LOG


push=lambda op:[Link](op)
pop=lambda:[Link]() if LOG else None
show=lambda:[print(f' {i+1}.',x) for i,x in enumerate(reversed(LOG))]

# Binary file operations


DAT='[Link]'
def load():
out=[]
try:
with open(DAT,'rb') as f:
while True:
try: [Link]([Link](f))
except EOFError: break
except FileNotFoundError: pass
return out

def save_one(rec):
with open(DAT,'ab') as f: [Link](rec,f)
push(f'ADD r={rec["r"]} n={rec["n"]}')

def overwrite(recs):
with open(DAT,'wb') as f: [[Link](r,f) for r in recs]

def add(r,n,m): save_one({'r':r,'n':n,'m':m}); print('Added.')


def delete(r): overwrite([x for x in load() if x['r']!=r]); push(f'DEL r={r}'); print('Deleted.')

def update(r,m):
recs=load()
if any(x['r']==r for x in recs):
for x in recs:
if x['r']==r: x['m']=m
overwrite(recs); push(f'UPD r={r} m={m}'); print('Updated.')
else: print('Roll not found.')

def export_csv():
recs=load()
with open('[Link]','w',newline='') as f:
w=[Link](f); [Link](['Roll','Name','Marks'])
[Link]([[r['r'],r['n'],r['m']] for r in recs])
push(f'EXPORT {len(recs)} records'); print(f'Exported {len(recs)}.')

def menu():
while True:
print('\[Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link]')
ch=input('> ')
try:
if ch=='1': add(int(input('Roll:')),input('Name:'),float(input('Marks:')))
elif ch=='2': update(int(input('Roll:')),float(input('New Marks:')))
elif ch=='3': delete(int(input('Roll:')))
elif ch=='4': [print(x) for x in load()] or print('No data.')
elif ch=='5': export_csv()
elif ch=='6': show()
elif ch=='7': print('Undone:',pop() or 'Nothing to undo.')
elif ch=='8': print('Bye!'); break
else: print('Invalid.')
except ValueError: print('Error: numbers required!')
except Exception as e: print('Error:',e)
menu()

B Integration-5 covers in ONE program: • def keyword — user-defined functions (Unit 1B) • try/except — exception handling (Unit 1C) •
O
A
[Link]/load with ab/rb modes — binary file handling (Unit 1D) • [Link] with newline='' — CSV file handling (Unit 1D) • Stack (LOG)
R with push/pop/show — Stack DS (Unit 1E) A 5-mark question can test ANY combination of these. Know each piece in isolation, then combined.
D
EX
A
M
N
O
TE
BOARD ANSWER TEMPLATES — WORD-PERFECT ANSWERS
Complete Answer Bank — All Mark Levels
Concept Marks Write Word-for-Word Required Code Examiner Keywords
User-defined function 1m A user-defined function is a named, def f(x): return x*2 named · def · reusable ·
reusable block of code created by the f(5) → 10 task
programmer using the def keyword to
perform a specific task.
Built-in function 1m A built-in function is pre-loaded into the print('Hi') len([1,2,3]) pre-loaded · no import ·
Python interpreter and available without interpreter
any import statement.
Module function 2m A module-defined function is written in a import math module · import · .py file
Python module file and must be explicitly [Link](16)→4.0
imported before use using the import import random
statement. [Link](1,6)
Default parameter 2m A parameter with a pre-assigned value in def power(base,exp=2): pre-assigned · optional ·
the function definition; the caller may omit return base**exp caller may omit
it and the default value is used. power(3)→9
Local scope 2m A variable defined inside a function has def f(): x=10 inside fn · destroyed on
local scope; it exists only during the print(x) # return · not accessible
function's execution and is destroyed when outside→NameError outside
the function returns.
Global scope 2m A variable defined at module level (outside x=0 module level · accessible
all functions) has global scope; it is def inc(): global x; x+=1 anywhere · global keyword
accessible from anywhere in the program. inc(); print(x) → 1
Multiple return 3m A function can return multiple values by def bounds(lst): multiple · tuple · unpack
separating them with commas; Python return min(lst),max(lst)
automatically packs them into a tuple, lo,hi=bounds([3,1,7])
which the caller can unpack.
Flow of execution 3m Python reads code top-to-bottom; the def def f():print('B') def=stored · call=executes ·
statement stores the function body print('A') call stack · LIFO
without executing it; the body executes f()
only when the function is called; each call print('C')
pushes a frame onto the call stack, which is # Output: A B C
popped on return.
try-except-finally 5m The exception handling mechanism has try: try · except · finally · always
three parts: try contains risky code that result=int(input()) · exception type
may raise an exception; except catches and except ValueError:
handles specific exception types; finally print('Not a number!')
always executes regardless of whether an finally:
exception occurred or not. print('Done.')

You might also like