ANIL'S PYTHON LAB 🐍
Starting from Zero. Learning Python Together.
No experience required. Just curiosity.
A complete, self-study Python guidebook built for the CBSE Class 12 Computer Science (083) board exam. Every concept is taught from zero, with runnable examples, exam-style questions, and full solutions.
Complete Exam Preparation for Every Subject
Har Subject Ka Jugaad, Ek Hi Jagah.
Python is just the beginning. More subjects, same friendly, zero-to-hero style — all in one place.
What's inside
📘 Teaching
- Plain-language explanations
- Runnable code + expected output
- Line-by-line breakdowns
- "Teach me like a tutor" mode
🎯 CBSE Focus
- 1-mark, MCQ, Assertion-Reason
- Output & debugging questions
- Case-based & competency
- Previous-year-style bank
🧪 Practice
- Try-It-Yourself panels
- Quick quizzes with answers
- 4 difficulty levels
- Chapter tests + keys
🏁 Exam Prep
- 30-day & 7-day plans
- Mock papers (CBSE pattern)
- 24-hour checklist
- Master cheat sheet
Python Fundamentals
What Python is, how a program runs, and how to write your very first lines of code — starting from absolutely nothing.
1.1 What is Python?
Concept. Python is a programming language — a set of words and rules you use to give instructions to a computer. You write the instructions in plain-ish English-like text, and Python carries them out one line at a time.
Simple explanation. Think of the computer as a very fast but very literal helper. It will do exactly what you say, in the order you say it, and nothing more. Python is the language you use to talk to that helper.
Python is interpreted (it runs your code line by line, not all at once after translating), high-level (close to human language, far from machine 0s and 1s), and dynamically typed (you don't have to announce in advance whether something is a number or text).
1.2 How a Python program runs
When you run a Python file, the Python interpreter reads your code from top to bottom and executes each statement in order. This top-to-bottom order is called the flow of control, and it's the foundation of everything later (conditions and loops just change this flow).
| Term | Meaning (plain English) |
|---|---|
Interpreter | The program that reads and runs your Python code. |
Statement | One complete instruction (usually one line). |
Syntax | The grammar rules of Python. Break them → error. |
Comment | A note for humans that Python ignores. Starts with #. |
Token | The smallest unit Python recognises: keyword, identifier, literal, operator, punctuator. |
1.3 Your first program
Syntax — the print function displays something on the screen:
print("text you want to show")
Example.
# My first Python program print("Hello, CBSE!") print("I am learning Python.")
Line-by-line explanation
| Line | What it does |
|---|---|
# My first Python program | A comment. Python ignores it completely — it's just a note for you. |
print("Hello, CBSE!") | Calls the built-in print() function to display the text inside the quotes. |
print("I am learning Python.") | Runs after the line above (top-to-bottom flow) and prints the second line. |
print(), numbers, and basic math right here.- Forgetting the quotes:
print(Hello)→ Python thinksHellois a variable name → NameError. - Capital
Printinstead ofprint→ Python is case-sensitive → NameError. - Missing a closing bracket
print("hi"→ SyntaxError.
1.4 Comments & indentation
Comments start with #. Everything after # on that line is ignored. Use them to explain why your code does something.
Indentation (the spaces at the start of a line) is not decoration in Python — it is grammar. Python uses indentation to know which lines belong together. You'll see this the moment you reach if and loops.
{ } to group statements into a block. Wrong indentation changes the meaning of the program or causes an IndentationError.1.5 Quick Quiz
# starts a comment in Python. // and /* */ are from other languages.Print("hi") (capital P) will…Print is not the same as print.1.6 What did you learn?
Revision notes
- Python = interpreted, high-level, dynamically typed
- Code runs top-to-bottom (flow of control)
print()shows output#= comment- Indentation is grammar, not style
- 5 tokens: Keyword, Identifier, Literal, Operator, Punctuator
Top mistakes
- Missing/extra quotes or brackets
- Wrong capitalisation
- Mixing tabs and spaces
1.7 CBSE-style questions
Q1 · 1 mark · Name the five types of tokens in Python.
Answer: Keywords, Identifiers, Literals, Operators, Punctuators (delimiters).
Q2 · 2 marks · What is the difference between a compiler and an interpreter?
Answer: A compiler translates the entire program into machine code at once before running, and reports all errors together. An interpreter translates and executes the program line by line; it stops at the first error it reaches. Python uses an interpreter.
Q3 · 1 mark · Assertion–Reason
Assertion (A): Indentation is optional in Python.
Reason (R): Python uses indentation to define blocks of code.
Answer: A is false, R is true. Indentation is mandatory in Python precisely because it defines blocks.
1.8 Challenge
print("CBSE", 2026) print("Marks:", 70 + 30)
Show answer
print separates multiple items with a space; 70 + 30 is calculated before printing.
Variables & Data Types
How Python stores information in memory, the built-in data types you must know for boards, and the mutable-vs-immutable idea that trips up half of all students.
2.1 What is a variable?
Concept. A variable is a name that refers to a value stored in the computer's memory. You "assign" a value to a name using =.
Syntax
variable_name = valueExample
name = "Ahana" age = 17 marks = 95.5 print(name, age, marks)
Line-by-line
| Line | Explanation |
|---|---|
name = "Ahana" | Creates a name name pointing to the string "Ahana". |
age = 17 | Points age at the integer 17. No need to declare "int". |
marks = 95.5 | Points marks at a float (decimal number). |
print(name, age, marks) | Prints all three, separated by spaces. |
2.2 Rules for naming variables (identifiers)
| Rule | Valid ✅ | Invalid ❌ |
|---|---|---|
| Letters, digits, underscore only | total_1 | total-1 |
| Cannot start with a digit | m1 | 1m |
| No spaces | first_name | first name |
| Cannot be a keyword | total | for, if |
| Case-sensitive | Age, age, AGE are three different variables | |
2.3 Core data types (must know for boards)
| Type | Keyword | Example | Mutable? |
|---|---|---|---|
| Integer | int | 70 | — |
| Floating point | float | 95.5 | — |
| String | str | "CBSE" | ❌ Immutable |
| Boolean | bool | True, False | — |
| List | list | [1, 2, 3] | ✅ Mutable |
| Tuple | tuple | (1, 2, 3) | ❌ Immutable |
| Dictionary | dict | {"a":1} | ✅ Mutable |
You can check any value's type with the built-in type() function:
print(type(70)) print(type(95.5)) print(type("CBSE")) print(type(True))
2.4 Mutable vs Immutable — the big idea
Concept. Mutable means "can be changed after it is created." Immutable means "cannot be changed — any 'change' actually makes a new object."
# List is mutable — item changes in place marks = [90, 80, 70] marks[0] = 100 print(marks) # String is immutable — this line ERRORS name = "CBSE" # name[0] = "X" -> TypeError
name[0] = "X" on a string raises TypeError: 'str' object does not support item assignment. Strings and tuples cannot be changed by index.2.5 Type conversion
Convert between types with int(), float(), str(). This matters hugely for input(), which always returns a string.
a = "25" # a is a STRING b = int(a) # now an INTEGER print(b + 5) # 30 print(str(b) + "5") # "255" (string joining)
+ on numbers = addition; + on strings = joining (concatenation). This distinction is a favourite output-prediction question.2.6 Quick Quiz
type(95.5) returns…print("2" + "3") outputs…+ joins them into "23".2.7 Output prediction (mini-set)
P1 · print(7 // 2, 7 % 2)
// is integer division (3), % is remainder (1).
P2 · print(int("12") + int("8"))
Both strings become integers first, then add.
P3 · print(3 + True)
🧠 Higher-order trap: True counts as 1, False as 0. So 3 + True = 4.
2.8 Debugging drill
1marks = 50 print(1marks)
Show fix
Error: SyntaxError — identifier starts with a digit. Fix: rename to a valid identifier, e.g. marks1 = 50.
2.9 What did you learn?
Revision notes
- Variable = label pointing at a value
- Assign with
= - Types: int, float, str, bool, list, tuple, dict
- Check with
type() - Convert with
int/float/str
Mutable / Immutable
- Mutable: list, dict
- Immutable: int, float, str, tuple, bool
input()always returns str
Top mistakes
- Naming a variable with a digit first
- Assuming input() gives a number
- Trying to edit a string by index
2.10 CBSE-style questions
Q1 · 1 mark · Name two immutable and two mutable data types.
Answer: Immutable: string, tuple (also int, float). Mutable: list, dictionary.
Q2 · 2 marks · Why does input() need type conversion for arithmetic?
Answer: input() always returns data as a string. To do arithmetic you must convert it using int() or float(), otherwise + would join strings instead of adding numbers (or raise a TypeError with mixed types).
Q3 · 1 mark · Assertion–Reason
A: Tuples are immutable. R: You cannot change a tuple's element by index assignment.
Answer: Both A and R are true, and R is the correct explanation of A.
Operators
The symbols that make Python do things — arithmetic, comparison, logic, assignment — plus the operator-precedence rules that decide output-prediction questions.
3.1 What is an operator?
Concept. An operator is a symbol that performs an operation on values. The values it works on are called operands. In 7 + 3, the + is the operator and 7 and 3 are operands.
3.2 Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | True division (always float) | 7 / 2 | 3.5 |
// | Floor division (drops decimal) | 7 // 2 | 3 |
% | Modulus (remainder) | 7 % 2 | 1 |
** | Exponent (power) | 2 ** 3 | 8 |
/ always gives a float (4/2 is 2.0, not 2). // throws away the fractional part. % gives the remainder — the go-to trick for "is it even/odd?" (n % 2 == 0) and "last digit" (n % 10).a = 17 print(a / 5) # 3.4 print(a // 5) # 3 print(a % 5) # 2 print(a ** 2) # 289
% really means
Real-world example: You have 17 chocolates to share equally among 5 friends. Each gets 17 // 5 = 3 (floor division), and 17 % 5 = 2 are left over (modulus). Floor division = "how many each", modulus = "what's left".3.3 Relational (comparison) operators
These compare two values and always give a Boolean (True/False).
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 5 > 8 | False |
< | Less than | 5 < 8 | True |
>= | Greater or equal | 5 >= 5 | True |
<= | Less or equal | 5 <= 4 | False |
= is assignment (put a value in). == is comparison (check if equal). Writing if x = 5: is a SyntaxError. You want if x == 5:.3.4 Logical operators
Combine Boolean conditions: and, or, not.
| Operator | True when… | Example | Result |
|---|---|---|---|
and | BOTH sides are True | (5>2) and (3>1) | True |
or | AT LEAST ONE side is True | (5<2) or (3>1) | True |
not | Reverses the value | not (5>2) | False |
and is strict (needs everyone to agree). or is generous (one yes is enough). not flips the answer.3.5 Assignment operators
Shorthand that updates a variable using its own current value.
| Shortcut | Same as |
|---|---|
x += 3 | x = x + 3 |
x -= 3 | x = x - 3 |
x *= 3 | x = x * 3 |
x //= 3 | x = x // 3 |
x %= 3 | x = x % 3 |
3.6 Operator precedence (who goes first)
When several operators appear together, Python follows a priority order. Higher rows run first.
| Priority | Operators |
|---|---|
| 1 (highest) | ** |
| 2 | * / // % |
| 3 | + - |
| 4 | == != < > <= >= |
| 5 | not |
| 6 | and |
| 7 (lowest) | or |
( ) to force the order you want and to make your intent obvious. Brackets always win over precedence.print(2 + 3 * 4) # 14, not 20 print((2 + 3) * 4) # 20 print(2 ** 3 * 2) # 16 (** first -> 8*2)
3.7 Quick Quiz
print(9 // 2) outputs…n is even, you write…(5 > 3) and (2 > 8) evaluates to…and needs both True. The second part is False, so the whole is False.2 + 3 ** 2 gives…** runs first: 3**2 = 9, then 2 + 9 = 11.3.8 Output prediction
P1 · print(17 % 5, 17 // 5)
P2 · print(not (5 == 5))
5==5 is True; not True is False.
P3 · x = 5; x *= 2 + 3; print(x)
🧠 Trap: the right side 2+3 is computed first (=5), then x = 5 * 5 = 25.
3.9 Debugging drill
age = 18 if age = 18: print("adult")
Show fix
Error: SyntaxError — used = (assignment) inside an if. Fix: use ==: if age == 18:
3.10 What did you learn?
Revision notes
- Arithmetic:
+ - * / // % ** /→ float,//→ floor,%→ remainder- Comparison gives Boolean
- Logic:
and or not - Precedence:
**>*/>+-> comparison > logic
Top mistakes
=vs==- Expecting
/to give an int - Forgetting
**runs before*
3.11 CBSE-style questions
Q1 · 1 mark · Difference between / and //.
Answer: / performs true division and always returns a float. // performs floor division and returns the quotient without the fractional part (an int when both operands are int).
Q2 · 2 marks · Evaluate 2 + 3 * 4 ** 2 - 1 showing steps.
Answer: 4**2 = 16 → 3*16 = 48 → 2 + 48 - 1 = 49. Result: 49.
Q3 · 1 mark · Assertion–Reason
A: 3 / 2 gives 1. R: Division in Python discards the decimal.
Answer: A is false (it gives 1.5), R is false (that describes //, not /).
3.12 Challenge
// and %.
Show approach
For n = 349: units = n % 10 → 9; tens = (n // 10) % 10 → 4; hundreds = n // 100 → 3. This digit-extraction idea powers many CBSE programs (reverse a number, sum of digits, Armstrong numbers).
Input & Output
How to read data from the user with input() and display results neatly with print() — including the single most common beginner bug in all of CBSE Python.
4.1 Taking input
Concept. input() pauses the program, waits for the user to type something and press Enter, then hands that text back to your program as a string.
Syntax
variable = input("prompt message")
name = input("Enter your name: ") print("Hello,", name)
a = input("num: ") # a is "5" (string) print(a + 1) # TypeError!
int() or float().The correct pattern
a = int(input("First number: ")) b = int(input("Second number: ")) print("Sum =", a + b)
int(input(...)) — input runs first (reads text), then int converts it. Read it inside-out.4.2 Producing output with print()
print() can display many items, separated by a space by default.
Useful options: sep and end
| Option | Controls | Default |
|---|---|---|
sep | What goes between items | a space " " |
end | What goes after the whole line | a newline "\n" |
print("2026", "03", "14", sep="-") print("Loading", end="...") print("done")
sep and end are common in output prediction. If end is changed from its default newline, the next print continues on the same line — that's why "done" appears right after "...".sep/end: line 2 supported; try predicting all four.4.3 Quick Quiz
input() always returns data of type…input(), then convert with int().print("X", end=" ") then print("Y") outputs…end to a space keeps output on the same line.4.4 Output prediction
P1 · print(1, 2, 3, sep="*")
P2 · print("Hi", end="") then print("There")
4.5 Debugging drill
num = input("Enter marks: ") avg = num / 2 print(avg)
Show fix
Error: TypeError — num is a string, can't divide by 2. Fix: num = int(input("Enter marks: ")) (or float).
4.6 What did you learn?
Revision notes
input()reads text (always str)- Wrap with
int()/float()for numbers print(a, b, sep=..., end=...)- Default
sep= space,end= newline
Top mistakes
- Doing math on raw input
- Wrong wrap order
- Forgetting
endkeeps line open
4.7 CBSE-style questions
Q1 · 1 mark · What is the default value of sep in print()?
Answer: A single space " ".
Q2 · 2 marks · Write a program to input two numbers and print their average.
a = float(input("a: ")) b = float(input("b: ")) print("Average =", (a + b) / 2)
Conditional Statements
Teaching your program to make decisions — if, if-else, if-elif-else, and nesting — where indentation stops being optional and becomes everything.
5.1 The idea of a decision
Concept. Until now, code ran straight top-to-bottom. A conditional statement lets the program choose whether to run a block, based on whether a condition is True or False.
5.2 The if statement
Syntax
if condition: statement # runs only if condition is True statement # (same indentation = same block)
: at the end of the if line. (2) The indentation of the body. Miss either and you get a SyntaxError or IndentationError.age = 20 if age >= 18: print("You can vote") print("Program ends")
Line-by-line: the indented print belongs to the if and runs only when the condition is true. The non-indented print is outside the if, so it always runs.
5.3 if-else
Do one thing when the condition is true, another when it's false.
n = 7 if n % 2 == 0: print("Even") else: print("Odd")
5.4 if-elif-else — many choices
Use elif (else-if) to check several conditions in order. Python runs the first true branch and skips the rest.
marks = 82 if marks >= 90: print("A") elif marks >= 75: print("B") elif marks >= 60: print("C") else: print("D")
elif conditions from most specific / highest to lowest. If you check marks >= 60 first, an A student would wrongly get a C.5.5 Nested if
An if inside another if. The inner one is only checked when the outer condition is true.
num = 10 if num >= 0: if num == 0: print("Zero") else: print("Positive") else: print("Negative")
- Missing colon:
if x > 5→ SyntaxError. - Using
=instead of==in the condition. - Wrong indentation → IndentationError, or the wrong lines run.
- Mixing tabs and spaces (looks fine, breaks silently).
5.6 Quick Quiz
if line?if, elif, else header ends with a colon.elif is short for…if-elif-elif-else, how many branches can run?if in Python?5.7 Output prediction
P1 · x=5; if x>3: print("A"); print("B")
Condition true → "A"; the un-indented "B" always prints.
P2 · What if x = 2 in the code above?
Condition false → "A" skipped; "B" still prints because it's outside the if.
P3 🧠 · m=90; if m>=60: print("Pass") elif m>=90: print("Top")
Higher-order trap: m>=60 is checked first and is true, so "Top" is never reached even though m is 90. Ordering matters.
5.8 Debugging drill
marks = 40 if marks >= 33 print("Pass") else: print("Fail")
Show fix (two errors)
Error 1: missing colon after the if condition. Error 2: the print lines are not indented. Fixed:
marks = 40 if marks >= 33: print("Pass") else: print("Fail")
5.9 What did you learn?
Revision notes
if condition:— colon + indented blockelsefor the false caseeliffor multiple checks, in order- Only the first true branch runs
- Nested
if= decision inside a decision
Top mistakes
- Missing colon
- Wrong / mixed indentation
=instead of==- Bad
elifordering
5.10 CBSE-style questions
Q1 · 1 mark · What is the purpose of elif?
Answer: It checks an additional condition when the previous if/elif conditions were false, allowing multiple mutually-exclusive choices.
Q2 · 3 marks · Program: input a number and print whether it is positive, negative, or zero.
n = int(input("Enter a number: ")) if n > 0: print("Positive") elif n < 0: print("Negative") else: print("Zero")
Q3 · 1 mark · Assertion–Reason
A: In an if-elif-else ladder, more than one branch may execute. R: Python evaluates every condition independently.
Answer: Both false. Python runs only the first true branch and then skips the rest.
5.11 Challenge
if/elif/else (no built-in max).
Show solution
a = int(input()) b = int(input()) c = int(input()) if a >= b and a >= c: print(a) elif b >= c: print(b) else: print(c)
The first branch checks if a beats both others. If not, we already know a isn't largest, so we just compare b and c.
Loops
Making the computer repeat work — for, while, range(), nested loops, and the break/continue controls that turn up in almost every board paper.
6.1 Why loops?
Concept. A loop repeats a block of code many times so you don't have to write it out by hand. Printing 1 to 100 with 100 print lines is madness; a loop does it in two.
6.2 The for loop with range()
A for loop repeats a known number of times. It usually walks over a sequence produced by range().
How range() works — memorise this
| Call | Produces | Note |
|---|---|---|
range(5) | 0 1 2 3 4 | starts at 0, stops before 5 |
range(1, 5) | 1 2 3 4 | start, stop (stop excluded) |
range(1, 10, 2) | 1 3 5 7 9 | start, stop, step |
range(5, 0, -1) | 5 4 3 2 1 | negative step counts down |
range(1, 5) gives 1,2,3,4 — not 5. This off-by-one is the single most common loop mistake in exams.Example — sum of first 5 numbers
total = 0 for i in range(1, 6): total = total + i print("Added", i, "-> total =", total) print("Final sum:", total)
Line-by-line
| Line | What happens |
|---|---|
total = 0 | Start an accumulator at 0 before the loop. |
for i in range(1,6): | i takes values 1,2,3,4,5 one at a time. |
total = total + i | Each pass adds the current i to the running total. |
print("Final...", total) | Runs after the loop (not indented into it). |
6.3 The while loop
A while loop repeats as long as a condition stays true. Use it when you don't know the count in advance.
n = 5 while n > 0: print(n) n = n - 1 # update — or it loops forever! print("Lift off")
while loop needs three things: (1) initialise the variable before, (2) a condition that can become false, (3) an update inside the loop that moves toward stopping. Forget the update and the loop never ends.for. Unknown count, depends on a condition ("keep asking until the password is right") → while.6.4 break and continue
| Keyword | Effect |
|---|---|
break | Exit the loop immediately, skip the rest. |
continue | Skip the rest of this iteration, jump to the next one. |
for i in range(1, 6): if i == 3: continue # skip printing 3 if i == 5: break # stop before 5 print(i)
Why: 3 is skipped by continue; the loop stops entirely at 5 due to break, so 5 never prints.
6.5 Nested loops
A loop inside a loop. The inner loop finishes completely for each single step of the outer loop. Essential for pattern-printing questions.
for i in range(1, 4): for j in range(i): print("*", end="") print() # move to next line
end="" to stay on the same line, then a bare print() to break the line."*" * 5 prints a string repeated — a shortcut for simple rows.6.6 Quick Quiz
range(2, 8, 2) produces…break does what?break leaves the loop at once; continue skips just one iteration.while loop runs forever most often because…6.7 Output prediction
P1 · for i in range(3): print(i, end=" ")
P2 🧠 · i=1; while i<=3: print(i*i); i+=1
Prints squares of 1,2,3.
P3 🧠 · for i in range(5): if i==2: break; print(i)
Loop stops the moment i reaches 2, so only 0 and 1 print.
6.8 Debugging drill
i = 1 while i <= 5: print(i)
Show fix
Bug: infinite loop — i is never updated, so the condition stays true forever. Fix: add i = i + 1 (or i += 1) inside the loop.
6.9 What did you learn?
Revision notes
for= known count;while= condition-basedrange(start, stop, step); stop excludedbreakexits;continueskips one- Nested: outer rows, inner columns
end=""+print()for patterns
Top mistakes
- Off-by-one with range's stop
- Missing update → infinite loop
- Confusing break and continue
- Wrong indentation of loop body
6.10 CBSE-style questions
Q1 · 1 mark · How many times does for i in range(2, 20, 3) iterate?
Answer: Values are 2, 5, 8, 11, 14, 17 → 6 times.
Q2 · 3 marks · Program: print the multiplication table of a number entered by the user.
n = int(input("Number: ")) for i in range(1, 11): print(n, "x", i, "=", n * i)
Q3 · 1 mark · Assertion–Reason
A: range(5) includes the number 5. R: The stop value in range() is excluded.
Answer: A is false, R is true. R correctly explains why A is false.
6.11 Challenge
Show solution
for i in range(1, 5): for j in range(1, i + 1): print(j, end=" ") print()
Outer i = row number (1–4). Inner j runs from 1 to i, printing each value; the bare print() ends the row.
Strings
Text data — indexing, slicing, the methods CBSE loves, and the immutability rule that produces so many output-prediction questions.
7.1 What is a string?
Concept. A string is a sequence of characters written inside quotes: 'hi' or "hi". Each character has a position number called an index.
Indexing — positive and negative
For the string "PYTHON":
| Character | P | Y | T | H | O | N |
|---|---|---|---|---|---|---|
| Index (+) | 0 | 1 | 2 | 3 | 4 | 5 |
| Index (−) | −6 | −5 | −4 | −3 | −2 | −1 |
s = "PYTHON" print(s[0]) # P print(s[-1]) # N (last char) print(len(s)) # 6
s[-1]. len(s) gives the count; the highest valid positive index is len(s) - 1.7.2 Slicing — the exam favourite
Syntax: s[start : stop : step]. It returns the characters from start up to but not including stop.
s = "PYTHON" print(s[0:3]) # PYT print(s[2:]) # THON print(s[:4]) # PYTH print(s[::2]) # PTO print(s[::-1]) # NOHTYP (reversed!)
s[::-1] reverses any string. Missing start/stop means "from the beginning" / "to the end". A step of -1 walks backward. This exact trick appears constantly.s[1:4] means "tear from gap 1 to gap 4" — you keep whatever is between them (characters at 1, 2, 3). That's why stop is not included.7.3 Strings are immutable
s = "cat" # s[0] = "b" -> TypeError s = "b" + s[1:] # make a NEW string instead print(s)
s[0] = "b" — that's a TypeError. To "edit" a string you build a new one, often by slicing and concatenating.7.4 Important string methods (must-know)
| Method | Does | Example → Result |
|---|---|---|
upper() | ALL CAPS | "hi".upper() → HI |
lower() | all small | "HI".lower() → hi |
title() | Each Word Capitalised | "my file".title() → My File |
strip() | Remove surrounding spaces | " hi ".strip() → hi |
replace(a,b) | Swap text | "aba".replace("a","x") → xbx |
split(sep) | Break into a list | "a,b,c".split(",") → ['a','b','c'] |
count(x) | How many times x occurs | "banana".count("a") → 3 |
find(x) | Index of first x (−1 if absent) | "abc".find("c") → 2 |
isdigit() | All digits? | "123".isdigit() → True |
s.upper() does not change s unless you reassign: s = s.upper().+ joins strings; * repeats them.7.5 Looping over a string
s = "CBSE" for ch in s: print(ch, end="-")
7.6 Quick Quiz
s = "HELLO", s[-1] is…-1 is the last character: O."PYTHON"[1:4] gives…s?reverse() method; slicing with step −1 does it."banana".count("a") returns…7.7 Output prediction
P1 · print("abc" * 2)
P2 · print("Hello".replace("l", "L"))
Both l's are replaced; original is unchanged (a new string is returned).
P3 🧠 · s="PROGRAM"; print(s[1:6:2])
Indices 1,3,5 → R, G, A (step 2, stop 6 excluded).
7.8 Debugging drill
s = "data" s[0] = "D" print(s)
Show fix
Bug: TypeError — strings are immutable, so item assignment fails. Fix: build a new string: s = "D" + s[1:].
7.9 What did you learn?
Revision notes
- Index from 0; last =
s[-1] s[a:b:c]; stop excludeds[::-1]reverses- Immutable → methods return new strings
- Know: upper, lower, strip, replace, split, count, find
Top mistakes
- Forgetting index starts at 0
- Expecting stop to be included
- Assigning to
s[i] - Forgetting to reassign method result
7.10 CBSE-style questions
Q1 · 1 mark · What does len("Computer") return?
Answer: 8.
Q2 · 2 marks · Write code to count vowels in a string entered by the user.
s = input("Enter text: ").lower() count = 0 for ch in s: if ch in "aeiou": count += 1 print("Vowels:", count)
Q3 · 1 mark · Assertion–Reason
A: "abc".upper() changes the original string. R: Strings are mutable.
Answer: Both false. Strings are immutable; upper() returns a new string and leaves the original unchanged.
7.11 Challenge
Show solution
w = input("Word: ").lower() if w == w[::-1]: print("Palindrome") else: print("Not a palindrome")
The whole trick is comparing the string to its reverse w[::-1]. This is a very common board question.
Lists
Python's workhorse container — an ordered, changeable collection. Indexing, slicing, the methods you must know, and the mutability behaviour that catches students out.
8.1 What is a list?
Concept. A list stores many values in one variable, in order, inside square brackets [ ]. Unlike a string, a list is mutable — you can change, add, and remove items.
marks = [90, 85, 70, 95] print(marks[0]) # 90 print(marks[-1]) # 95 print(len(marks)) # 4 marks[2] = 75 # change works (mutable!) print(marks)
marks[2] = 75), a string cannot.8.2 Slicing lists
Exactly like strings: L[start:stop:step], stop excluded.
L = [10, 20, 30, 40, 50] print(L[1:4]) # [20, 30, 40] print(L[:2]) # [10, 20] print(L[::-1]) # [50, 40, 30, 20, 10]
8.3 List methods (must-know for boards)
| Method | Does | Example (on L=[3,1,2]) |
|---|---|---|
append(x) | Add x at the end | L.append(5) → [3,1,2,5] |
insert(i,x) | Insert x at index i | L.insert(0,9) → [9,3,1,2] |
extend(list) | Add all items of another list | L.extend([7,8]) → [3,1,2,7,8] |
remove(x) | Delete first occurrence of x | L.remove(1) → [3,2] |
pop(i) | Remove & return item at i (last if no i) | L.pop() → returns 2 |
sort() | Sort in place (ascending) | L.sort() → [1,2,3] |
reverse() | Reverse in place | L.reverse() → [2,1,3] |
index(x) | Position of x | L.index(2) → 2 |
count(x) | How many times x appears | L.count(1) → 1 |
append([7,8]) adds the list itself as one item → [3,1,2,[7,8]]. extend([7,8]) adds each element → [3,1,2,7,8]. This distinction is a favourite trick question.sort()andreverse()return None — they change the list in place. Never writeL = L.sort()(that sets L to None).remove(x)needs the value;pop(i)needs the index.removeon a value not present → ValueError.
sort() rearranges the shelf and hands back nothing (None). sorted(L) leaves your shelf alone and hands you a new sorted copy.8.4 Looping over a list
marks = [40, 55, 70] total = 0 for m in marks: total += m print("Sum:", total) print("Average:", total / len(marks))
8.5 Quick Quiz
append(x) adds x at the end. Python lists have no add()/push().L = [1,2,3]; L = L.sort(). Now L is…sort() sorts in place and returns None, so L becomes None. Trap!pop() without an argument removes the…pop() removes and returns the last element.L=[1,2]; L.append([3,4]), len(L) is…append adds the whole list as one item → [1,2,[3,4]], length 3.8.6 Output prediction
P1 · L=[5,3,8,1]; L.sort(); print(L)
P2 🧠 · L=[1,2,3]; L.insert(1,9); print(L)
9 is inserted at index 1; everything from there shifts right.
P3 🧠 · L=[10,20,30]; print(L[-1] + L[0])
Last (30) + first (10) = 40.
8.7 Debugging drill
L = [3, 1, 2] biggest = L.sort() print(biggest[-1])
Show fix
Bug: L.sort() returns None, so biggest is None and indexing it errors. Fix: sort first, then read: L.sort() then print(L[-1]) — or use biggest = sorted(L)[-1].
8.8 What did you learn?
Revision notes
- List = ordered, mutable,
[ ] - Index & slice like strings
- Add: append, insert, extend
- Remove: remove(value), pop(index)
- Reorder: sort, reverse (in place → None)
Top mistakes
L = L.sort()→ None- append vs extend confusion
- remove(value) vs pop(index)
- remove() on missing value → error
8.9 CBSE-style questions
Q1 · 1 mark · Difference between append() and extend().
Answer: append(x) adds x as a single element (even if x is a list). extend(iterable) adds each element of the iterable individually.
Q2 · 3 marks · Program: find the largest and smallest value in a list without using max/min.
L = [40, 12, 88, 5, 63] big = small = L[0] for x in L: if x > big: big = x if x < small: small = x print("Largest:", big, "Smallest:", small)
Start both at the first element, then compare each item and update. Output: Largest: 88 Smallest: 5.
Q3 · 1 mark · Assertion–Reason
A: sorted(L) changes the original list L. R: sorted() returns a new sorted list and leaves L unchanged.
Answer: A is false, R is true. R explains why A is false. (list.sort() changes in place; sorted() does not.)
8.10 Challenge
Show solution
nums = [4, 7, 10, 15, 22] evens = [] for n in nums: if n % 2 == 0: evens.append(n) print(evens) # [4, 10, 22]
Start with an empty list, test each number with % 2 == 0, and append the ones that pass.
Tuples
Like lists, but locked. An ordered collection you cannot change — why that matters, how it differs from a list, and the packing/unpacking tricks CBSE tests.
9.1 What is a tuple?
Concept. A tuple is an ordered collection of values inside round brackets ( ). It behaves like a list for reading, but it is immutable — once created, you cannot change, add, or remove items.
t = (10, 20, 30, 40) print(t[0]) # 10 print(t[-1]) # 40 print(t[1:3]) # (20, 30) print(len(t)) # 4
[ ] = list (mutable), ( ) = tuple (immutable), { } = dictionary/set. This is a guaranteed 1-mark identification question.9.2 The single-element trap
a = (5) # NOT a tuple — just the number 5 b = (5,) # a tuple with one element print(type(a)) # <class 'int'> print(type(b)) # <class 'tuple'>
(5,). Without the comma, the brackets are just grouping and you get a plain value. This is a classic exam trick.9.3 Trying to change a tuple
t = (1, 2, 3) # t[0] = 99 -> TypeError: cannot change a tuple print(t)
9.4 Tuple methods & operations
Because tuples can't change, they only have two methods: count() and index(). But the usual operations still work.
| Operation | Example | Result |
|---|---|---|
Concatenation + | (1,2) + (3,4) | (1, 2, 3, 4) |
Repetition * | (0,) * 3 | (0, 0, 0) |
Membership in | 3 in (1,2,3) | True |
count(x) | (1,1,2).count(1) | 2 |
index(x) | (5,6,7).index(6) | 1 |
max/min/sum | max((4,9,2)) | 9 |
9.5 Packing and unpacking (very examinable)
t = (18, "Ahana", 95.5) # packing age, name, marks = t # unpacking print(name, age, marks)
a, b = b, a. This is a favourite short-answer/output question.9.6 Quick Quiz
type((7)) is…t?a, b = 3, 7 then a, b = b, a. Now a is…9.7 Output prediction
P1 · t=(1,2,3); print(t*2)
P2 · print((1,2)+(3,))
P3 🧠 · t=(5,); print(len(t))
The trailing comma makes it a one-element tuple, length 1.
9.8 Debugging drill
t = (10, 20, 30) t.append(40) print(t)
Show fix
Bug: tuples have no append() — they're immutable → AttributeError. Fix: if you must add, convert to a list, or build a new tuple: t = t + (40,).
9.9 What did you learn?
Revision notes
- Tuple = ordered, immutable,
( ) - Index & slice like a list
- One element needs a comma:
(5,) - Only
count()&index() - Unpacking & one-line swap
Top mistakes
- Forgetting the trailing comma
- Trying to edit / append
- Confusing
( )with[ ]
9.10 CBSE-style questions
Q1 · 1 mark · Give two differences between a list and a tuple.
Answer: (1) A list is mutable (can change); a tuple is immutable. (2) Lists use [ ], tuples use ( ). (Also: lists have many methods; tuples have only count and index.)
Q2 · 2 marks · How do you create a tuple with a single element? Why?
Answer: Write t = (5,) with a trailing comma. Without the comma, (5) is just the value 5 in brackets; the comma is what tells Python it's a tuple.
Q3 · 1 mark · Assertion–Reason
A: A tuple can be used as a dictionary key but a list cannot. R: Dictionary keys must be immutable.
Answer: Both true, and R correctly explains A. (Tuples are immutable, so they qualify as keys.)
9.11 Challenge
Show solution
t = (12, 8, 20, 4) print("Sum:", sum(t)) print("Average:", sum(t) / len(t))
sum() and len() work directly on tuples. Output: Sum 44, Average 11.0.
Dictionaries
Storing data as key–value pairs — the structure behind so many CBSE case-based questions. Creating, accessing, updating, and looping through dictionaries.
10.1 What is a dictionary?
Concept. A dictionary stores data as key : value pairs inside curly brackets { }. Instead of finding items by position (0, 1, 2…), you find them by their key.
student = {"name": "Ahana", "age": 18, "marks": 95} print(student["name"]) # Ahana print(student["marks"]) # 95
10.2 Adding & updating
d = {"a": 1, "b": 2} d["c"] = 3 # new key -> ADD d["a"] = 99 # existing key -> UPDATE print(d)
d[key] = value does two jobs: if the key is new it adds a pair; if the key already exists it overwrites the old value. Because keys are unique, you can't have two pairs with the same key.10.3 Accessing safely with get()
d = {"x": 10} # print(d["y"]) -> KeyError (crash) print(d.get("y")) # None (no crash) print(d.get("y", 0)) # 0 (default if missing)
d["y"] raises a KeyError. d.get("y") returns None instead of crashing — and you can give a fallback default. This difference is frequently tested.10.4 Important dictionary methods
| Method | Returns / does | Example (on d={'a':1,'b':2}) |
|---|---|---|
keys() | All keys | dict_keys(['a','b']) |
values() | All values | dict_values([1,2]) |
items() | All key–value pairs | [('a',1),('b',2)] |
get(k) | Value for k, or None | d.get('a') → 1 |
update(d2) | Merge another dict in | d.update({'c':3}) |
pop(k) | Remove key k, return its value | d.pop('a') → 1 |
10.5 Looping through a dictionary
marks = {"Maths": 95, "CS": 98, "Eng": 88} for subject, score in marks.items(): print(subject, "->", score)
for k in d: gives you the keys. To get keys and values together, loop over d.items() as shown above.10.6 Quick Quiz
d["z"] gives…get() to avoid it.items() gives (key, value) tuples; there is no pairs().10.7 Output prediction
P1 · d={'a':1}; d['a']=5; print(d)
Existing key is overwritten, not duplicated.
P2 🧠 · d={'x':1,'y':2}; print(d.get('z',99))
Key 'z' is missing, so the default 99 is returned.
P3 🧠 · d={1:'a',2:'b'}; print(len(d))
len() counts the number of key–value pairs.
10.8 Debugging drill
d = {"name": "Ravi"} print(d["age"])
Show fix
Bug: KeyError — 'age' isn't in the dictionary. Fix: use d.get("age") (returns None safely) or add the key first: d["age"] = 17.
10.9 What did you learn?
Revision notes
- Dict = key:value pairs,
{ }, mutable - Access by key, not index
- Keys unique & immutable
d[k]=vadds or updatesget, keys, values, items, update, pop
Top mistakes
- KeyError on missing key
- Using a list as a key
- Expecting duplicate keys
- Looping keys but wanting values
10.10 CBSE-style questions
Q1 · 1 mark · Why must dictionary keys be immutable?
Answer: Python uses the key to locate the value internally (via hashing). If a key could change, its stored location would become invalid, so only immutable types (string, number, tuple) are allowed as keys.
Q2 · 3 marks · Program: count how many times each character appears in a string, using a dictionary.
s = "banana" freq = {} for ch in s: if ch in freq: freq[ch] += 1 else: freq[ch] = 1 print(freq)
Output: {'b': 1, 'a': 3, 'n': 2}. For each character, add 1 if seen before, else start at 1. This exact pattern is extremely common in boards.
Q3 · 1 mark · Assertion–Reason
A: A dictionary can have two identical keys. R: Dictionary keys are unique.
Answer: A is false, R is true; R explains why A is false — assigning to an existing key overwrites it.
10.11 Challenge
Show solution
marks = {"Maths": 95, "CS": 98, "Eng": 88} top = "" best = -1 for subject, score in marks.items(): if score > best: best = score top = subject print("Highest:", top, best)
Track the best score seen and the subject that has it. Output: Highest: CS 98.
Functions
Reusable blocks of code you define once and call many times — parameters, return values, default arguments, and the built-in functions CBSE expects you to know cold.
11.1 What is a function?
Concept. A function is a named block of code that performs a task. You define it once, then call it whenever you need it — avoiding repetition and keeping programs organised.
Three types of functions in the CBSE syllabus
| Type | Meaning | Example |
|---|---|---|
| Built-in | Come with Python | len(), print(), max() |
| Module | From an imported library | math.sqrt(), random.randint() |
| User-defined | Written by you with def | def greet(): |
11.2 Defining and calling
Syntax
def function_name(parameters): # body (indented) statement
def greet(name): print("Hello,", name) greet("Ahana") # call 1 greet("Ravi") # call 2
def only creates the function; nothing runs until you call it with greet("Ahana"). The body between def and the next un-indented line is the function.11.3 Parameters and arguments
Parameter = the variable named in the definition. Argument = the actual value you pass when calling.
def add(a, b): # a, b are PARAMETERS print(a + b) add(10, 20) # 10, 20 are ARGUMENTS
11.4 Return values — the big idea
return sends a value back to whoever called the function, so the result can be stored and reused. Printing shows a value; returning gives it back.
def square(n): return n * n result = square(5) # store the returned value print(result) # 25 print(square(3) + square(4)) # 9 + 16 = 25
prints a value shows it but hands back None, so you can't do maths with it. A function that returns a value gives it back so you can store or reuse it. Mixing these up is one of the most common exam errors.return in the same block never runs — return exits the function immediately. And a function with no return automatically returns None.11.5 Default parameters
Give a parameter a default so the caller may skip it.
def power(base, exp=2): # exp defaults to 2 return base ** exp print(power(5)) # 25 (uses default exp=2) print(power(5, 3)) # 125 (overrides default)
def f(a, b=2) is fine; def f(a=1, b) is a SyntaxError.square()/sum_upto() function should return.11.6 Using library functions (modules)
import math print(math.sqrt(16)) # 4.0 print(math.pi) # 3.14159... import random print(random.randint(1, 6)) # a dice roll 1-6
math (sqrt, floor, ceil, pi) and random (randint(a,b) gives an integer including both ends; random() gives a float 0–1).11.7 Quick Quiz
def to define a function.return statement returns…None.def f(a, b=5), b is a…b has a default value, so it's optional when calling.random.randint(1, 6) can return…randint includes both endpoints — unlike range.11.8 Output prediction
P1 · def f(x): return x+1 then print(f(f(3)))
Inner f(3)=4, outer f(4)=5.
P2 🧠 · def g(): print("A"); return; print("B") then g()
"B" never prints — return exits the function first.
P3 🧠 · def h(a,b=10): return a+b then print(h(5))
b uses its default 10; 5 + 10 = 15.
11.9 Debugging drill
def total(a, b): sum = a + b x = total(3, 4) print(x * 2)
Show fix
Bug: the function computes sum but never returns it, so x is None and x * 2 raises a TypeError. Fix: add return sum as the last line of the function.
11.10 What did you learn?
Revision notes
- Define with
def, then call - Parameter (definition) vs argument (call)
returnsends a value back & exits- No return → None
- Defaults come last
- 3 types: built-in, module, user-defined
Top mistakes
- Forgetting to call the function
- print vs return confusion
- Code after return (dead)
- Default before non-default param
11.11 CBSE-style questions
Q1 · 1 mark · Difference between a parameter and an argument.
Answer: A parameter is the variable listed in the function definition; an argument is the actual value passed to the function when it is called.
Q2 · 3 marks · Write a function is_prime(n) that returns True if n is prime, else False.
def is_prime(n): if n < 2: return False for i in range(2, n): if n % i == 0: return False return True print(is_prime(7)) # True print(is_prime(9)) # False
If any number from 2 up to n−1 divides n exactly, n is not prime, so we return False immediately. If the loop finishes with no divisor found, n is prime.
Q3 · 1 mark · Assertion–Reason
A: Statements written after a return in the same block will execute. R: return immediately ends the function.
Answer: A is false, R is true; R explains why A is false.
11.12 Challenge
factorial(n) that returns n! (e.g. 5! = 120).
Show solution
def factorial(n): result = 1 for i in range(1, n + 1): result *= i return result print(factorial(5)) # 120
Start result at 1 and multiply by every number from 1 to n. Returning the value (not printing) lets you reuse it in bigger calculations.
Scope of Variables
Where a variable "lives" and where it can be seen — local vs global, why a function can read a global but not change it by default, and the global keyword.
12.1 What is scope?
Concept. Scope is the region of a program where a variable can be used. A variable created inside a function is local — it exists only while that function runs. A variable created outside all functions is global — visible throughout the file.
12.2 Local variables
def show(): x = 10 # x is LOCAL to show() print(x) show() # print(x) -> NameError: x not defined out here
print(x) after the function raises a NameError. Local means local.12.3 Global variables
count = 100 # GLOBAL def display(): print(count) # can READ the global display() print(count)
12.4 The key rule — read yes, change no
A function can read a global variable freely. But if you try to assign to it inside the function, Python creates a new local variable instead — the global is untouched.
x = 5 def change(): x = 99 # makes a NEW local x, not the global print("inside:", x) change() print("outside:", x) # global unchanged
12.5 The global keyword
To actually change a global from inside a function, declare it global first.
x = 5 def change(): global x # now x refers to the global x = 99 print("inside:", x) change() print("outside:", x) # now really changed
global sparingly. It's examinable, but in real programs it's usually cleaner to return a value and reassign, rather than reaching into globals.12.6 Quick Quiz
global keyword.global x tells Python to use the outer variable.x=5; inside a function x=10 (no global). Outside, x is…12.7 Output prediction
P1 🧠 · global a=1; func does a=2; print(a); then outside print(a)
Inside prints the local 2; outside the global is still 1.
P2 🧠 · same but with global a declared
Now the function changes the actual global.
12.8 Debugging drill
def setValue(): result = 42 setValue() print(result)
Show fix
Bug: result is local to setValue(), so print(result) outside raises NameError. Fix: return result from the function and capture it: r = setValue(); print(r).
12.9 What did you learn?
Revision notes
- Local = inside a function only
- Global = outside all functions
- Functions can read globals
- Assigning inside makes a local (shadows global)
global xto really change it
Top mistakes
- Using a local outside → NameError
- Expecting an inside-assignment to change the global
- Overusing
global
12.10 CBSE-style questions
Q1 · 1 mark · What is a local variable?
Answer: A variable defined inside a function; it is accessible only within that function and ceases to exist once the function finishes.
Q2 · 2 marks · Why does assigning to a global inside a function not change it, and how do you fix it?
Answer: By default, an assignment inside a function creates a new local variable that shadows the global, leaving the global unchanged. To modify the actual global, declare it with the global keyword before assigning.
Q3 · 1 mark · Assertion–Reason
A: A function can always modify a global variable directly. R: Reading a global inside a function is allowed.
Answer: A is false (modification needs global), R is true.
File Handling — The Big Picture
Why programs need files, the three file types in the CBSE syllabus, file modes, and the safe with pattern that every file program should use.
13.1 Why do we need files?
Concept. Variables live in memory (RAM) and vanish when the program ends. A file stores data on disk permanently, so it's still there next time you run the program. This permanence is called persistence.
13.2 The three file types (know these cold)
| Type | Stores | Readable by humans? | Example |
|---|---|---|---|
| Text file | Characters (readable text) | Yes — open in Notepad | .txt, notes, logs |
| Binary file | Raw bytes / Python objects | No — looks like gibberish | .dat, images |
| CSV file | Table data, comma-separated | Yes — a plain-text table | .csv, spreadsheets |
13.3 Opening and closing a file
To use a file you open it (getting a file object), work with it, then close it to save changes and free the resource.
Syntax
f = open("filename.txt", "mode") # ... use f ... f.close()
13.4 File modes — the master table
| Mode | Meaning | If file missing | Existing data |
|---|---|---|---|
"r" | Read (default) | Error | Kept |
"w" | Write | Created | Erased! |
"a" | Append (add to end) | Created | Kept |
"r+" | Read + write | Error | Kept |
"rb", "wb", "ab" | Same, but binary | — | — |
"w" mode wipes everything in it before you write a single character. If you want to keep old data and add new, use "a" (append). This is a favourite exam trap and a real-world disaster.w and a mode?" is asked almost every year. Model answer: w overwrites (erases existing content); a appends (adds new data at the end, keeping the old).13.5 The safe way — with
The with statement opens a file and closes it automatically, even if an error occurs. This is the recommended, exam-safe pattern.
with open("notes.txt", "w") as f: f.write("Hello file") # file is closed automatically here
with, you never call close() yourself — Python does it for you when the block ends. Fewer bugs, cleaner marks.13.6 Quick Quiz
"w" truncates the file to empty before writing.with open(...) is…with guarantees the file is closed even if an error occurs."a" appends new content at the end, keeping the old.13.7 What did you learn?
Revision notes
- Files give persistence (survive after program ends)
- Three types: text, binary, CSV
- Modes: r (read), w (overwrite), a (append)
- Add 'b' for binary: rb, wb, ab
with open(...)auto-closes
Top mistakes
- Using "w" and wiping data
- Reading a file that doesn't exist
- Forgetting to close (use
with)
13.8 CBSE-style questions
Q1 · 1 mark · Name the three types of files handled in Python.
Answer: Text files, binary files, and CSV files.
Q2 · 2 marks · What is the difference between "w" and "a" modes?
Answer: "w" opens a file for writing and erases any existing content (creating the file if it doesn't exist). "a" opens for appending and adds new data to the end, preserving existing content.
Q3 · 1 mark · Assertion–Reason
A: Data stored in a variable is lost when the program ends. R: Files provide permanent (persistent) storage.
Answer: Both true; R is the reason we use files, and it correctly explains why A motivates file handling.
Text Files
Reading and writing plain-text files — the read methods, the write methods, the newline gotcha, and the standard "count words / lines" programs CBSE asks every year.
14.1 Writing to a text file
| Method | Does |
|---|---|
write(s) | Writes the string s (no automatic newline) |
writelines(list) | Writes each string in a list (still no auto newline) |
with open("notes.txt", "w") as f: f.write("Line one\n") # \n = newline f.write("Line two\n")
print(), write() does not add a newline automatically. If you forget \n, everything runs together on one line: Line oneLine two. This is one of the most common file-handling mistakes.14.2 Reading a text file — three methods
| Method | Returns |
|---|---|
read() | The whole file as one string |
readline() | One line (including its \n) |
readlines() | A list of all lines |
with open("notes.txt", "r") as f: data = f.read() print(data)
The cleanest way to read line by line
with open("notes.txt", "r") as f: for line in f: # loop directly over the file print(line.strip()) # strip() removes the trailing \n
for line in f: reads one line at a time and is memory-friendly for large files. Use line.strip() to drop the newline so lines don't print with blank gaps.read() = photocopy the whole book into one long sheet. readline() = read just the next single line aloud. readlines() = tear out every line and stack them as a list of strips.14.3 Appending to a text file
with open("notes.txt", "a") as f: f.write("Line three\n") # old lines stay, this is added
14.4 The classic CBSE text-file programs
(a) Count the number of lines
count = 0 with open("notes.txt", "r") as f: for line in f: count += 1 print("Lines:", count)
(b) Count words
words = 0 with open("notes.txt", "r") as f: for line in f: words += len(line.split()) # split on spaces print("Words:", words)
line.split() with no argument splits on any whitespace and returns a list of words; len(...) counts them. This "count words" pattern and its cousins (count lines, count characters, count lines starting with a vowel) appear constantly.(c) Count lines starting with a particular letter
count = 0 with open("notes.txt", "r") as f: for line in f: if line[0] == "T": count += 1 print(count)
14.5 Quick Quiz
read() returns…read() returns everything as a single string.readlines() (plural) gives a list; readline() gives one line.write() differs from print() because it…\n yourself with write()."a b c".split() gives a list of length…14.6 Output prediction
P1 · "hello world".split()
P2 🧠 · file has 3 lines; len(f.readlines()) gives…
readlines() returns a list with one item per line.
14.7 Debugging drill
f = open("data.txt", "w") data = f.read() print(data)
Show fix
Bug: the file is opened in "w" (write) mode, so read() fails — you can't read in write mode (and "w" also just erased the file). Fix: open in "r" mode to read: open("data.txt", "r").
14.8 What did you learn?
Revision notes
- Write:
write(),writelines() - Read:
read(),readline(),readlines() write()needs manual\nfor line in f:for line-by-linesplit()to count words
Top mistakes
- Forgetting
\nin write - Reading in "w" mode
- Confusing readline / readlines
- Not stripping the newline
14.9 CBSE-style questions
Q1 · 1 mark · Difference between readline() and readlines().
Answer: readline() reads and returns a single line as a string. readlines() reads all lines and returns them as a list of strings.
Q2 · 3 marks · Program: read a text file and count how many words start with a vowel.
count = 0 with open("notes.txt", "r") as f: for line in f: for word in line.split(): if word[0].lower() in "aeiou": count += 1 print("Words starting with a vowel:", count)
Split each line into words, check the first letter of each word against the vowels. Lowercasing handles capital letters too.
Q3 · 1 mark · Assertion–Reason
A: write() automatically moves to a new line after each call. R: write() adds \n like print().
Answer: Both false. write() does not add a newline; you must include \n yourself.
14.10 Challenge
source.txt into dest.txt, converting everything to uppercase.
Show solution
with open("source.txt", "r") as src: text = src.read() with open("dest.txt", "w") as dst: dst.write(text.upper())
Read the whole file, transform the string with upper(), and write it to the new file. Two with blocks keep both files handled safely.
Binary Files
Storing real Python objects — lists, dictionaries — exactly as they are, using the pickle module. The dump/load pair and the record-update pattern CBSE asks for.
15.1 Why binary files?
Concept. A binary file stores data as raw bytes, keeping the exact structure of a Python object. A text file would turn a list into plain characters and lose its "list-ness"; a binary file keeps a list a list, a dictionary a dictionary.
15.2 The pickle module
Python's pickle module does the conversion. Two functions do all the work:
| Function | Does | Direction |
|---|---|---|
pickle.dump(obj, f) | Writes (serialises) an object to a binary file | object → file |
pickle.load(f) | Reads (deserialises) an object back | file → object |
"wb" (write binary), "rb" (read binary), "ab" (append binary). You must import pickle first. "Pickling" = writing; "unpickling" = reading.15.3 Writing an object
import pickle student = {"name": "Ahana", "marks": 95} with open("student.dat", "wb") as f: pickle.dump(student, f) print("Saved!")
15.4 Reading it back
import pickle with open("student.dat", "rb") as f: data = pickle.load(f) print(data) print(data["name"]) # works — it's a real dict again
15.5 Storing many records
A common pattern: store a list of records, or dump each record one by one and read them in a loop until the file ends.
import pickle records = [ {"roll": 1, "name": "A"}, {"roll": 2, "name": "B"}, ] with open("data.dat", "wb") as f: pickle.dump(records, f) # store whole list at once with open("data.dat", "rb") as f: back = pickle.load(f) for r in back: print(r["roll"], r["name"])
15.6 Reading until end-of-file (multiple dumps)
If you dump records one at a time, reading past the end raises EOFError. Catch it to stop cleanly.
import pickle with open("data.dat", "rb") as f: while True: try: rec = pickle.load(f) print(rec) except EOFError: break # reached end — stop
pickle.load() when the file has no more objects raises EOFError. That's expected — wrap the read loop in try/except EOFError to end gracefully. (You'll learn try/except fully in Chapter 17.)"wb". You cannot edit one record in place inside a binary file.15.7 Quick Quiz
pickle serialises and deserialises Python objects.pickle.dump() is used to…dump writes (object → file); load reads (file → object)."wb" = write binary.load() raises…15.8 Behaviour prediction
P1 · You dump a list, then load it. The type you get back is…
Pickle preserves the exact type. A list stays a list.
P2 🧠 · You open a binary file in "w" (not "wb") and dump. Result?
Pickle writes bytes; a text-mode file expects strings, so it errors. Always use "wb".
15.9 Debugging drill
import pickle with open("d.dat", "rb") as f: data = pickle.dump(f)
Show fix
Bug: two errors — reading should use load, not dump; and load takes the file, dump takes (object, file). Fix: data = pickle.load(f).
15.10 What did you learn?
Revision notes
- Binary = raw bytes, keeps object type
import pickledump(obj, f)writes;load(f)reads- Modes: wb, rb, ab
- Loop-read → catch EOFError
- Update = read all → change → rewrite
Top mistakes
- Using "w"/"r" instead of "wb"/"rb"
- Swapping dump and load
- Not handling EOFError
- Trying to edit one record in place
15.11 CBSE-style questions
Q1 · 1 mark · What is pickling?
Answer: Pickling is the process of converting a Python object into a byte stream and writing it to a binary file (serialisation), done with pickle.dump().
Q2 · 3 marks · Program: write a list of three student dictionaries to a binary file and read them back.
import pickle students = [ {"roll": 1, "name": "Amit"}, {"roll": 2, "name": "Bina"}, {"roll": 3, "name": "Chetan"}, ] with open("stu.dat", "wb") as f: pickle.dump(students, f) with open("stu.dat", "rb") as f: for s in pickle.load(f): print(s["roll"], s["name"])
Q3 · 1 mark · Assertion–Reason
A: A binary file can be read in a text editor like a text file. R: Binary files store data as human-readable characters.
Answer: Both false. Binary files store raw bytes and appear as unreadable symbols.
15.12 Challenge
Show solution
import pickle with open("emp.dat", "rb") as f: emps = pickle.load(f) for e in emps: e["salary"] = e["salary"] * 1.1 with open("emp.dat", "wb") as f: pickle.dump(emps, f)
This is the update-a-record pattern: read all → modify in memory → rewrite the whole list. There is no way to edit just one record inside the binary file directly.
CSV Files
Comma-separated tables — the format that opens in Excel. Using the csv module to write and read rows, with the newline detail that CBSE loves to test.
16.1 What is a CSV file?
Concept. CSV stands for Comma-Separated Values. Each line is one row of a table, and commas separate the columns. It's plain text, so it opens in Notepad or Excel.
Roll,Name,Marks 1,Ahana,95 2,Ravi,88
16.2 The csv module
You import csv, then use a writer to save rows and a reader to read them.
| Object / method | Does |
|---|---|
csv.writer(f) | Creates a writer for file f |
writer.writerow(list) | Writes one row from a list |
writer.writerows(list_of_lists) | Writes many rows at once |
csv.reader(f) | Creates a reader you loop over |
16.3 Writing a CSV file
import csv with open("marks.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["Roll", "Name", "Marks"]) # header w.writerow([1, "Ahana", 95]) w.writerow([2, "Ravi", 88])
newline="" When opening a CSV file for writing, add newline="" in open(). Without it, Windows inserts an extra blank line between rows. This exact detail is frequently asked ("why do blank rows appear?").16.4 Reading a CSV file
import csv with open("marks.csv", "r") as f: r = csv.reader(f) for row in r: print(row)
"95". To do arithmetic, convert with int() first: int(row[2]). Forgetting this causes wrong sums or TypeErrors.16.5 Skipping the header
import csv with open("marks.csv", "r") as f: r = csv.reader(f) next(r) # skip the header row for row in r: print(row[1], "scored", row[2])
next(reader) reads and throws away one row — handy for skipping the header before processing the data rows.16.6 Quick Quiz
newline="" when writing a CSV?csv.reader yields each row as a list of string values.writerows() takes a list of rows.16.7 Behaviour prediction
P1 · A CSV cell holds 88. After reading, type(row[2]) is…
CSV values always come back as strings; convert for maths.
P2 🧠 · You write with writerow("Ahana") instead of writerow(["Ahana"]). What happens?
A string is iterable, so each character becomes its own column. Always pass a list.
16.8 Debugging drill
import csv with open("m.csv", "r") as f: r = csv.reader(f) total = 0 for row in r: total += row[2] print(total)
Show fix
Bug: row[2] is a string, so += tries to add strings (or errors on the header). Fix: skip the header with next(r) and convert: total += int(row[2]).
16.9 What did you learn?
Revision notes
- CSV = comma-separated text table
import csv- Write:
writer,writerow(s) - Read:
reader, loop rows (lists of str) - Use
newline=""when writing next(reader)skips header
Top mistakes
- Forgetting
newline=""→ blank rows - Not converting str → int
- Passing a string to writerow
- Not skipping the header
16.10 CBSE-style questions
Q1 · 1 mark · Which module is used to work with CSV files?
Answer: The csv module.
Q2 · 3 marks · Program: read "marks.csv" (Roll,Name,Marks) and print the average of the Marks column.
import csv total = 0 n = 0 with open("marks.csv", "r") as f: r = csv.reader(f) next(r) # skip header for row in r: total += int(row[2]) n += 1 print("Average:", total / n)
Skip the header, convert each Marks cell with int(), accumulate and divide by the count.
Q3 · 1 mark · Assertion–Reason
A: Numbers read from a CSV file can be used in arithmetic directly. R: csv.reader returns every value as a string.
Answer: A is false, R is true; R explains why A is false — you must convert first.
16.11 Challenge
Show solution
import csv with open("marks.csv", "r") as f: rows = list(csv.reader(f)) header = rows[0] data = rows[1:] with open("toppers.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(header) for row in data: if int(row[2]) > 90: w.writerow(row)
Read all rows, keep the header, then write back only the rows whose Marks (converted to int) exceed 90.
Exception Handling
Stopping your program from crashing when something goes wrong — try, except, else, finally, and the common exceptions CBSE expects you to name.
17.1 What is an exception?
Concept. An exception is an error that occurs while the program is running (a runtime error). Normally it crashes the program. Exception handling lets you catch the error and respond gracefully instead of crashing.
17.2 Common exceptions to know
| Exception | Happens when… |
|---|---|
ValueError | int("abc") — wrong value for the type |
ZeroDivisionError | dividing by zero |
TypeError | "5" + 3 — incompatible types |
IndexError | list/string index out of range |
KeyError | missing dictionary key |
NameError | using a variable that isn't defined |
FileNotFoundError | opening a file that doesn't exist |
ValueError, ZeroDivisionError, IndexError, and KeyError.17.3 The try–except block
Syntax
try: # risky code that might fail except ErrorType: # runs only if that error happens
try: a = int(input("Number: ")) print(100 / a) except ZeroDivisionError: print("Cannot divide by zero") except ValueError: print("Please enter a valid number")
except blocks, one per error type. Python runs the first one that matches the error that actually occurred.17.4 else and finally
| Block | Runs when… |
|---|---|
try | always attempted first |
except | only if a matching error occurs |
else | only if no error occurred |
finally | always, error or not |
try: x = 10 / 2 except ZeroDivisionError: print("Error") else: print("Success:", x) # no error -> runs finally: print("Done (always runs)")
finally finally runs no matter what — used to release resources like closing a file whether or not an error happened. This is a classic "what is the use of finally?" question.- A bare
except:catches every error, hiding bugs. Prefer naming the specific exception. - Order matters: put specific exceptions before a general
Exception. trymust be followed by at least oneexceptorfinally.
except would catch it.17.5 Quick Quiz
int("hello") raises…finally executes whether or not an exception occurred.else in try/except runs when…else block runs only if the try succeeded with no exception.17.6 Output prediction
P1 · try: print(5/0) except ZeroDivisionError: print("oops")
P2 🧠 · try: print("A") except: print("B") finally: print("C")
No error, so B is skipped; C (finally) always runs.
P3 🧠 · L=[1,2]; try: print(L[5]) except IndexError: print("bad index")
Index 5 is out of range → IndexError, caught cleanly.
17.7 Debugging drill
try: n = int(input()) print(10 / n)
Show fix
Bug: the try has no except/finally, and the division is outside the try. Fix: put risky code inside try and add an except:
try: n = int(input()) print(10 / n) except (ValueError, ZeroDivisionError): print("Invalid input")
17.8 What did you learn?
Revision notes
- Exception = runtime error
try/exceptcatches it- Multiple
exceptblocks allowed else= no error;finally= always- Know the common exception names
Top mistakes
- try without except/finally
- Bare
except:hiding bugs - Risky code outside the try
- Wrong exception name
17.9 CBSE-style questions
Q1 · 1 mark · Name the exception raised when dividing by zero.
Answer: ZeroDivisionError.
Q2 · 2 marks · What is the purpose of the finally block?
Answer: The finally block always executes, whether or not an exception occurred. It is used for clean-up actions that must happen regardless, such as closing a file or releasing resources.
Q3 · 3 marks · Program: safely divide two numbers input by the user, handling both invalid input and division by zero.
try: a = int(input("a: ")) b = int(input("b: ")) print("Result:", a / b) except ValueError: print("Enter valid integers") except ZeroDivisionError: print("b cannot be zero") finally: print("Program finished")
Q4 · 1 mark · Assertion–Reason
A: The else block of a try statement runs when an exception occurs. R: The else block runs only when the try block completes without any exception.
Answer: A is false, R is true; R explains why A is false.
17.10 Challenge
Show solution
try: with open("notes.txt", "r") as f: print(f.read()) except FileNotFoundError: print("File not found — please check the name.")
FileNotFoundError is the specific exception for a missing file. Catching it lets the program continue instead of crashing.
Data Structures: Stack
The one data structure named in the CBSE syllabus — a Last-In-First-Out (LIFO) stack built with a Python list. Push, pop, peek, and the classic applications examiners ask about.
18.1 What is a stack?
Concept. A stack is a collection where you add and remove items from one end only, called the top. The last item you put in is the first one you take out — this rule is called LIFO (Last In, First Out).
18.2 Stack operations
| Operation | Meaning | List method used |
|---|---|---|
| push | Add an item to the top | list.append(x) |
| pop | Remove & return the top item | list.pop() |
| peek / top | Look at the top item without removing | list[-1] |
| isEmpty | Check if the stack has no items | len(list) == 0 |
append() to add and pop() to remove. The "top" is the last element (list[-1]).18.3 Push and pop in action
stack = [] stack.append(10) # push 10 stack.append(20) # push 20 stack.append(30) # push 30 print("Stack:", stack) top = stack.pop() # pop -> removes 30 (last in) print("Popped:", top) print("Now:", stack) print("Top now:", stack[-1]) # peek
18.4 The empty-stack trap
stack = [] # stack.pop() -> IndexError: pop from empty list if len(stack) == 0: print("Stack is empty (underflow)") else: print(stack.pop())
isEmpty (len(stack)==0) before popping or peeking. This is called stack underflow.18.5 A menu-driven stack (exam pattern)
def push(stack, item): stack.append(item) def pop(stack): if len(stack) == 0: return "Underflow" return stack.pop() def peek(stack): if len(stack) == 0: return "Empty" return stack[-1] s = [] push(s, 5) push(s, 8) print(peek(s)) # 8 print(pop(s)) # 8 print(pop(s)) # 5 print(pop(s)) # Underflow
18.6 Quick Quiz
append() adds to the top (end) of the stack.18.7 Output prediction
P1 · Push A,B,C. Pop, pop. Print top.
After two pops (C then B), the top is A.
P2 🧠 · s=[1,2,3]; s.append(s.pop()+s.pop()); print(s)
First pop()→3, second pop()→2, sum 5 appended. List had 1 left, so [1, 5].
18.8 Debugging drill
stack = [] stack.append(5) print(stack.pop()) print(stack.pop()) # crash?
Show fix
Bug: the second pop() runs on an empty stack → IndexError. Fix: guard it: if len(stack) > 0: print(stack.pop()) else: print("Underflow").
18.9 What did you learn?
Revision notes
- Stack = LIFO, one end (top)
- push →
append() - pop →
pop() - peek →
list[-1] - isEmpty →
len()==0 - Apps: undo, back button, reversing
Top mistakes
- Popping an empty stack (underflow)
- Confusing LIFO with FIFO
- Using insert(0) instead of append
18.10 CBSE-style questions
Q1 · 1 mark · What does LIFO stand for and which structure uses it?
Answer: Last In, First Out — used by a stack.
Q2 · 4 marks · Write push() and pop() functions for a stack of numbers, handling underflow.
def push(stack, x): stack.append(x) def pop(stack): if len(stack) == 0: print("Underflow") return None return stack.pop()
Q3 · 3 marks · Program: use a stack to reverse a string.
s = "PYTHON" stack = [] for ch in s: stack.append(ch) # push each char rev = "" while len(stack) > 0: rev += stack.pop() # pop reverses order print(rev) # NOHTYP
Because a stack is LIFO, popping the pushed characters gives them back in reverse — a neat demonstration of the LIFO idea.
Q4 · 1 mark · Assertion–Reason
A: In a stack, elements can be removed from any position. R: A stack allows insertion and deletion only at the top.
Answer: A is false, R is true; R explains why A is false.
18.11 Challenge
Show solution
expr = "(a+b)" stack = [] balanced = True for ch in expr: if ch == "(": stack.append(ch) elif ch == ")": if len(stack) == 0: balanced = False else: stack.pop() if balanced and len(stack) == 0: print("Balanced") else: print("Not balanced")
Push every "(" and pop on every ")". If you ever try to pop when empty, or the stack isn't empty at the end, the brackets don't match. This is a favourite higher-order stack application.
Searching & Sorting
Two everyday algorithm tasks — finding an item (linear search) and arranging items in order (bubble and insertion sort). Understand how each works step by step, not just the code.
19.1 Linear search
Concept. Linear search checks each element one by one, from the start, until it finds the target or reaches the end. Simple, and works on any list (sorted or not).
def linear_search(L, target): for i in range(len(L)): if L[i] == target: return i # found — return position return -1 # not found nums = [4, 9, 2, 7, 5] print(linear_search(nums, 7)) # 3 print(linear_search(nums, 8)) # -1
19.2 Bubble sort
Concept. Bubble sort repeatedly compares adjacent pairs and swaps them if they're in the wrong order. After each full pass, the largest remaining value "bubbles" to the end.
def bubble_sort(L): n = len(L) for i in range(n - 1): # number of passes for j in range(n - 1 - i): # compare pairs if L[j] > L[j + 1]: L[j], L[j + 1] = L[j + 1], L[j] # swap return L print(bubble_sort([5, 1, 4, 2]))
Trace of pass 1 on [5, 1, 4, 2]
| Compare | Action | List after |
|---|---|---|
| 5 > 1? | swap | [1, 5, 4, 2] |
| 5 > 4? | swap | [1, 4, 5, 2] |
| 5 > 2? | swap | [1, 4, 2, 5] |
After pass 1, the largest value (5) is at the end. Later passes sort the rest.
L[j], L[j+1] = L[j+1], L[j]. No temporary variable needed. Being asked to "dry run" (trace) bubble sort and show the list after each pass is extremely common.19.3 Insertion sort
Concept. Insertion sort builds the sorted list one item at a time: take each element and insert it into its correct place among the already-sorted items to its left.
def insertion_sort(L): for i in range(1, len(L)): key = L[i] j = i - 1 while j >= 0 and L[j] > key: L[j + 1] = L[j] # shift right j -= 1 L[j + 1] = key # place key return L print(insertion_sort([3, 1, 2]))
sorted() / .sort() are faster in practice — but boards want you to understand and trace the manual algorithms.19.4 Quick Quiz
19.5 Output / trace prediction
P1 · Linear search for 2 in [4,9,2,7] returns…
2 is at index 2.
P2 🧠 · One bubble pass on [3,2,1] gives…
3>2 swap → [2,3,1]; 3>1 swap → [2,1,3]. Largest (3) now at the end.
19.6 Debugging drill
def search(L, x): for i in range(len(L)): if L[i] == x: return i else: return -1
Show fix
Bug: the return -1 is inside the loop, so it exits after checking only the first element. Fix: move return -1 outside (after) the loop, so it only runs once every element has been checked.
19.7 What did you learn?
Revision notes
- Linear search: check each item; return index or −1
- Bubble sort: swap adjacent pairs; biggest bubbles to end each pass
- Insertion sort: insert each item into the sorted left part
- One-line swap:
a,b = b,a
Top mistakes
- Returning −1 inside the search loop
- Wrong inner range in bubble sort
- Forgetting the swap condition
19.8 CBSE-style questions
Q1 · 1 mark · What does a linear search return if the element is not found?
Answer: −1 (by convention), indicating the element is not present.
Q2 · 4 marks · Dry run bubble sort on [4, 3, 2, 1], showing the list after each pass.
| Pass | List after pass |
|---|---|
| 1 | [3, 2, 1, 4] |
| 2 | [2, 1, 3, 4] |
| 3 | [1, 2, 3, 4] |
Each pass moves the largest remaining value to its correct place at the right end.
Q3 · 3 marks · Program: count how many comparisons linear search makes to find a value.
def search_count(L, x): count = 0 for i in range(len(L)): count += 1 if L[i] == x: return i, count return -1, count print(search_count([4, 9, 2, 7], 7)) # (3, 4)
Q4 · 1 mark · Assertion–Reason
A: Bubble sort compares only the first and last elements. R: Bubble sort repeatedly compares and swaps adjacent elements.
Answer: A is false, R is true; R correctly describes bubble sort.
19.9 Challenge
Show solution
def bubble_desc(L): n = len(L) for i in range(n - 1): for j in range(n - 1 - i): if L[j] < L[j + 1]: # flipped > to < L[j], L[j + 1] = L[j + 1], L[j] return L print(bubble_desc([5, 1, 4, 2])) # [5, 4, 2, 1]
Changing the comparison from > to < reverses the sort direction. Understanding why one operator flips the whole result is exactly the higher-order thinking boards reward.
SQL / Python Connectivity
Connecting a Python program to a MySQL database — the connector module, cursor, running queries, and fetching results. The exact steps and vocabulary CBSE expects.
20.1 Why connect Python to a database?
Concept. A database (MySQL) stores data in tables, safely and permanently. Connectivity lets a Python program talk to that database — insert records, search, update, and read — so your program and your stored data work together.
20.2 The interface module
Python uses the mysql.connector module to talk to MySQL. You import it first.
import mysql.connectormysql.connector. Learn the exact spelling; it's a common 1-mark question.20.3 The five steps of connectivity
Every database program in CBSE follows the same sequence. Memorise these five steps.
| Step | What you do | Code |
|---|---|---|
| 1. Import | Import the module | import mysql.connector |
| 2. Connect | Open a connection to the database | connect(...) |
| 3. Cursor | Create a cursor to run SQL | con.cursor() |
| 4. Execute | Run an SQL query | cur.execute(sql) |
| 5. Fetch / Commit | Read results, or save changes | fetchall() / commit() |
20.4 Making the connection
import mysql.connector con = mysql.connector.connect( host="localhost", user="root", passwd="yourpassword", database="school" ) if con.is_connected(): print("Connected successfully")
The four connection parameters
| Parameter | Meaning |
|---|---|
host | Where MySQL runs — usually "localhost" (same computer) |
user | MySQL username, commonly "root" |
passwd | The MySQL password you set |
database | The database name to use |
connect() step. Also note: the keyword is passwd (or password) — spelling matters. If the database doesn't exist yet, connecting to it fails.20.5 Creating a cursor and running a query
The cursor is the object that carries your SQL to the database and holds the results that come back.
cur = con.cursor() # step 3 cur.execute("SELECT * FROM student") # step 4 rows = cur.fetchall() # step 5: get all rows for row in rows: print(row)
fetchall() returns a list of tuples. Access a field by index: row[0], row[1], etc.20.6 The three fetch methods
| Method | Returns |
|---|---|
fetchone() | The next single row as a tuple (or None if no more) |
fetchmany(n) | The next n rows as a list of tuples |
fetchall() | All remaining rows as a list of tuples |
cur.rowcount gives the number of rows affected/returned by the last query. Questions often ask the difference between fetchone() (one tuple) and fetchall() (list of tuples).20.7 Inserting data — and why commit() matters
cur = con.cursor() sql = "INSERT INTO student VALUES (3, 'Meera', 91)" cur.execute(sql) con.commit() # SAVE the change permanently print(cur.rowcount, "record inserted")
con.commit(). Without it, the change is discarded when the program ends. SELECT queries do not need commit. Forgetting commit() is the number-one database-connectivity exam error.commit() is pressing "Save". If you close without saving, your edits vanish. Reading a document (SELECT) needs no save — only changes do.20.8 Parameterised queries (safer inserts)
Instead of gluing values into the SQL string, use %s placeholders and pass a tuple. This avoids quoting mistakes.
roll = 4 name = "Sara" marks = 87 sql = "INSERT INTO student VALUES (%s, %s, %s)" cur.execute(sql, (roll, name, marks)) con.commit()
%s placeholders are filled by the tuple you pass as the second argument to execute(). This is cleaner than building strings with + and quotes.20.9 Closing the connection
con.close() # release the connection when done20.10 Full example — search by condition
import mysql.connector con = mysql.connector.connect( host="localhost", user="root", passwd="pass", database="school") cur = con.cursor() cur.execute("SELECT * FROM student WHERE marks > 90") for row in cur.fetchall(): print("Roll:", row[0], "Name:", row[1]) con.close()
20.11 Quick Quiz
mysql.connector module.commit().fetchone() returns…20.12 Behaviour prediction
P1 · fetchall() on a table with 3 rows returns a…
P2 🧠 · You INSERT a row but never call commit(). After the program ends, the row is…
Without commit, the change is rolled back when the connection closes.
20.13 Debugging drill
cur = con.cursor() cur.execute("DELETE FROM student WHERE roll=2") print("Deleted") con.close()
Show fix
Bug: DELETE changes data but there's no con.commit(), so the deletion isn't saved. Fix: add con.commit() after execute() and before closing.
20.14 What did you learn?
Revision notes
- Module:
mysql.connector - 5 steps: import → connect → cursor → execute → fetch/commit
- connect(host,user,passwd,database)
- Rows come back as tuples
- fetchone / fetchmany / fetchall
commit()after INSERT/UPDATE/DELETE
Top mistakes
- Forgetting commit()
- Wrong connection parameters
- Expecting a dict instead of a tuple
- Not creating a cursor first
20.15 CBSE-style questions
Q1 · 1 mark · What is the role of a cursor in database connectivity?
Answer: A cursor is an object used to execute SQL queries and to hold and traverse the result set returned from the database.
Q2 · 2 marks · Why is commit() needed and when?
Answer: commit() permanently saves changes made by INSERT, UPDATE or DELETE queries to the database. It is needed after any data-modifying query; SELECT queries do not require it.
Q3 · 4 marks · Write a Python program to connect to database "library" and display all rows of table "books".
import mysql.connector con = mysql.connector.connect( host="localhost", user="root", passwd="pass", database="library") cur = con.cursor() cur.execute("SELECT * FROM books") for row in cur.fetchall(): print(row) con.close()
Q4 · 1 mark · Assertion–Reason
A: A SELECT query requires commit() to see results. R: commit() is only needed for queries that modify data.
Answer: A is false, R is true; R explains why A is false — reading data needs no commit.
20.16 Challenge
Show solution
import mysql.connector con = mysql.connector.connect( host="localhost", user="root", passwd="pass", database="school") cur = con.cursor() r = int(input("Enter roll number: ")) cur.execute("SELECT * FROM student WHERE roll = %s", (r,)) row = cur.fetchone() if row: print(row) else: print("No such student") con.close()
Note (r,) — a one-element tuple (the comma matters, as you learned in Chapter 9). fetchone() returns the single matching row, or None if there's no match.
Master Python Cheat Sheet
Everything from all 20 chapters on one scannable page. Use it for last-minute revision and to look things up while you practise. Print it or keep it open beside your code.
1. Core syntax
| Task | Syntax |
|---|---|
| Comment | # this is a comment |
print(a, b, sep=" ", end="\n") | |
| Input (always string) | x = input("prompt") |
| Integer input | n = int(input("prompt")) |
| Assignment | x = 5 |
| Multiple assignment | a, b = 1, 2 |
| Swap (no temp) | a, b = b, a |
| Import module | import math |
2. Data types & mutability
| Type | Example | Mutable? |
|---|---|---|
| int | 70 | — |
| float | 95.5 | — |
| str | "CBSE" | ❌ Immutable |
| bool | True / False | — |
| list | [1, 2, 3] | ✅ Mutable |
| tuple | (1, 2, 3) | ❌ Immutable |
| dict | {"a": 1} | ✅ Mutable |
type(x); convert with int() / float() / str().3. Operators
| Category | Operators |
|---|---|
| Arithmetic | + - * / // % ** |
| Comparison | == != < > <= >= |
| Logical | and or not |
| Assignment | = += -= *= //= %= |
| Membership | in, not in |
| Special divisions | Example → Result |
|---|---|
/ true division (float) | 7 / 2 → 3.5 |
// floor division | 7 // 2 → 3 |
% remainder | 7 % 2 → 1 |
** power | 2 ** 3 → 8 |
** → * / // % → + - → comparisons → not → and → or. Brackets always win.4. Control flow
if cond: ... elif cond2: ... else: ...
for i in range(start, stop, step): ... while cond: ... # remember to update! # break = exit loop | continue = skip iteration
range() call | Produces |
|---|---|
range(5) | 0 1 2 3 4 |
range(1, 5) | 1 2 3 4 (stop excluded) |
range(1, 10, 2) | 1 3 5 7 9 |
range(5, 0, -1) | 5 4 3 2 1 |
5. String methods
| Method | Does | Example → Result |
|---|---|---|
upper() | uppercase | "hi".upper() → HI |
lower() | lowercase | "HI".lower() → hi |
title() | Title Case | "my dog".title() → My Dog |
strip() | trim spaces | " x ".strip() → x |
replace(a,b) | swap text | "aa".replace("a","b") → bb |
split(sep) | string → list | "a,b".split(",") → ['a','b'] |
count(x) | count occurrences | "banana".count("a") → 3 |
find(x) | first index (−1 if none) | "abc".find("c") → 2 |
isdigit() | all digits? | "12".isdigit() → True |
len(s) | length | len("abc") → 3 |
s[start:stop:step] — stop excluded. s[::-1] reverses. s[-1] = last char. First index is 0.6. List methods
| Method | Does |
|---|---|
append(x) | add x at end |
insert(i, x) | insert x at index i |
extend(L2) | add all items of L2 |
remove(x) | delete first x (by value) |
pop(i) | remove & return item at i (last if no i) |
sort() | sort in place (returns None) |
reverse() | reverse in place |
index(x) | position of x |
count(x) | how many x |
append([7,8]) adds a list-as-one-item; extend adds each element. sort()/reverse() return None — never L = L.sort(). Use sorted(L) for a new sorted copy.7. Tuples
| Point | Detail |
|---|---|
| Create | t = (1, 2, 3) |
| One element | t = (5,) — comma required! |
| Immutable | can't change items |
| Only 2 methods | count(), index() |
| Unpacking | a, b, c = t |
8. Dictionary methods
| Method | Does |
|---|---|
d[key] | access (KeyError if missing) |
d.get(key, default) | safe access, no crash |
d[key] = val | add or update |
keys() | all keys |
values() | all values |
items() | all (key, value) pairs |
update(d2) | merge in another dict |
pop(key) | remove key, return value |
for k, v in d.items():9. Functions
def name(param, default=2): return value # exits + sends back name(argument) # call
| Point | Detail |
|---|---|
| Parameter vs argument | definition vs call value |
| print vs return | print shows; return gives back (reusable) |
| No return | function returns None |
| Default params | must come after non-default |
| 3 types | built-in, module, user-defined |
| Module | Common functions |
|---|---|
math | sqrt, floor, ceil, pow, pi |
random | randint(a,b) (both ends), random() (0–1) |
10. Scope
| Point | Detail |
|---|---|
| Local | inside a function; gone after it ends |
| Global | top level; readable everywhere |
| Assigning inside a function | makes a local by default |
global x | needed to reassign a global inside a function |
| LEGB | Local → Enclosing → Global → Built-in |
11. File handling
| Mode | Meaning | Missing file |
|---|---|---|
"r" | read (default) | Error |
"w" | write (erases!) | Creates |
"a" | append (keeps old) | Creates |
"r+" | read + write | Error |
+b | binary: rb wb ab | — |
with open("f.txt", "r") as f: f.read() # whole file (str) f.read(n) # n characters f.readline() # one line f.readlines() # list of lines for line in f: # loop lines line.strip() # remove \n # write: f.write(str), f.writelines(list) — no auto \n
import pickle with open("f.dat", "wb") as f: pickle.dump(obj, f) # write with open("f.dat", "rb") as f: obj = pickle.load(f) # read (EOFError at end)
import csv with open("f.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["a", "b"]) # one row (list) w.writerows(rows) # many rows with open("f.csv", "r") as f: r = csv.reader(f) next(r) # skip header for row in r: # row = list of STRINGS int(row[2]) # convert to use as number
"w" erases · always close or use with · write() needs str, no auto newline · CSV needs newline="" and returns strings · binary needs wb/rb + pickle.12. Exception handling
try: risky() except ValueError: ... # specific error except ZeroDivisionError: ... else: ... # runs if NO error finally: ... # ALWAYS runs
| Exception | Cause |
|---|---|
ValueError | int("abc") |
ZeroDivisionError | divide by 0 |
TypeError | "5" + 3 |
IndexError | index out of range |
KeyError | missing dict key |
NameError | undefined variable |
FileNotFoundError | file doesn't exist |
EOFError | pickle load past end |
13. Stack (LIFO)
| Operation | Code |
|---|---|
| push | stack.append(x) |
| pop | stack.pop() |
| peek / top | stack[-1] |
| isEmpty | len(stack) == 0 |
14. Searching & sorting
| Algorithm | Key idea |
|---|---|
| Linear search | check each item; return index or −1 |
| Bubble sort | swap adjacent pairs; biggest bubbles to end each pass |
| Insertion sort | insert each item into the sorted left part |
for i in range(n-1): for j in range(n-1-i): if L[j] > L[j+1]: L[j], L[j+1] = L[j+1], L[j]
15. SQL / Python connectivity
import mysql.connector con = mysql.connector.connect( host="localhost", user="root", passwd="pass", database="school") cur = con.cursor() cur.execute("SELECT * FROM student") rows = cur.fetchall() # list of tuples # after INSERT/UPDATE/DELETE: con.commit() # MUST save changes con.close()
| Step | Fetch method | Returns |
|---|---|---|
| 1 import | fetchone() | one tuple |
| 2 connect | fetchmany(n) | n tuples (list) |
| 3 cursor | fetchall() | all rows (list) |
| 4 execute | rowcount | rows affected |
| 5 fetch/commit | — | — |
con.commit() after INSERT / UPDATE / DELETE. SELECT needs no commit.16. Common programming patterns
Even / odd
if n % 2 == 0: print("Even")
Sum & average of a list
total = sum(L) avg = sum(L) / len(L)
Largest / smallest (manual)
big = L[0] for x in L: if x > big: big = x
Reverse a string / number
rev = s[::-1] # string # number: use % 10 and // 10 in a loop
Count digits / sum of digits
s = 0 while n > 0: s += n % 10 # last digit n = n // 10 # drop last digit
Frequency count (dictionary)
freq = {} for ch in s: freq[ch] = freq.get(ch, 0) + 1
Count lines / words in a file
lines = words = 0 with open("f.txt") as f: for line in f: lines += 1 words += len(line.split())
Star triangle pattern
for i in range(1, n+1): print("*" * i)
17. Top errors to avoid (all chapters)
| Mistake | Fix |
|---|---|
= vs == in conditions | use == to compare |
Doing maths on input() | wrap in int()/float() |
| range stop included | stop is excluded |
| while with no update | infinite loop — add update |
| editing a string by index | strings immutable — rebuild |
L = L.sort() | sort returns None; call then use L |
| append vs extend | append = 1 item; extend = each |
| missing dict key | use .get() |
| print vs return | return to reuse a value |
| using local outside function | return it, or use global |
| "w" wiping a file | use "a" to keep data |
| writing a number to file | f.write(str(x)) |
| CSV blank rows | open with newline="" |
| forgetting commit() | commit after INSERT/UPDATE/DELETE |
| popping empty stack | check isEmpty first |
18. Board-exam tips
Writing code answers
- Always add the colon
:and indent - Write comments for logic marks
- Show sample output if asked
- Close files / commit DB changes
Output questions
- Trace line by line, note variable values
- Watch range limits & slicing stops
- Remember True=1, False=0
- Check mutability effects
Debugging questions
- Scan for
:, indentation,== - Check type conversions
- Look for missing return/commit
- Verify loop updates
Time strategy
- Do 1-mark & MCQs first (easy marks)
- Attempt all — no negative marking
- Leave hard programs for last
- Keep 10 min to review
Revision Plans
Three ready-made schedules depending on how much time you have left — a thorough 30-day plan, a fast 7-day sprint, and a 24-hour final checklist. Tick items off as you go; your progress is saved in this browser.
📅 The 30-Day Plan
Four weeks: three weeks to learn and consolidate, one week for full revision and mock papers. Aim for 1–1.5 focused hours per day.
Week 1 — Programming foundations (Days 1–7)
Week 2 — Collections, functions, files (Days 8–14)
Week 3 — Advanced topics + database (Days 15–21)
Week 4 — Full revision & mock papers (Days 22–30)
⚡ The 7-Day Sprint
Short on time? This covers everything essential in a week. Aim for 2–3 focused hours per day and prioritise programs + output questions over deep theory.
⏰ The 24-Hour Final Checklist
The day before the exam. Do not learn new topics now — consolidate what you know and rest. Light revision only.
Concepts to glance over
Programs you should be able to write blind
Exam-morning reminders
Mock Paper 1 — Full Board Pattern
A complete practice paper modelled on the CBSE Class 12 Computer Science (083) theory pattern: 70 marks, 5 sections (A–E), 3 hours. Every question is original but mirrors the real exam's style and difficulty. Attempt it fully before opening any solution — each answer is hidden in a drop-down with the marking scheme.
Section A — 1 mark each (Q1–Q18) · 18 marks
Multiple choice, fill-ups, and one-line answers. No internal choice.
Q1. What is the output of print(2 ** 3 ** 2)?
(a) 64 (b) 512 (c) 12 (d) 256
Solution
(b) 512. The ** operator is right-associative, so it evaluates as 2 ** (3 ** 2) = 2 ** 9 = 512.
Marking: 1 mark for correct option.
Q2. Which of the following is an immutable data type?
(a) list (b) dictionary (c) tuple (d) set
Solution
(c) tuple. Tuples cannot be changed after creation. Lists, dictionaries and sets are all mutable.
Marking: 1 mark.
Q3. The default mode in which a file is opened using open() is ______.
Solution
read mode ("r"). If no mode is given, the file opens for reading as text.
Marking: 1 mark.
Q4. What will "PYTHON"[1:4] return?
(a) PYT (b) YTH (c) YTHO (d) PYTH
Solution
(b) YTH. Slicing starts at index 1 (Y) and stops before index 4, so it gives indices 1, 2, 3 = Y, T, H.
Marking: 1 mark.
Q5. Which keyword is used to handle exceptions in Python along with try?
(a) catch (b) except (c) handle (d) error
Solution
(b) except. Python uses try with except (unlike some languages that use "catch").
Marking: 1 mark.
Q6. Assertion (A): A tuple can be used as a key in a dictionary.
Reason (R): Dictionary keys must be immutable.
(a) Both A and R true, R explains A (b) Both true, R does not explain A (c) A true, R false (d) A false, R true
Solution
(a). Both statements are true, and the reason correctly explains the assertion: because keys must be immutable, and a tuple is immutable, a tuple can serve as a key (whereas a list cannot).
Marking: 1 mark.
Q7. What does the fetchone() method return?
Solution
It returns a single record (one row) as a tuple from the result of a query, or None if no more rows are available.
Marking: 1 mark.
Q8. Identify the invalid identifier: total_marks, 2marks, _temp, Marks1
Solution
2marks is invalid — an identifier cannot begin with a digit.
Marking: 1 mark.
Q9. The statement to add an element x to the top of a stack (implemented as list s) is ______.
Solution
s.append(x) — push adds to the end (top) of the list.
Marking: 1 mark.
Q10. What is the output of print(10 // 3, 10 % 3)?
(a) 3 1 (b) 3.3 1 (c) 3 3 (d) 1 3
Solution
(a) 3 1. Floor division 10 // 3 = 3; modulo 10 % 3 = 1.
Marking: 1 mark.
Q11. Which method writes a list of strings to a text file?
(a) write() (b) writelines() (c) writerow() (d) dump()
Solution
(b) writelines(). It writes each string in a list to the file (without adding newlines automatically).
Marking: 1 mark.
Q12. True + True + False evaluates to ______.
Solution
2. In Python True equals 1 and False equals 0, so 1 + 1 + 0 = 2.
Marking: 1 mark.
Q13. Name the module required to work with CSV files in Python.
Solution
The csv module.
Marking: 1 mark.
Q14. What is the output of print(len("Data Science"))?
Solution
12. "Data Science" has 12 characters including the space.
Marking: 1 mark.
Q15. Which SQL command must a Python program call to permanently save changes after an INSERT?
Solution
commit() — called on the connection object, e.g. con.commit().
Marking: 1 mark.
Q16. The output of print(list(range(2, 11, 3))) is ______.
Solution
[2, 5, 8] — start 2, step 3, stop before 11: 2, 5, 8 (next would be 11, excluded).
Marking: 1 mark.
Q17. What type of error is raised by int("hello")?
(a) TypeError (b) ValueError (c) NameError (d) SyntaxError
Solution
(b) ValueError. The string is the right type but an invalid value for integer conversion.
Marking: 1 mark.
Q18. Give the term: a variable declared inside a function that cannot be accessed outside it.
Solution
A local variable (it has local scope).
Marking: 1 mark.
Section B — 2 marks each (Q19–Q25) · 14 marks
Q19. Rewrite the following code after removing all syntax errors. Underline each correction.
n = int(input("Enter: ")
if n % 2 = 0
print("Even")
else
print("Odd")Solution
n = int(input("Enter: ")) # added closing ) if n % 2 == 0: # == not =, added : print("Even") else: # added : print("Odd")
Marking: 3 errors to fix (missing ), =→==, missing colons). ½ mark each, rounded to 2 marks for all correct.
Q20. What is the difference between append() and extend() for lists? Give one example each.
Solution
append(x) adds x as a single element at the end. extend(L) adds each element of an iterable L individually.
L = [1, 2] L.append([3, 4]) # [1, 2, [3, 4]] L = [1, 2] L.extend([3, 4]) # [1, 2, 3, 4]
Marking: 1 mark for the distinction + 1 mark for correct examples.
Q21. Predict the output:
d = {1: "one", 2: "two", 3: "three"}
for k in d:
if k % 2 != 0:
print(d[k], end=" ")Solution
Output: one three
Looping over a dict gives its keys (1, 2, 3). Odd keys are 1 and 3, printing their values "one" and "three" on one line separated by spaces.
Marking: 2 marks for exact output (1 mark if minor spacing error).
Q22. Write a Python function count_vowels(s) that returns the number of vowels in string s.
Solution
def count_vowels(s): count = 0 for ch in s.lower(): if ch in "aeiou": count += 1 return count
Marking: 1 mark for loop + membership check, 1 mark for correct counting & return.
Q23. Differentiate between r+ and w+ file modes.
Solution
r+ opens for reading and writing; the file must already exist and existing content is kept. w+ opens for writing and reading but truncates (erases) the file if it exists, and creates it if it doesn't.
Marking: 1 mark each mode.
Q24. Expand and explain the term SQL, and name one DDL and one DML command.
Solution
SQL = Structured Query Language, used to create and manipulate relational databases.
DDL example: CREATE (also DROP, ALTER). DML example: INSERT (also UPDATE, DELETE, SELECT).
Marking: 1 mark for expansion+purpose, ½ + ½ for the two commands.
Q25. Predict the output and justify:
x = 5
def change():
x = 10
print(x, end=" ")
change()
print(x)Solution
Output: 10 5
Inside change(), x = 10 creates a local variable, so it prints 10. The global x is untouched, so the last line prints 5.
Marking: 1 mark output + 1 mark scope justification.
Section C — 3 marks each (Q26–Q29) · 12 marks
Q26. Write a function that reads a text file "story.txt" and displays the number of lines that begin with a vowel.
Solution
def vowel_lines(): count = 0 with open("story.txt", "r") as f: for line in f: line = line.strip() if len(line) > 0 and line[0] in "aeiouAEIOU": count += 1 print("Lines starting with a vowel:", count)
Marking: 1 mark file open/loop, 1 mark first-char vowel check (with empty-line guard), 1 mark count & display.
Q27. Consider a stack S = []. Write functions push(S, item) and pop(S). The pop function should return "Underflow" if the stack is empty.
Solution
def push(S, item): S.append(item) def pop(S): if len(S) == 0: return "Underflow" return S.pop()
Marking: 1 mark push, 1 mark underflow check, 1 mark correct pop & return.
Q28. Predict the output:
def process(L):
for i in range(len(L)):
if L[i] % 2 == 0:
L[i] = L[i] * 2
else:
L[i] = L[i] + 1
return L
nums = [3, 4, 7, 10]
print(process(nums))Solution
Output: [4, 8, 8, 20]
3 is odd → 3+1 = 4; 4 is even → 4×2 = 8; 7 is odd → 7+1 = 8; 10 is even → 10×2 = 20.
Marking: 3 marks for exact list; deduct 1 per wrong element.
Q29. Write the output. If an error occurs, state which exception is raised.
try:
L = [10, 20, 30]
print(L[1])
print(L[5])
print("Done")
except IndexError:
print("Bad index")
finally:
print("Finished")Solution
Output:
20 Bad index Finished
L[1] prints 20. L[5] raises IndexError, so "Done" is skipped, the except block prints "Bad index", and finally always runs, printing "Finished".
Marking: 1 mark each line of output in correct order.
Section D — 4 marks each (Q30–Q32) · 12 marks
Q30. A binary file "emp.dat" stores employee records as lists [empno, name, salary] using pickle. Write a function high_earners() that reads the file and displays all employees with salary greater than 50000.
Solution
import pickle def high_earners(): try: with open("emp.dat", "rb") as f: while True: rec = pickle.load(f) if rec[2] > 50000: print(rec[0], rec[1], rec[2]) except EOFError: pass
Key ideas: open in "rb", loop pickle.load until EOFError marks end of file, check index 2 (salary).
Marking: 1 mark rb open, 1 mark loop with load, 1 mark EOFError handling, 1 mark salary check & display.
Q31. Write a function add_record() that appends a new student [roll, name, marks] to a CSV file "students.csv", taking the values as input. Then write show_toppers() that displays students with marks ≥ 90.
Solution
import csv def add_record(): roll = input("Roll: ") name = input("Name: ") marks = input("Marks: ") with open("students.csv", "a", newline="") as f: w = csv.writer(f) w.writerow([roll, name, marks]) def show_toppers(): with open("students.csv", "r") as f: r = csv.reader(f) for row in r: if int(row[2]) >= 90: print(row)
Note the append mode "a" with newline="", and converting row[2] to int since CSV returns strings.
Marking: 2 marks add_record (append + writerow), 2 marks show_toppers (read + int conversion + filter).
Q32. Predict the output:
s = "aBcDeF"
result = ""
for ch in s:
if ch.isupper():
result = result + ch.lower()
else:
result = result + ch.upper()
print(result)
print(result[::-1])Solution
Output:
AbCdEf fEdCbA
Each character's case is flipped: a→A, B→b, c→C, D→d, e→E, F→f giving "AbCdEf". The second line reverses it with [::-1].
Marking: 2 marks first line, 2 marks reversed line.
Section E — 5 marks each (Q33–Q35) · 15 marks
Q33. Consider the table STUDENT with columns: RollNo, Name, Class, Marks, City. Write SQL statements for (i)–(v):
(i) Display all students of class 12 sorted by marks in descending order.
(ii) Display the number of students in each city.
(iii) Increase marks by 5 for all students in 'Delhi'.
(iv) Display names of students whose name starts with 'A'.
(v) Display the highest marks in the table.
Solution
-- (i) SELECT * FROM STUDENT WHERE Class = 12 ORDER BY Marks DESC; -- (ii) SELECT City, COUNT(*) FROM STUDENT GROUP BY City; -- (iii) UPDATE STUDENT SET Marks = Marks + 5 WHERE City = 'Delhi'; -- (iv) SELECT Name FROM STUDENT WHERE Name LIKE 'A%'; -- (v) SELECT MAX(Marks) FROM STUDENT;
Marking: 1 mark each part. Watch for GROUP BY in (ii), LIKE 'A%' in (iv).
Q34. Write a complete Python program using MySQL connectivity that connects to database school and displays all records from the table teacher where salary is above 40000. Assume host localhost, user root, password admin.
Solution
import mysql.connector con = mysql.connector.connect( host="localhost", user="root", passwd="admin", database="school") cur = con.cursor() cur.execute("SELECT * FROM teacher WHERE salary > 40000") rows = cur.fetchall() for row in rows: print(row) con.close()
Marking: 1 mark import, 1 mark connect with all params, 1 mark cursor+execute with correct WHERE, 1 mark fetchall+loop, 1 mark close. (No commit needed — SELECT only.)
Q35. Write a menu-driven program with a function count_words() that counts total words in "essay.txt", and a function longest_word() that finds and returns the longest word in the file.
Solution
def count_words(): total = 0 with open("essay.txt") as f: for line in f: total += len(line.split()) print("Total words:", total) def longest_word(): longest = "" with open("essay.txt") as f: for line in f: for w in line.split(): if len(w) > len(longest): longest = w return longest # menu while True: print("1.Count words 2.Longest word 3.Exit") ch = int(input("Choice: ")) if ch == 1: count_words() elif ch == 2: print("Longest:", longest_word()) elif ch == 3: break
Marking: 2 marks count_words (split & sum), 2 marks longest_word (compare lengths), 1 mark working menu loop.
Mock Paper 2 — Full Board Pattern
A second complete practice paper in the same CBSE Class 12 CS (083) format: 70 marks, 5 sections (A–E), 3 hours. Fresh questions, same difficulty spread. Sit this one a few days after Paper 1 to measure real improvement.
Section A — 1 mark each (Q1–Q18) · 18 marks
Q1. What is the output of print(7 // 2 + 7 % 2)?
(a) 3 (b) 4 (c) 4.5 (d) 5
Solution
(b) 4. 7 // 2 = 3, 7 % 2 = 1, and 3 + 1 = 4.
Marking: 1 mark.
Q2. Which of these creates a tuple with a single element?
(a) (5) (b) (5,) (c) [5] (d) {5}
Solution
(b) (5,). Without the trailing comma, (5) is just the integer 5 in brackets.
Marking: 1 mark.
Q3. The file mode that opens a file for appending without erasing existing content is ______.
Solution
"a" (append mode). It adds new content at the end and creates the file if it doesn't exist.
Marking: 1 mark.
Q4. What does "HELLO".find("L") return?
(a) 2 (b) 3 (c) [2, 3] (d) -1
Solution
(a) 2. find returns the index of the first occurrence; the first "L" is at index 2.
Marking: 1 mark.
Q5. Which block runs whether or not an exception occurs?
(a) try (b) except (c) else (d) finally
Solution
(d) finally. It always executes, typically used for cleanup like closing files.
Marking: 1 mark.
Q6. Assertion (A): sort() on a list returns a new sorted list.
Reason (R): sort() modifies the list in place and returns None.
(a) Both true, R explains A (b) Both true, R does not explain A (c) A false, R true (d) A true, R false
Solution
(c) A false, R true. The assertion is wrong — sort() does not return a new list; it sorts in place and returns None (which is exactly what R correctly states). For a new list you'd use sorted().
Marking: 1 mark.
Q7. Which method returns all rows of a query result as a list of tuples?
Solution
fetchall().
Marking: 1 mark.
Q8. What is the output of print("ab" * 3)?
Solution
ababab. The * operator repeats a string.
Marking: 1 mark.
Q9. The operation to remove and return the top element of a stack list s is ______.
Solution
s.pop() — with no index, it removes the last (top) element.
Marking: 1 mark.
Q10. What is the output of print(bool(0), bool(""), bool("0"))?
(a) False False False (b) False False True (c) True False True (d) False True True
Solution
(b) False False True. 0 and empty string are falsy, but "0" is a non-empty string, so it's truthy.
Marking: 1 mark.
Q11. Which function of the pickle module writes an object to a binary file?
(a) write() (b) dump() (c) load() (d) save()
Solution
(b) dump(). pickle.dump(obj, f) serialises and writes; load() reads it back.
Marking: 1 mark.
Q12. Fill in: "Python".upper() gives ______.
Solution
PYTHON.
Marking: 1 mark.
Q13. Which parameter must be passed to open() when writing a CSV file to avoid blank rows?
Solution
newline=""
Marking: 1 mark.
Q14. What is the output of print("a,b,c".split(","))?
Solution
['a', 'b', 'c'] — split breaks the string at each comma and returns a list.
Marking: 1 mark.
Q15. Name the object created by con.cursor() and state its purpose in one line.
Solution
A cursor object — it is used to execute SQL queries and fetch results from the database.
Marking: 1 mark.
Q16. What is the output of print(list(range(10, 4, -2)))?
Solution
[10, 8, 6] — start 10, step −2, stop before 4: 10, 8, 6 (next is 4, excluded).
Marking: 1 mark.
Q17. Which exception is raised by accessing a dictionary key that does not exist?
(a) IndexError (b) ValueError (c) KeyError (d) TypeError
Solution
(c) KeyError. Use .get() to avoid it.
Marking: 1 mark.
Q18. Give the term: a value passed to a function when it is called.
Solution
An argument (the value in the definition is a parameter).
Marking: 1 mark.
Section B — 2 marks each (Q19–Q25) · 14 marks
Q19. Rewrite after removing errors, underlining corrections:
def greet(name):
print("Hello" + name)
for i in range(3)
greet("Sam")Solution
def greet(name): print("Hello " + name) # indent + space in string for i in range(3): # added colon greet("Sam")
Marking: missing indentation of print, missing colon after range(3). 1 mark each. (Adding the space is a nice-to-have.)
Q20. What is the difference between a text file and a binary file? Give one example each.
Solution
A text file stores data as human-readable characters (encoded text), e.g. .txt, .csv. A binary file stores data in raw byte form that isn't directly human-readable, e.g. .dat pickle files, images.
Marking: 1 mark distinction + 1 mark examples.
Q21. Predict the output:
L = [1, 2, 3, 4, 5] print(L[::2]) print(L[-2:]) print(L[1:4])
Solution
Output:
[1, 3, 5] [4, 5] [2, 3, 4]
[::2] every 2nd item; [-2:] last two; [1:4] indices 1–3.
Marking: ⅔ mark per correct line, 2 marks total.
Q22. Write a function is_palindrome(s) that returns True if string s reads the same forwards and backwards.
Solution
def is_palindrome(s): return s == s[::-1]
Full-credit alternative: loop comparing s[i] with s[-1-i].
Marking: 1 mark reversal logic, 1 mark correct boolean return.
Q23. Explain the difference between fetchone() and fetchmany(n).
Solution
fetchone() returns the next single row as a tuple (or None if exhausted). fetchmany(n) returns the next n rows as a list of tuples.
Marking: 1 mark each method.
Q24. Predict the output:
d = {}
for ch in "mississippi":
d[ch] = d.get(ch, 0) + 1
print(d)Solution
Output: {'m': 1, 'i': 4, 's': 4, 'p': 2}
The classic frequency-count pattern; .get(ch, 0) gives 0 for a new character. Order follows first appearance.
Marking: 2 marks for all counts correct.
Q25. What will be the contents of "log.txt" after this runs?
f = open("log.txt", "w")
f.write("AB")
f.write("CD\n")
f.write("EF")
f.close()Solution
File contents:
ABCD EF
write does not add newlines automatically, so "AB" and "CD\n" join as "ABCD" then a newline, then "EF" on the next line.
Marking: 1 mark for joining behaviour, 1 mark for newline placement.
Section C — 3 marks each (Q26–Q29) · 12 marks
Q26. Write a function copy_capitals() that reads "names.txt" and writes only the lines that are fully in uppercase into a new file "caps.txt".
Solution
def copy_capitals(): with open("names.txt") as src, \ open("caps.txt", "w") as dst: for line in src: if line.strip().isupper(): dst.write(line)
Full credit also for opening the two files separately. isupper() tests the whole stripped line.
Marking: 1 mark read loop, 1 mark isupper check, 1 mark write to second file.
Q27. A list nums holds integers. Using a stack, write code that pushes only the even numbers and then pops and prints them all (which reverses their order).
Solution
nums = [3, 8, 5, 12, 7, 4] stack = [] for n in nums: if n % 2 == 0: stack.append(n) while len(stack) > 0: print(stack.pop(), end=" ") # Output: 4 12 8
Marking: 1 mark even filter + push, 1 mark pop loop, 1 mark correct reversed output.
Q28. Predict the output:
def mystery(n):
result = 1
while n > 1:
result = result * n
n = n - 1
return result
for x in range(1, 5):
print(x, mystery(x))Solution
Output:
1 1 2 2 3 6 4 24
mystery computes the factorial of n. For x = 1,2,3,4 it prints x alongside 1!, 2!, 3!, 4!.
Marking: 3 marks for all four lines; identifying it as factorial is a bonus understanding check.
Q29. Write the output, naming any exception raised:
nums = [4, 0, 2]
for n in nums:
try:
print(10 / n)
except ZeroDivisionError:
print("Cannot divide")Solution
Output:
2.5 Cannot divide 5.0
10/4 = 2.5; 10/0 raises ZeroDivisionError → "Cannot divide"; 10/2 = 5.0. The loop continues because the error is caught each iteration.
Marking: 1 mark each output line in order.
Section D — 4 marks each (Q30–Q32) · 12 marks
Q30. A binary file "books.dat" stores records as dictionaries {"id":.., "title":.., "price":..}. Write add_book() to append one book (input from user) and cheap_books() to display all books priced below 300.
Solution
import pickle def add_book(): b = {} b["id"] = int(input("ID: ")) b["title"] = input("Title: ") b["price"] = float(input("Price: ")) with open("books.dat", "ab") as f: pickle.dump(b, f) def cheap_books(): try: with open("books.dat", "rb") as f: while True: b = pickle.load(f) if b["price"] < 300: print(b) except EOFError: pass
Marking: 2 marks add_book (ab mode + dump), 2 marks cheap_books (rb + load loop + EOFError + price filter).
Q31. A CSV file "sales.csv" has rows [date, product, amount] (with a header row). Write a function that returns the total of the amount column.
Solution
import csv def total_sales(): total = 0 with open("sales.csv", "r") as f: r = csv.reader(f) next(r) # skip header for row in r: total += float(row[2]) return total
Key points: next(r) skips the header, and row[2] is a string that must be converted with float().
Marking: 1 mark reader, 1 mark skip header, 1 mark float conversion, 1 mark accumulate & return.
Q32. Predict the output:
def update(data, key, val=0):
data[key] = data.get(key, 0) + val
return data
d = {"a": 5}
update(d, "a", 3)
update(d, "b")
update(d, "b", 7)
print(d)Solution
Output: {'a': 8, 'b': 7}
"a": 5+3 = 8. "b" first call uses default val 0 → 0+0 = 0. Second "b" call → 0+7 = 7. The same dict is modified across calls (mutable, passed by reference).
Marking: 2 marks correct 'a', 2 marks correct 'b' (tests default args + get + mutability).
Section E — 5 marks each (Q33–Q35) · 15 marks
Q33. Consider table EMPLOYEE with columns EmpID, Name, Dept, Salary, JoinYear. Write SQL for (i)–(v):
(i) Display all employees of the 'Sales' department.
(ii) Display the average salary department-wise.
(iii) Display names of employees who joined after 2020, sorted by name.
(iv) Add 2000 to the salary of every employee in 'IT'.
(v) Delete all employees whose salary is below 15000.
Solution
-- (i) SELECT * FROM EMPLOYEE WHERE Dept = 'Sales'; -- (ii) SELECT Dept, AVG(Salary) FROM EMPLOYEE GROUP BY Dept; -- (iii) SELECT Name FROM EMPLOYEE WHERE JoinYear > 2020 ORDER BY Name; -- (iv) UPDATE EMPLOYEE SET Salary = Salary + 2000 WHERE Dept = 'IT'; -- (v) DELETE FROM EMPLOYEE WHERE Salary < 15000;
Marking: 1 mark each. Common slips: forgetting GROUP BY in (ii), quoting the number in (iii)/(v).
Q34. Write a complete Python program that connects to database shop and inserts a new product (pid, pname, price) taken as input into table product. Assume host localhost, user root, password root. Remember to save the change.
Solution
import mysql.connector con = mysql.connector.connect( host="localhost", user="root", passwd="root", database="shop") cur = con.cursor() pid = int(input("PID: ")) pname = input("Name: ") price = float(input("Price: ")) sql = "INSERT INTO product VALUES (%s, %s, %s)" cur.execute(sql, (pid, pname, price)) con.commit() # MUST save print("Record added") con.close()
Marking: 1 mark connect, 1 mark cursor + input values, 1 mark correct INSERT with placeholders, 1 mark commit(), 1 mark close. Missing commit = −1 (the classic error).
Q35. Write a menu-driven program with functions: even_odd(L) that prints how many even and odd numbers are in list L, and search(L, x) that does a linear search and prints the position of x (or "Not found").
Solution
def even_odd(L): e = o = 0 for n in L: if n % 2 == 0: e += 1 else: o += 1 print("Even:", e, "Odd:", o) def search(L, x): for i in range(len(L)): if L[i] == x: print("Found at position", i) return print("Not found") data = [4, 7, 2, 9, 6] while True: print("1.Even/Odd 2.Search 3.Exit") ch = int(input("Choice: ")) if ch == 1: even_odd(data) elif ch == 2: x = int(input("Search: ")) search(data, x) elif ch == 3: break
Marking: 2 marks even_odd (counting both), 2 marks search (loop + found/not found), 1 mark menu loop.
PYQ-Style Question Bank
A topic-wise bank of exam-style questions, grouped by unit and tagged by difficulty. Every question is original but written in the exact style boards favour, so you can drill one weak chapter at a time instead of sitting a whole paper. Attempt first, then reveal the answer.
📘 Programming Basics (Ch 1–6)
Easy QB1. Predict the output: print(3 + 4 * 2, (3 + 4) * 2)
Answer
11 14. First uses precedence (4×2=8, +3=11); brackets force 7×2=14.
Easy QB2. Write a program to check whether a number entered by the user is positive, negative, or zero.
Answer
n = int(input("Enter: ")) if n > 0: print("Positive") elif n < 0: print("Negative") else: print("Zero")
Medium QB3. Write a program to print the multiplication table of a number n, from n×1 to n×10.
Answer
n = int(input("Number: ")) for i in range(1, 11): print(n, "x", i, "=", n * i)
Medium QB4. Predict the output:
for i in range(1, 4):
for j in range(i):
print("*", end="")
print()Answer
* ** ***
Outer i = 1,2,3; inner prints i stars per row.
Hard QB5. Write a program to check whether a number is an Armstrong number (sum of cubes of digits equals the number), e.g. 153.
Answer
n = int(input("Enter: ")) temp = n total = 0 while temp > 0: d = temp % 10 total += d ** 3 temp = temp // 10 if total == n: print("Armstrong") else: print("Not Armstrong")
Uses the digit-extraction pattern: % 10 gets the last digit, // 10 drops it.
📗 Strings, Lists, Tuples & Dictionaries (Ch 7–10)
Easy QB6. Predict: s = "Computer"; print(s[::-1], s[2:5])
Answer
retupmoC mpu. [::-1] reverses; [2:5] gives indices 2,3,4 = m, p, u.
Medium QB7. Write a program to count how many words in a sentence have more than 4 characters.
Answer
s = input("Sentence: ") count = 0 for w in s.split(): if len(w) > 4: count += 1 print(count)
Medium QB8. Predict the output:
L = [10, 20, 30, 40, 50] L.insert(2, 99) L.pop(0) print(L) print(sum(L) / len(L))
Answer
[20, 99, 30, 40, 50] then 47.8.
Insert 99 at index 2 → [10,20,99,30,40,50]; pop(0) removes 10 → [20,99,30,40,50]; sum 239 / 5 = 47.8.
Medium QB9. Given a list of marks, write a program to create a dictionary mapping "pass"/"fail" to counts (pass ≥ 33).
Answer
marks = [45, 30, 88, 20, 60] result = {"pass": 0, "fail": 0} for m in marks: if m >= 33: result["pass"] += 1 else: result["fail"] += 1 print(result) # {'pass': 3, 'fail': 2}
Hard QB10. Write a program that takes a sentence and prints a dictionary of each word's length, but only for unique words.
Answer
s = input("Sentence: ") d = {} for w in s.split(): d[w] = len(w) print(d)
Because dictionary keys are unique, repeated words automatically collapse to one entry.
Hard QB11. A tuple t = (5, 3, 8, 1, 9, 2). Without using max()/min(), write code to print the largest and smallest values.
Answer
t = (5, 3, 8, 1, 9, 2) big = small = t[0] for x in t: if x > big: big = x if x < small: small = x print(big, small) # 9 1
📙 Functions & Scope (Ch 11–12)
Easy QB12. Write a function area_rect(l, b) that returns the area of a rectangle, with b defaulting to l (so a single argument gives a square).
Answer
def area_rect(l, b=None): if b is None: b = l return l * b
A default of None lets us detect "no second argument" and fall back to a square.
Medium QB13. Predict the output:
x = 100
def f():
global x
x = x + 50
return x
print(f(), x)Answer
150 150. global x lets the function modify the global; it becomes 150 both inside and outside.
Hard QB14. Predict the output and explain:
def add_item(item, box=[]):
box.append(item)
return box
print(add_item(1))
print(add_item(2))Answer
[1] then [1, 2].
A mutable default argument is created once and shared across calls, so the second call keeps the first item. This is a famous Python gotcha — for board purposes, know that the default list persists between calls.
📕 File Handling (Ch 13–16)
Easy QB15. Write a function to count the total number of lines in a text file "data.txt".
Answer
def line_count(): with open("data.txt") as f: return len(f.readlines())
Medium QB16. Write a function that counts how many times the letter 'e' appears in a text file "para.txt" (case-insensitive).
Answer
def count_e(): with open("para.txt") as f: text = f.read().lower() return text.count("e")
Medium QB17. A binary file "nums.dat" stores a single list of integers (pickled once). Write code to read it and print the average.
Answer
import pickle with open("nums.dat", "rb") as f: L = pickle.load(f) print(sum(L) / len(L))
Only one load is needed because the whole list was dumped as a single object.
Hard QB18. A CSV file "stock.csv" has header item,qty,price. Write a function that prints items whose qty × price (total value) exceeds 1000.
Answer
import csv def high_value(): with open("stock.csv") as f: r = csv.reader(f) next(r) # skip header for row in r: value = int(row[1]) * float(row[2]) if value > 1000: print(row[0], value)
Remember CSV values are strings — convert qty and price before multiplying.
📔 Exceptions, Stack, Searching & Sorting (Ch 17–19)
Easy QB19. Rewrite this so a bad (non-numeric) input does not crash the program:
n = int(input("Number: "))
print(100 / n)Answer
try: n = int(input("Number: ")) print(100 / n) except ValueError: print("Please enter a valid number") except ZeroDivisionError: print("Cannot divide by zero")
Medium QB20. Using a stack, write a function reverse_string(s) that returns the string reversed.
Answer
def reverse_string(s): stack = [] for ch in s: stack.append(ch) rev = "" while len(stack) > 0: rev += stack.pop() return rev
Pushing then popping every character naturally reverses order (LIFO).
Medium QB21. Dry-run one pass of bubble sort on [5, 2, 9, 1] and show the list after the first pass.
Answer
Compare & swap adjacent pairs left to right:
[5,2,9,1] → swap 5,2 → [2,5,9,1] → 5<9 no swap → [2,5,9,1] → swap 9,1 → [2,5,1,9].
After pass 1 the largest value (9) has "bubbled" to the end.
Hard QB22. Write a function that uses a stack to check whether a string of brackets like "(())" is balanced.
Answer
def balanced(s): stack = [] for ch in s: if ch == "(": stack.append(ch) elif ch == ")": if len(stack) == 0: return False stack.pop() return len(stack) == 0
Each "(" is pushed; each ")" pops one. Balanced means the stack is empty at the end and never underflowed.
🗄️ SQL & Connectivity (Ch 20)
Easy QB23. Write the sequence of five steps (in order) to fetch data from MySQL in Python.
Answer
1. import mysql.connector · 2. connect() to make a connection · 3. create a cursor() · 4. execute() the query · 5. fetch results (fetchall/fetchone). (Then close; commit if you changed data.)
Medium QB24. Table ITEM(Code, Name, Price, Qty). Write SQL to (i) show items costing between 100 and 500, (ii) show the total quantity of all items.
Answer
-- (i) SELECT * FROM ITEM WHERE Price BETWEEN 100 AND 500; -- (ii) SELECT SUM(Qty) FROM ITEM;
Hard QB25. Write a Python function that connects to database bank and updates the balance of account number acc by adding amt to table accounts. Ensure the change is saved.
Answer
import mysql.connector def deposit(acc, amt): con = mysql.connector.connect( host="localhost", user="root", passwd="root", database="bank") cur = con.cursor() cur.execute( "UPDATE accounts SET balance = balance + %s WHERE accno = %s", (amt, acc)) con.commit() # save the update con.close()
The commit() is essential — without it the UPDATE is discarded when the connection closes.
Debugging & Output Masterclass
The two question types that decide the most marks in the shortest space: find the bug and predict the output. This is a consolidated cross-topic workout pulling the trickiest traps from every chapter into one focused drill. Do these last, once you've revised — they're the sharpest test of whether the concepts have truly stuck.
= vs ==, and type conversion. For output: keep a small table of variable values in the margin and update it line by line. Never guess — trace.🐞 Part 1 — Find & Fix the Bug
Each snippet has one or more errors (syntax or logic). Find them before revealing the fix.
D1. Meant to print numbers 1 to 5:
for i in range(1, 5):
print(i)Fix
Logic bug: range(1, 5) stops before 5, printing only 1–4. Fix the stop value:
for i in range(1, 6): print(i)
The classic "stop is excluded" trap — to reach n, write range(1, n+1).
D2. Meant to add two numbers entered by the user:
a = input("First: ")
b = input("Second: ")
print(a + b)Fix
Type bug: input() returns strings, so "3" + "4" gives "34", not 7. Convert to int:
a = int(input("First: ")) b = int(input("Second: ")) print(a + b)
D3. Meant to find the average of a list:
L = [10, 20, 30] avg = sum(L) / len(L) L = L.sort() print(avg, L)
Fix
Logic bug: L.sort() sorts in place and returns None, so L = L.sort() makes L become None. Remove the assignment:
L = [10, 20, 30] avg = sum(L) / len(L) L.sort() # just call it print(avg, L)
D4. Meant to open a file and read it:
f = open("data.txt", "w")
content = f.read()
print(content)
f.close()Fix
Mode bug: the file is opened in write mode "w" (which also erases it!) and then read — reading in write mode raises an error. Use read mode:
f = open("data.txt", "r") content = f.read() print(content) f.close()
D5. A function meant to return double a number:
def double(n):
result = n * 2
x = double(5)
print(x)Fix
Missing return: the function computes result but never returns it, so x becomes None. Add a return:
def double(n): result = n * 2 return result
D6. Meant to insert a record into a database:
cur.execute("INSERT INTO emp VALUES (1, 'Sam')")
con.close()Fix
Missing commit: after an INSERT (or UPDATE/DELETE) you must call con.commit() or the change is lost when the connection closes:
cur.execute("INSERT INTO emp VALUES (1, 'Sam')") con.commit() # save it con.close()
The single most common database mistake in the exam.
D7. Meant to safely read a dictionary value:
d = {"a": 1, "b": 2}
print(d["c"])Fix
KeyError: key "c" doesn't exist, so this crashes. Use .get() with a default:
d = {"a": 1, "b": 2} print(d.get("c", "Not found"))
D8. Multiple syntax errors — meant to check even/odd for numbers 1–3:
for n in range(1, 4)
if n % 2 = 0
print(n, "even")
else
print(n "odd")Fix
Four bugs: missing colon after range, = should be ==, missing colon after if, missing colon after else, and a missing comma in the last print.
for n in range(1, 4): if n % 2 == 0: print(n, "even") else: print(n, "odd")
🔮 Part 2 — Predict the Output
Trace each one carefully. Write your answer before revealing.
O1.
x = 7 y = 2 print(x / y, x // y, x % y, x ** y)
Output
3.5 3 1 49
True division 3.5, floor 3, remainder 1, power 7²=49.
O2.
s = "Programming" print(s[3:7]) print(s[-4:]) print(s[::3])
Output
gram ming Pgmi
[3:7] indices 3–6 = g,r,a,m; [-4:] last four = ming; [::3] every 3rd char: P(0), g(3), m(6), i(9).
O3.
L = [1, 2, 3] M = L M.append(4) print(L) print(L is M)
Output
[1, 2, 3, 4] True
Aliasing trap: M = L makes both names point to the same list, so appending via M changes L too. is confirms they are the same object.
O4.
count = 0
for i in range(2, 20, 3):
count += 1
print(i, count)Output
17 6
range gives 2,5,8,11,14,17 — six values, so count = 6 and the last i is 17.
O5.
def f(a, b=3, c=5):
return a + b + c
print(f(1))
print(f(1, 2))
print(f(1, c=10))Output
9 8 14
f(1): 1+3+5=9. f(1,2): b becomes 2 → 1+2+5=8. f(1,c=10): b stays 3, c=10 → 1+3+10=14.
O6.
text = "banana"
d = {}
for ch in text:
d[ch] = d.get(ch, 0) + 1
for k in d:
print(k, d[k])Output
b 1 a 3 n 2
Frequency count; keys appear in first-seen order: b, a, n.
O7.
t = (1, 2, 3, 4, 5) print(t.index(3)) print(t.count(2)) print(t[1:4])
Output
2 1 (2, 3, 4)
index of 3 is 2; 2 appears once; slice indices 1–3 as a tuple.
O8. Assume a while-loop trace:
n = 5
result = 1
while n > 0:
result *= n
n -= 1
print(result)Output
120
Factorial of 5: 5×4×3×2×1 = 120.
O9. Nested loop trap:
for i in range(1, 4):
for j in range(1, 4):
if i == j:
print(i * j, end=" ")Output
1 4 9
Only when i == j (1,1), (2,2), (3,3) → 1, 4, 9.
O10. Exception flow:
try:
x = int("50")
y = x / 0
except ValueError:
print("value")
except ZeroDivisionError:
print("zero")
else:
print("ok")
finally:
print("end")Output
zero end
int("50") works (no ValueError), then x / 0 raises ZeroDivisionError → "zero". The else is skipped (an error occurred), but finally always runs → "end".
O11. The tricky one — string immutability:
s = "hello"
new = ""
for ch in s:
new = ch + new
print(new)Output
olleh
Each character is placed before the accumulated string, so it builds up reversed. A neat manual reverse without slicing.
O12. Final boss — combines several concepts:
data = [3, 6, 9, 12, 15]
stack = []
for x in data:
if x % 2 == 0:
stack.append(x)
else:
if len(stack) > 0:
stack.pop()
print(stack)Output
[6]
Trace: 3 odd→pop (empty, nothing); 6 even→push [6]; 9 odd→pop [ ]; 12 even→push [12]; 15 odd→pop [ ]... wait — let's be careful:
3 odd, stack empty, no pop → []. 6 even → [6]. 9 odd → pop → []. 12 even → [12]. 15 odd → pop → []. Final: [].
[], not [6]. This is exactly why you trace on paper rather than eyeballing — the last odd number empties the stack. Always finish the trace to the final line.== not = in conditions · int()/float() on input · return values from functions · commit() after DB writes · correct file mode · .get() for dict keys · sort()/reverse() return None. Nine checks that catch almost every board bug.🎉 You have the complete guide
Every part of the Python Masterclass is now built — 20 full teaching chapters covering the entire CBSE Class 12 Computer Science (083) syllabus, plus a complete exam-prep suite. Here's the full map of what's inside so you can jump straight to what you need.
📚 Unit 1 — Programming & core concepts
| # | Chapter |
|---|---|
| 1–6 | Fundamentals · Variables & Data Types · Operators · Input/Output · Conditionals · Loops |
| 7–10 | Strings · Lists · Tuples · Dictionaries |
| 11–12 | Functions · Scope |
| 13–16 | File Handling overview · Text Files · Binary Files (pickle) · CSV Files |
| 17–19 | Exception Handling · Stack · Searching & Sorting |
🗄️ Unit 3 — Database
| # | Chapter |
|---|---|
| 20 | SQL / Python Connectivity |
🎯 Exam prep suite
| Section | What it's for |
|---|---|
| Master Cheat Sheet | One-page reference for last-minute revision |
| Revision Plans | 30-day, 7-day & 24-hour trackable schedules |
| Mock Paper 1 · Mock Paper 2 | Two full 70-mark timed papers with solutions |
| Question Bank | Topic-wise drills tagged by difficulty |
| Debugging & Output | The two highest-yield question types |