Home
Learn → Practice → Code → Test → Master

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.

Coming Soon 🚀

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.

📤 Upload Exam Material Share notes, papers & PYQs — opens a Google upload form.
📌How this guide is built Every concept follows the same rhythm so your brain always knows what's coming next:
ConceptExplainSyntaxExampleOutputLine-by-lineMistakesPracticeCBSE QsChallenge

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
💡How to use it Work top to bottom. Read a concept, run the Try-It panel, take the quick quiz, then move on. Mark each chapter "done" (top-right) — your progress bar and ticks are saved in this browser automatically.
⚠️Syllabus note Aligned to the CBSE Class 12 CS (083) 2025–26 syllabus: Python programming, file handling (text/binary/CSV), data structures (stack), exception handling, and SQL–Python connectivity. Topics outside the syllabus are clearly flagged Beyond CBSE.
🔒About the questions Previous-year-style questions in this guide are original, written to match CBSE patterns and difficulty. They are labelled "CBSE-style" rather than presented as exact reproductions of past papers, so you're always practising against authentic formats without relying on unverified copies.
Chapter 01 · Unit 1 — Programming

Python Fundamentals

What Python is, how a program runs, and how to write your very first lines of code — starting from absolutely nothing.

⭐ Very Important for Boards 💡 Easy Marks 🔥 Frequently Asked

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).

🧑‍🏫If you are confused… "interpreted" vs "compiled" Analogy: A compiled language is like translating a whole book into another language, then handing over the finished translation. An interpreted language is like a live translator who speaks each sentence out loud as you say it. Python uses the live-translator approach — which is why an error only appears when Python reaches that line.

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).

TermMeaning (plain English)
InterpreterThe program that reads and runs your Python code.
StatementOne complete instruction (usually one line).
SyntaxThe grammar rules of Python. Break them → error.
CommentA note for humans that Python ignores. Starts with #.
TokenThe smallest unit Python recognises: keyword, identifier, literal, operator, punctuator.
📌Remember (exam favourite) The five kinds of tokens in Python: Keywords, Identifiers, Literals, Operators, Punctuators. This appears as a 1-mark/MCQ question.

1.3 Your first program

Syntax — the print function displays something on the screen:

syntax
print("text you want to show")

Example.

first.py
# My first Python program
print("Hello, CBSE!")
print("I am learning Python.")
OutputHello, CBSE! I am learning Python.

Line-by-line explanation

LineWhat it does
# My first Python programA 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.
▶ TRY IT YOURSELF
A safe mini-interpreter runs simple print(), numbers, and basic math right here.
// output appears here
⚠️Common mistakes
  • Forgetting the quotes: print(Hello) → Python thinks Hello is a variable name → NameError.
  • Capital Print instead of print → 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.

Exam alert "Why is indentation important in Python?" is a classic 1–2 mark question. Model answer: Python uses indentation instead of braces { } to group statements into a block. Wrong indentation changes the meaning of the program or causes an IndentationError.

1.5 Quick Quiz

Q1. Python is best described as a language that is…
Python runs line-by-line (interpreted) and reads close to English (high-level).
Q2. What symbol begins a single-line comment?
# starts a comment in Python. // and /* */ are from other languages.
Q3. Print("hi") (capital P) will…
Python is case-sensitive; 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

💻 Must-practise: Without running it, predict the output, then check with Try-It:
predict.py
print("CBSE", 2026)
print("Marks:", 70 + 30)
Show answer
OutputCBSE 2026 Marks: 100

print separates multiple items with a space; 70 + 30 is calculated before printing.

Chapter 02 · Unit 1 — Programming

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.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap 🧠 Higher-Order

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 =.

🧑‍🏫If you are confused… what a variable really is Analogy: A variable is a name tag on a box. The box holds a value; the name tag lets you find it again. In Python it's even lighter: the name is a label pointing at a value, and you can move the label to a different value any time.

Syntax

syntax
variable_name = value

Example

vars.py
name = "Ahana"
age = 17
marks = 95.5
print(name, age, marks)
OutputAhana 17 95.5

Line-by-line

LineExplanation
name = "Ahana"Creates a name name pointing to the string "Ahana".
age = 17Points age at the integer 17. No need to declare "int".
marks = 95.5Points marks at a float (decimal number).
print(name, age, marks)Prints all three, separated by spaces.

2.2 Rules for naming variables (identifiers)

RuleValid ✅Invalid ❌
Letters, digits, underscore onlytotal_1total-1
Cannot start with a digitm11m
No spacesfirst_namefirst name
Cannot be a keywordtotalfor, if
Case-sensitiveAge, age, AGE are three different variables
💡Easy marks "Which of the following are valid identifiers?" is a guaranteed MCQ. Just check: starts with letter/underscore, no spaces, no special symbols, not a keyword.

2.3 Core data types (must know for boards)

TypeKeywordExampleMutable?
Integerint70
Floating pointfloat95.5
Stringstr"CBSE"❌ Immutable
BooleanboolTrue, False
Listlist[1, 2, 3]✅ Mutable
Tupletuple(1, 2, 3)❌ Immutable
Dictionarydict{"a":1}✅ Mutable

You can check any value's type with the built-in type() function:

types.py
print(type(70))
print(type(95.5))
print(type("CBSE"))
print(type(True))
Output<class 'int'> <class 'float'> <class 'str'> <class 'bool'>

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."

🧑‍🏫If you are confused… Real-world example: A whiteboard is mutable — you erase and rewrite the same board. A printed page is immutable — to "change" it you must print a new page. Lists and dictionaries are whiteboards; strings, numbers and tuples are printed pages.
mutable.py
# 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
Output[100, 80, 70]
⚠️Common trap (boards love this) Trying name[0] = "X" on a string raises TypeError: 'str' object does not support item assignment. Strings and tuples cannot be changed by index.
▶ TRY IT YOURSELF
Predict each line before you run it.
// output appears here

2.5 Type conversion

Convert between types with int(), float(), str(). This matters hugely for input(), which always returns a string.

convert.py
a = "25"          # a is a STRING
b = int(a)         # now an INTEGER
print(b + 5)         # 30
print(str(b) + "5")  # "255" (string joining)
Output30 255
📌Remember + on numbers = addition; + on strings = joining (concatenation). This distinction is a favourite output-prediction question.

2.6 Quick Quiz

Q1. Which of these is mutable?
Only lists and dictionaries (among common types) can be changed in place.
Q2. type(95.5) returns…
Decimal numbers are floats. Python has no separate "double" type name.
Q3. Which is an invalid identifier?
A variable name cannot start with a digit.
Q4. print("2" + "3") outputs…
Both are strings, so + joins them into "23".

2.7 Output prediction (mini-set)

P1 · print(7 // 2, 7 % 2)
Output3 1

// is integer division (3), % is remainder (1).

P2 · print(int("12") + int("8"))
Output20

Both strings become integers first, then add.

P3 · print(3 + True)
Output4

🧠 Higher-order trap: True counts as 1, False as 0. So 3 + True = 4.

2.8 Debugging drill

🐞Find the error
buggy.py
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.

Chapter 03 · Unit 1 — Programming

Operators

The symbols that make Python do things — arithmetic, comparison, logic, assignment — plus the operator-precedence rules that decide output-prediction questions.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap

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

OperatorMeaningExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/True division (always float)7 / 23.5
//Floor division (drops decimal)7 // 23
%Modulus (remainder)7 % 21
**Exponent (power)2 ** 38
Exam alert — the three that get confused / 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).

arith.py
a = 17
print(a / 5)   # 3.4
print(a // 5)  # 3
print(a % 5)   # 2
print(a ** 2)  # 289
Output3.4 3 2 289
🧑‍🏫If you are confused… what % 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).

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 8False
<Less than5 < 8True
>=Greater or equal5 >= 5True
<=Less or equal5 <= 4False
⚠️The #1 trap in all of Python = 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.

OperatorTrue when…ExampleResult
andBOTH sides are True(5>2) and (3>1)True
orAT LEAST ONE side is True(5<2) or (3>1)True
notReverses the valuenot (5>2)False
💡Truth-table shortcut 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.

ShortcutSame as
x += 3x = x + 3
x -= 3x = x - 3
x *= 3x = x * 3
x //= 3x = x // 3
x %= 3x = x % 3

3.6 Operator precedence (who goes first)

When several operators appear together, Python follows a priority order. Higher rows run first.

PriorityOperators
1 (highest)**
2* / // %
3+ -
4== != < > <= >=
5not
6and
7 (lowest)or
📌Remember Use brackets ( ) to force the order you want and to make your intent obvious. Brackets always win over precedence.
precedence.py
print(2 + 3 * 4)      # 14, not 20
print((2 + 3) * 4)    # 20
print(2 ** 3 * 2)     # 16 (** first -> 8*2)
Output14 20 16
▶ TRY IT YOURSELF
Predict every line first, then run.
// output appears here

3.7 Quick Quiz

Q1. print(9 // 2) outputs…
Floor division drops the decimal: 9//2 = 4.
Q2. To test if a number n is even, you write…
An even number has remainder 0 when divided by 2.
Q3. (5 > 3) and (2 > 8) evaluates to…
and needs both True. The second part is False, so the whole is False.
Q4. 2 + 3 ** 2 gives…
** runs first: 3**2 = 9, then 2 + 9 = 11.

3.8 Output prediction

P1 · print(17 % 5, 17 // 5)
Output2 3
P2 · print(not (5 == 5))
OutputFalse

5==5 is True; not True is False.

P3 · x = 5; x *= 2 + 3; print(x)
Output25

🧠 Trap: the right side 2+3 is computed first (=5), then x = 5 * 5 = 25.

3.9 Debugging drill

🐞Find the error
buggy.py
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 = 163*16 = 482 + 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

💻 Must-practise: A number has 3 digits. Write expressions to extract each digit using // 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).

Chapter 04 · Unit 1 — Programming

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.

⭐ Very Important for Boards ⚠️ Common Trap 💡 Easy Marks

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

syntax
variable = input("prompt message")
greet.py
name = input("Enter your name: ")
print("Hello,", name)
Sample runEnter your name: Ahana Hello, Ahana
⚠️THE big trap — input is always a string
wrong.py
a = input("num: ")   # a is "5" (string)
print(a + 1)         # TypeError!
You cannot add a number to a string. Convert first with int() or float().

The correct pattern

add.py
a = int(input("First number: "))
b = int(input("Second number: "))
print("Sum =", a + b)
Sample runFirst number: 10 Second number: 20 Sum = 30
📌Remember the wrapping order 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

OptionControlsDefault
sepWhat goes between itemsa space " "
endWhat goes after the whole linea newline "\n"
sepend.py
print("2026", "03", "14", sep="-")
print("Loading", end="...")
print("done")
Output2026-03-14 Loading...done
Exam alert Questions about 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 "...".
▶ TRY IT YOURSELF
sep/end: line 2 supported; try predicting all four.
// output appears here

4.3 Quick Quiz

Q1. input() always returns data of type…
It always returns a string — you must convert for arithmetic.
Q2. To read an integer, the correct code is…
Read text with input(), then convert with int().
Q3. print("X", end=" ") then print("Y") outputs…
Changing end to a space keeps output on the same line.

4.4 Output prediction

P1 · print(1, 2, 3, sep="*")
Output1*2*3
P2 · print("Hi", end="") then print("There")
OutputHiThere

4.5 Debugging drill

🐞Find the error
buggy.py
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 end keeps 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.
avg.py
a = float(input("a: "))
b = float(input("b: "))
print("Average =", (a + b) / 2)
Chapter 05 · Unit 1 — Programming

Conditional Statements

Teaching your program to make decisions — if, if-else, if-elif-else, and nesting — where indentation stops being optional and becomes everything.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap 🧠 Higher-Order

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.

🧑‍🏫If you are confused… what a condition is Real-world example: "IF it is raining, take an umbrella." The part after IF is a yes/no question (a Boolean). If the answer is yes (True), you do the action. Python works exactly the same way.

5.2 The if statement

Syntax

syntax
if condition:
    statement      # runs only if condition is True
    statement      # (same indentation = same block)
Two things CBSE checks every year (1) The colon : at the end of the if line. (2) The indentation of the body. Miss either and you get a SyntaxError or IndentationError.
if.py
age = 20
if age >= 18:
    print("You can vote")
print("Program ends")
OutputYou can vote 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.

ifelse.py
n = 7
if n % 2 == 0:
    print("Even")
else:
    print("Odd")
OutputOdd

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.

grade.py
marks = 82
if marks >= 90:
    print("A")
elif marks >= 75:
    print("B")
elif marks >= 60:
    print("C")
else:
    print("D")
OutputB
📌Remember — order matters Because Python stops at the first true branch, arrange 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.

nested.py
num = 10
if num >= 0:
    if num == 0:
        print("Zero")
    else:
        print("Positive")
else:
    print("Negative")
OutputPositive
⚠️Common traps
  • 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).
▶ TRY IT YOURSELF (predict, this runner shows math/print only)
Conditions evaluate to True/False — check your grade-logic reasoning here.
// output appears here

5.6 Quick Quiz

Q1. What punctuation ends an if line?
Every if, elif, else header ends with a colon.
Q2. elif is short for…
It lets you check another condition when the previous ones were false.
Q3. In an if-elif-elif-else, how many branches can run?
Python runs the first true branch, then skips the rest — exactly one branch executes.
Q4. What makes a block "belong" to an if in Python?
Python uses indentation, not braces, to group a block.

5.7 Output prediction

P1 · x=5; if x>3: print("A"); print("B")
OutputA B

Condition true → "A"; the un-indented "B" always prints.

P2 · What if x = 2 in the code above?
OutputB

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")
OutputPass

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

🐞Find the error
buggy.py
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:

fixed.py
marks = 40
if marks >= 33:
    print("Pass")
else:
    print("Fail")

5.9 What did you learn?

Revision notes
  • if condition: — colon + indented block
  • else for the false case
  • elif for 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 elif ordering

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.
sign.py
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

💻 Must-practise: Input three numbers and print the largest — using only if/elif/else (no built-in max).
Show solution
largest.py
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.

Chapter 06 · Unit 1 — Programming

Loops

Making the computer repeat work — for, while, range(), nested loops, and the break/continue controls that turn up in almost every board paper.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap 🧠 Higher-Order

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.

🧑‍🏫If you are confused… what "iterate" means Real-world example: Doing 20 push-ups is a loop: the action (one push-up) is the same each time; only the count changes. Each single repetition is called an iteration.

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

CallProducesNote
range(5)0 1 2 3 4starts at 0, stops before 5
range(1, 5)1 2 3 4start, stop (stop excluded)
range(1, 10, 2)1 3 5 7 9start, stop, step
range(5, 0, -1)5 4 3 2 1negative step counts down
📌Remember — the "stop is excluded" rule 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

sum.py
total = 0
for i in range(1, 6):
    total = total + i
    print("Added", i, "-> total =", total)
print("Final sum:", total)
OutputAdded 1 -> total = 1 Added 2 -> total = 3 Added 3 -> total = 6 Added 4 -> total = 10 Added 5 -> total = 15 Final sum: 15

Line-by-line

LineWhat happens
total = 0Start 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 + iEach 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.

countdown.py
n = 5
while n > 0:
    print(n)
    n = n - 1     # update — or it loops forever!
print("Lift off")
Output5 4 3 2 1 Lift off
⚠️The infinite-loop trap Every 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 vs while — which to use? Rule of thumb: Known count ("do this 10 times", "for each item") → for. Unknown count, depends on a condition ("keep asking until the password is right") → while.

6.4 break and continue

KeywordEffect
breakExit the loop immediately, skip the rest.
continueSkip the rest of this iteration, jump to the next one.
breakcont.py
for i in range(1, 6):
    if i == 3:
        continue       # skip printing 3
    if i == 5:
        break          # stop before 5
    print(i)
Output1 2 4

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.

stars.py
for i in range(1, 4):
    for j in range(i):
        print("*", end="")
    print()   # move to next line
Output* ** ***
Exam alert — pattern printing Star/number triangles are guaranteed 2–4 mark questions. Trick: the outer loop controls the number of rows; the inner loop controls how many symbols per row. Use end="" to stay on the same line, then a bare print() to break the line.
▶ TRY IT YOURSELF (loops run mentally; this runner shows print/math)
Tip: "*" * 5 prints a string repeated — a shortcut for simple rows.
// output appears here

6.6 Quick Quiz

Q1. range(2, 8, 2) produces…
Start 2, step 2, stop before 8 → 2, 4, 6.
Q2. break does what?
break leaves the loop at once; continue skips just one iteration.
Q3. A while loop runs forever most often because…
Without an update that makes the condition eventually false, it never stops.
Q4. In a nested loop, for each outer step the inner loop runs…
The inner loop completes all its iterations for every single outer iteration.

6.7 Output prediction

P1 · for i in range(3): print(i, end=" ")
Output0 1 2
P2 🧠 · i=1; while i<=3: print(i*i); i+=1
Output1 4 9

Prints squares of 1,2,3.

P3 🧠 · for i in range(5): if i==2: break; print(i)
Output0 1

Loop stops the moment i reaches 2, so only 0 and 1 print.

6.8 Debugging drill

🐞Find the bug
buggy.py
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-based
  • range(start, stop, step); stop excluded
  • break exits; continue skips 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.
table.py
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

💻 Must-practise: Print this number triangle for n = 4:
1 1 2 1 2 3 1 2 3 4
Show solution
triangle.py
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.

Chapter 07 · Unit 1 — Programming

Strings

Text data — indexing, slicing, the methods CBSE loves, and the immutability rule that produces so many output-prediction questions.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap 🧠 Higher-Order

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":

CharacterPYTHON
Index (+)012345
Index (−)−6−5−4−3−2−1
index.py
s = "PYTHON"
print(s[0])    # P
print(s[-1])   # N (last char)
print(len(s))   # 6
OutputP N 6
📌Remember First index is 0, not 1. Last character is always 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.

slice.py
s = "PYTHON"
print(s[0:3])    # PYT
print(s[2:])     # THON
print(s[:4])     # PYTH
print(s[::2])    # PTO
print(s[::-1])   # NOHTYP (reversed!)
OutputPYT THON PYTH PTO NOHTYP
Exam alert — reversing 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.
🧑‍🏫If you are confused… slicing Analogy: Think of index positions as the gaps between characters, like ticket stubs. 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

immut.py
s = "cat"
# s[0] = "b"   ->  TypeError
s = "b" + s[1:]   # make a NEW string instead
print(s)
Outputbat
⚠️Common trap You cannot change one character with 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)

MethodDoesExample → 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
📌Remember These methods return a new string and leave the original unchanged (because strings are immutable). s.upper() does not change s unless you reassign: s = s.upper().
▶ TRY IT YOURSELF (string + and * supported)
+ joins strings; * repeats them.
// output appears here

7.5 Looping over a string

loopstr.py
s = "CBSE"
for ch in s:
    print(ch, end="-")
OutputC-B-S-E-

7.6 Quick Quiz

Q1. For s = "HELLO", s[-1] is…
-1 is the last character: O.
Q2. "PYTHON"[1:4] gives…
Indices 1, 2, 3 → Y, T, H. Index 4 (O) is excluded.
Q3. How do you reverse a string s?
Strings have no reverse() method; slicing with step −1 does it.
Q4. "banana".count("a") returns…
"a" appears at positions 1, 3, 5 → 3 times.

7.7 Output prediction

P1 · print("abc" * 2)
Outputabcabc
P2 · print("Hello".replace("l", "L"))
OutputHeLLo

Both l's are replaced; original is unchanged (a new string is returned).

P3 🧠 · s="PROGRAM"; print(s[1:6:2])
OutputRGA

Indices 1,3,5 → R, G, A (step 2, stop 6 excluded).

7.8 Debugging drill

🐞Find the bug
buggy.py
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 excluded
  • s[::-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.
vowels.py
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

💻 Must-practise: Check whether a word is a palindrome (reads the same forwards and backwards, e.g. "level").
Show solution
palindrome.py
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.

Chapter 08 · Unit 1 — Programming

Lists

Python's workhorse container — an ordered, changeable collection. Indexing, slicing, the methods you must know, and the mutability behaviour that catches students out.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap 🧠 Higher-Order

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.

list.py
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)
Output90 95 4 [90, 85, 75, 95]
📌Remember — list vs string Both use indexing and slicing the same way. The big difference: a list can be changed by index (marks[2] = 75), a string cannot.

8.2 Slicing lists

Exactly like strings: L[start:stop:step], stop excluded.

slice.py
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]
Output[20, 30, 40] [10, 20] [50, 40, 30, 20, 10]

8.3 List methods (must-know for boards)

MethodDoesExample (on L=[3,1,2])
append(x)Add x at the endL.append(5) → [3,1,2,5]
insert(i,x)Insert x at index iL.insert(0,9) → [9,3,1,2]
extend(list)Add all items of another listL.extend([7,8]) → [3,1,2,7,8]
remove(x)Delete first occurrence of xL.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 placeL.reverse() → [2,1,3]
index(x)Position of xL.index(2) → 2
count(x)How many times x appearsL.count(1) → 1
Exam alert — append vs extend 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.
⚠️Traps
  • sort() and reverse() return None — they change the list in place. Never write L = L.sort() (that sets L to None).
  • remove(x) needs the value; pop(i) needs the index.
  • remove on a value not present → ValueError.
🧑‍🏫If you are confused… "in place" vs "returns a new one" Analogy: "In place" = rearranging your bookshelf (the shelf changes, you get nothing handed back). "Returns a value" = the librarian hands you a book. sort() rearranges the shelf and hands back nothing (None). sorted(L) leaves your shelf alone and hands you a new sorted copy.
▶ TRY IT YOURSELF (numbers/print supported)
Reason about list sums/averages here before writing loop code.
// output appears here

8.4 Looping over a list

looplist.py
marks = [40, 55, 70]
total = 0
for m in marks:
    total += m
print("Sum:", total)
print("Average:", total / len(marks))
OutputSum: 165 Average: 55.0

8.5 Quick Quiz

Q1. Which method adds a single item to the end of a list?
append(x) adds x at the end. Python lists have no add()/push().
Q2. L = [1,2,3]; L = L.sort(). Now L is…
sort() sorts in place and returns None, so L becomes None. Trap!
Q3. pop() without an argument removes the…
With no index, pop() removes and returns the last element.
Q4. After 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)
Output[1, 3, 5, 8]
P2 🧠 · L=[1,2,3]; L.insert(1,9); print(L)
Output[1, 9, 2, 3]

9 is inserted at index 1; everything from there shifts right.

P3 🧠 · L=[10,20,30]; print(L[-1] + L[0])
Output40

Last (30) + first (10) = 40.

8.7 Debugging drill

🐞Find the bug
buggy.py
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.
minmax.py
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

💻 Must-practise: Given a list of numbers, build a new list containing only the even ones.
Show solution
evens.py
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.

Chapter 09 · Unit 1 — Programming

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.

⭐ Very Important for Boards ⚠️ Common Trap 💡 Easy Marks

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.

tuple.py
t = (10, 20, 30, 40)
print(t[0])    # 10
print(t[-1])   # 40
print(t[1:3])  # (20, 30)
print(len(t))   # 4
Output10 40 (20, 30) 4
📌Remember — brackets tell the type [ ] = list (mutable), ( ) = tuple (immutable), { } = dictionary/set. This is a guaranteed 1-mark identification question.

9.2 The single-element trap

single.py
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'>
Output<class 'int'> <class 'tuple'>
⚠️Common trap A one-element tuple needs a trailing comma: (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

immut.py
t = (1, 2, 3)
# t[0] = 99   ->  TypeError: cannot change a tuple
print(t)
🧑‍🏫If you are confused… why use a "locked" list? Real-world example: Your date of birth or a fixed set of month names should never change while the program runs. A tuple protects that data from accidental edits — it's a safety guarantee, plus it's slightly faster than a list.

9.4 Tuple methods & operations

Because tuples can't change, they only have two methods: count() and index(). But the usual operations still work.

OperationExampleResult
Concatenation +(1,2) + (3,4)(1, 2, 3, 4)
Repetition *(0,) * 3(0, 0, 0)
Membership in3 in (1,2,3)True
count(x)(1,1,2).count(1)2
index(x)(5,6,7).index(6)1
max/min/summax((4,9,2))9

9.5 Packing and unpacking (very examinable)

unpack.py
t = (18, "Ahana", 95.5)   # packing
age, name, marks = t          # unpacking
print(name, age, marks)
OutputAhana 18 95.5
Exam alert — swapping without a temp variable Python lets you swap in one line using tuple unpacking: a, b = b, a. This is a favourite short-answer/output question.
▶ TRY IT YOURSELF (numbers/print supported)
See the one-line swap in action.
// output appears here

9.6 Quick Quiz

Q1. Which brackets create a tuple?
Round brackets make a tuple; square = list; curly = dict/set.
Q2. type((7)) is…
No comma → it's just the integer 7, not a tuple.
Q3. Which is NOT allowed on a tuple t?
Tuples are immutable, so item assignment raises TypeError.
Q4. a, b = 3, 7 then a, b = b, a. Now a is…
The values swap; a becomes 7, b becomes 3.

9.7 Output prediction

P1 · t=(1,2,3); print(t*2)
Output(1, 2, 3, 1, 2, 3)
P2 · print((1,2)+(3,))
Output(1, 2, 3)
P3 🧠 · t=(5,); print(len(t))
Output1

The trailing comma makes it a one-element tuple, length 1.

9.8 Debugging drill

🐞Find the bug
buggy.py
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

💻 Must-practise: Given a tuple of numbers, print their sum and average without converting to a list.
Show solution
tupstats.py
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.

Chapter 10 · Unit 1 — Programming

Dictionaries

Storing data as key–value pairs — the structure behind so many CBSE case-based questions. Creating, accessing, updating, and looping through dictionaries.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap 🧠 Higher-Order

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.

🧑‍🏫If you are confused… key vs value Real-world example: A real dictionary: you look up a word (the key) to get its meaning (the value). A contacts app: the name is the key, the phone number is the value. You never say "give me contact number 3" — you say "give me Ahana's number".
dict.py
student = {"name": "Ahana", "age": 18, "marks": 95}
print(student["name"])    # Ahana
print(student["marks"])   # 95
OutputAhana 95
📌Remember — the rules of keys Keys must be unique and immutable (string, number, tuple — never a list). Values can be anything and can repeat. A dictionary is mutable (you can add/change/remove pairs).

10.2 Adding & updating

update.py
d = {"a": 1, "b": 2}
d["c"] = 3      # new key -> ADD
d["a"] = 99     # existing key -> UPDATE
print(d)
Output{'a': 99, 'b': 2, 'c': 3}
⚠️Common trap 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()

get.py
d = {"x": 10}
# print(d["y"])       -> KeyError (crash)
print(d.get("y"))        # None (no crash)
print(d.get("y", 0))     # 0 (default if missing)
OutputNone 0
Exam alert Accessing a missing key with 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

MethodReturns / doesExample (on d={'a':1,'b':2})
keys()All keysdict_keys(['a','b'])
values()All valuesdict_values([1,2])
items()All key–value pairs[('a',1),('b',2)]
get(k)Value for k, or Noned.get('a') → 1
update(d2)Merge another dict ind.update({'c':3})
pop(k)Remove key k, return its valued.pop('a') → 1

10.5 Looping through a dictionary

loopdict.py
marks = {"Maths": 95, "CS": 98, "Eng": 88}
for subject, score in marks.items():
    print(subject, "->", score)
OutputMaths -> 95 CS -> 98 Eng -> 88
💡Tip Looping for k in d: gives you the keys. To get keys and values together, loop over d.items() as shown above.
▶ TRY IT YOURSELF (numbers/print supported)
Reason about totals/averages over dictionary values here.
// output appears here

10.6 Quick Quiz

Q1. Dictionaries store data as…
Each entry pairs a unique key with a value.
Q2. Which CANNOT be a dictionary key?
Keys must be immutable. A list is mutable, so it can't be a key.
Q3. Accessing a missing key with d["z"] gives…
Square-bracket access on a missing key raises KeyError. Use get() to avoid it.
Q4. Which returns all key–value pairs?
items() gives (key, value) tuples; there is no pairs().

10.7 Output prediction

P1 · d={'a':1}; d['a']=5; print(d)
Output{'a': 5}

Existing key is overwritten, not duplicated.

P2 🧠 · d={'x':1,'y':2}; print(d.get('z',99))
Output99

Key 'z' is missing, so the default 99 is returned.

P3 🧠 · d={1:'a',2:'b'}; print(len(d))
Output2

len() counts the number of key–value pairs.

10.8 Debugging drill

🐞Find the bug
buggy.py
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]=v adds or updates
  • get, 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.
freq.py
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

💻 Must-practise: A dictionary holds subject:marks. Print the subject with the highest marks.
Show solution
topper.py
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.

Chapter 11 · Unit 1 — Programming

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.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap 🧠 Higher-Order

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.

🧑‍🏫If you are confused… what a function is for Real-world example: A microwave's "popcorn" button. Someone defined what it does once; you just press it whenever you want popcorn. You don't re-explain the timing each time. A function is your own custom button.

Three types of functions in the CBSE syllabus

TypeMeaningExample
Built-inCome with Pythonlen(), print(), max()
ModuleFrom an imported librarymath.sqrt(), random.randint()
User-definedWritten by you with defdef greet():

11.2 Defining and calling

Syntax

syntax
def function_name(parameters):
    # body (indented)
    statement
greet.py
def greet(name):
    print("Hello,", name)

greet("Ahana")     # call 1
greet("Ravi")      # call 2
OutputHello, Ahana Hello, Ravi
📌Remember — define vs call 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.

add.py
def add(a, b):      # a, b are PARAMETERS
    print(a + b)

add(10, 20)         # 10, 20 are ARGUMENTS
Output30

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.

return.py
def square(n):
    return n * n

result = square(5)   # store the returned value
print(result)         # 25
print(square(3) + square(4))  # 9 + 16 = 25
Output25 25
Exam alert — print vs return A function that 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.

⚠️Common trap Any code after return in the same block never runsreturn 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.

default.py
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)
Output25 125
📌Remember — order rule Parameters with defaults must come after those without. def f(a, b=2) is fine; def f(a=1, b) is a SyntaxError.
▶ TRY IT YOURSELF (numbers/print supported)
Work out what a square()/sum_upto() function should return.
// output appears here

11.6 Using library functions (modules)

module.py
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
💡Easy marks Know two common modules: 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

Q1. Which keyword defines a function?
Python uses def to define a function.
Q2. A function with no return statement returns…
By default a function returns None.
Q3. In def f(a, b=5), b is a…
b has a default value, so it's optional when calling.
Q4. 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)))
Output5

Inner f(3)=4, outer f(4)=5.

P2 🧠 · def g(): print("A"); return; print("B") then g()
OutputA

"B" never prints — return exits the function first.

P3 🧠 · def h(a,b=10): return a+b then print(h(5))
Output15

b uses its default 10; 5 + 10 = 15.

11.9 Debugging drill

🐞Find the bug
buggy.py
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)
  • return sends 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.
prime.py
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

💻 Must-practise: Write a function factorial(n) that returns n! (e.g. 5! = 120).
Show solution
factorial.py
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.

Chapter 12 · Unit 1 — Programming

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.

⭐ Very Important for Boards ⚠️ Common Trap 🧠 Higher-Order

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.

🧑‍🏫If you are confused… local vs global Real-world example: A global variable is like a notice on the school notice-board — everyone can read it. A local variable is like a note you write on your own desk during one class — it's gone when the class ends, and students in other rooms never see it.

12.2 Local variables

local.py
def show():
    x = 10       # x is LOCAL to show()
    print(x)

show()
# print(x)    ->  NameError: x not defined out here
Output10
⚠️Common trap A local variable cannot be used outside its function. Trying print(x) after the function raises a NameError. Local means local.

12.3 Global variables

global.py
count = 100          # GLOBAL

def display():
    print(count)     # can READ the global

display()
print(count)
Output100 100

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.

shadow.py
x = 5

def change():
    x = 99       # makes a NEW local x, not the global
    print("inside:", x)

change()
print("outside:", x)   # global unchanged
Outputinside: 99 outside: 5
Exam alert — the #1 scope question "What is the output?" with a global assigned inside a function is a guaranteed trick. The global stays as it was (5 here) because the assignment inside created a separate local variable. Watch for this exact pattern.

12.5 The global keyword

To actually change a global from inside a function, declare it global first.

globalkw.py
x = 5

def change():
    global x       # now x refers to the global
    x = 99
    print("inside:", x)

change()
print("outside:", x)   # now really changed
Outputinside: 99 outside: 99
📌Remember Use global sparingly. It's examinable, but in real programs it's usually cleaner to return a value and reassign, rather than reaching into globals.
▶ TRY IT YOURSELF (numbers/print supported)
Trace which value "wins" when local and global names clash — do it on paper too.
// output appears here

12.6 Quick Quiz

Q1. A variable created inside a function is…
It exists only inside the function while it runs.
Q2. A function can ____ a global variable without any keyword.
Reading is allowed; changing needs the global keyword.
Q3. To modify a global inside a function you use…
global x tells Python to use the outer variable.
Q4. x=5; inside a function x=10 (no global). Outside, x is…
The assignment made a separate local; the global stayed 5.

12.7 Output prediction

P1 🧠 · global a=1; func does a=2; print(a); then outside print(a)
Output2 1

Inside prints the local 2; outside the global is still 1.

P2 🧠 · same but with global a declared
Output2 2

Now the function changes the actual global.

12.8 Debugging drill

🐞Find the bug
buggy.py
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 x to 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.

Chapter 13 · Unit 1 — File Handling

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.

⭐ Very Important for Boards 🔥 Frequently Asked 💡 Easy Marks

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.

🧑‍🏫If you are confused… memory vs file Real-world example: Working in your head is like RAM — fast, but forgotten the moment you stop. Writing in a notebook is like a file — slower, but it's still there tomorrow. Programs use files whenever data must outlive a single run.

13.2 The three file types (know these cold)

TypeStoresReadable by humans?Example
Text fileCharacters (readable text)Yes — open in Notepad.txt, notes, logs
Binary fileRaw bytes / Python objectsNo — looks like gibberish.dat, images
CSV fileTable data, comma-separatedYes — a plain-text table.csv, spreadsheets
📌Remember CSV stands for Comma-Separated Values. It's technically a text file with a table layout — each line is a row, values separated by commas.

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

syntax
f = open("filename.txt", "mode")
# ... use f ...
f.close()

13.4 File modes — the master table

ModeMeaningIf file missingExisting data
"r"Read (default)ErrorKept
"w"WriteCreatedErased!
"a"Append (add to end)CreatedKept
"r+"Read + writeErrorKept
"rb", "wb", "ab"Same, but binary
⚠️The most dangerous mode Opening an existing file in "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.
Exam alert "What is the difference between 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.py
with open("notes.txt", "w") as f:
    f.write("Hello file")
# file is closed automatically here
📌Remember With with, you never call close() yourself — Python does it for you when the block ends. Fewer bugs, cleaner marks.

13.6 Quick Quiz

Q1. Which mode ERASES existing file content?
"w" truncates the file to empty before writing.
Q2. CSV stands for…
Each row is a line; values are separated by commas.
Q3. The advantage of with open(...) is…
with guarantees the file is closed even if an error occurs.
Q4. To ADD data without erasing, open in mode…
"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.

Chapter 14 · Unit 1 — 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.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap 🧠 Higher-Order

14.1 Writing to a text file

MethodDoes
write(s)Writes the string s (no automatic newline)
writelines(list)Writes each string in a list (still no auto newline)
write.py
with open("notes.txt", "w") as f:
    f.write("Line one\n")   # \n = newline
    f.write("Line two\n")
File now containsLine one Line two
⚠️The newline gotcha Unlike 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

MethodReturns
read()The whole file as one string
readline()One line (including its \n)
readlines()A list of all lines
read.py
with open("notes.txt", "r") as f:
    data = f.read()
print(data)
OutputLine one Line two

The cleanest way to read line by line

loopread.py
with open("notes.txt", "r") as f:
    for line in f:          # loop directly over the file
        print(line.strip())   # strip() removes the trailing \n
💡Tip Looping 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.
🧑‍🏫If you are confused… read vs readline vs readlines Analogy: 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

append.py
with open("notes.txt", "a") as f:
    f.write("Line three\n")   # old lines stay, this is added
▶ TRY IT YOURSELF (string logic supported)
Rehearse the string operations you'll apply to each file line.
// output appears here

14.4 The classic CBSE text-file programs

(a) Count the number of lines

countlines.py
count = 0
with open("notes.txt", "r") as f:
    for line in f:
        count += 1
print("Lines:", count)

(b) Count words

countwords.py
words = 0
with open("notes.txt", "r") as f:
    for line in f:
        words += len(line.split())   # split on spaces
print("Words:", words)
Exam alert 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

startswith.py
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

Q1. read() returns…
read() returns everything as a single string.
Q2. Which returns a LIST of all lines?
readlines() (plural) gives a list; readline() gives one line.
Q3. write() differs from print() because it…
You must add \n yourself with write().
Q4. "a b c".split() gives a list of length…
Splits into ['a','b','c'] → 3 words.

14.6 Output prediction

P1 · "hello world".split()
Output['hello', 'world']
P2 🧠 · file has 3 lines; len(f.readlines()) gives…
Output3

readlines() returns a list with one item per line.

14.7 Debugging drill

🐞Find the bug
buggy.py
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 \n
  • for line in f: for line-by-line
  • split() to count words
Top mistakes
  • Forgetting \n in 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.
vowelwords.py
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

💻 Must-practise: Copy the contents of source.txt into dest.txt, converting everything to uppercase.
Show solution
copyupper.py
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.

Chapter 15 · Unit 1 — File Handling

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.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap 🧠 Higher-Order

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.

🧑‍🏫If you are confused… text vs binary storage Analogy: Saving to a text file is like describing your Lego model in words — to rebuild it you must re-read and reconstruct. Saving to a binary file (pickling) is like putting the built model in a box — you take out the finished object, ready to use, no rebuilding.

15.2 The pickle module

Python's pickle module does the conversion. Two functions do all the work:

FunctionDoesDirection
pickle.dump(obj, f)Writes (serialises) an object to a binary fileobject → file
pickle.load(f)Reads (deserialises) an object backfile → object
📌Remember — modes are binary Binary files use "wb" (write binary), "rb" (read binary), "ab" (append binary). You must import pickle first. "Pickling" = writing; "unpickling" = reading.

15.3 Writing an object

dump.py
import pickle

student = {"name": "Ahana", "marks": 95}

with open("student.dat", "wb") as f:
    pickle.dump(student, f)
print("Saved!")
OutputSaved!

15.4 Reading it back

load.py
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
Output{'name': 'Ahana', 'marks': 95} Ahana
Exam alert The object comes back with its type intact — a dictionary is still a dictionary you can index. That's the whole point of binary files versus text files. State this in "why use binary files?" answers.

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.

records.py
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"])
Output1 A 2 B

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.

eof.py
import pickle
with open("data.dat", "rb") as f:
    while True:
        try:
            rec = pickle.load(f)
            print(rec)
        except EOFError:
            break       # reached end — stop
⚠️Common trap Calling 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.)
💡The update-a-record pattern (very examinable) To modify a record: (1) read all records into a list, (2) change the one you want in memory, (3) write the whole list back with "wb". You cannot edit one record in place inside a binary file.

15.7 Quick Quiz

Q1. Which module handles binary files in CBSE Python?
pickle serialises and deserialises Python objects.
Q2. pickle.dump() is used to…
dump writes (object → file); load reads (file → object).
Q3. The correct mode to write a binary file is…
"wb" = write binary.
Q4. Reading past the last object with load() raises…
End-of-file during load raises EOFError — catch it to stop.

15.8 Behaviour prediction

P1 · You dump a list, then load it. The type you get back is…
Answerlist

Pickle preserves the exact type. A list stays a list.

P2 🧠 · You open a binary file in "w" (not "wb") and dump. Result?
AnswerTypeError

Pickle writes bytes; a text-mode file expects strings, so it errors. Always use "wb".

15.9 Debugging drill

🐞Find the bug
buggy.py
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 pickle
  • dump(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.
students.py
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

💻 Must-practise: A binary file "emp.dat" holds a list of employee dicts with keys "id" and "salary". Give everyone a 10% raise and save it back.
Show solution
raise.py
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.

Chapter 16 · Unit 1 — File Handling

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.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap

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.

marks.csv (contents)
Roll,Name,Marks
1,Ahana,95
2,Ravi,88
🧑‍🏫If you are confused… what CSV really is Analogy: A CSV is a spreadsheet with the grid lines removed — just values with commas marking where each cell ends and a new line marking each row. Excel understands it instantly.

16.2 The csv module

You import csv, then use a writer to save rows and a reader to read them.

Object / methodDoes
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

writecsv.py
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])
Exam alert — 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

readcsv.py
import csv

with open("marks.csv", "r") as f:
    r = csv.reader(f)
    for row in r:
        print(row)
Output['Roll', 'Name', 'Marks'] ['1', 'Ahana', '95'] ['2', 'Ravi', '88']
⚠️Common trap — everything reads as strings Each row is a list of strings. The number 95 comes back as "95". To do arithmetic, convert with int() first: int(row[2]). Forgetting this causes wrong sums or TypeErrors.

16.5 Skipping the header

skiphdr.py
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])
OutputAhana scored 95 Ravi scored 88
💡Tip next(reader) reads and throws away one row — handy for skipping the header before processing the data rows.

16.6 Quick Quiz

Q1. CSV stands for…
Values in each row are separated by commas.
Q2. Why add newline="" when writing a CSV?
It prevents an extra blank line between rows on Windows.
Q3. When reading, each row is returned as a…
csv.reader yields each row as a list of string values.
Q4. Which writes several rows at once?
writerows() takes a list of rows.

16.7 Behaviour prediction

P1 · A CSV cell holds 88. After reading, type(row[2]) is…
Answerstr

CSV values always come back as strings; convert for maths.

P2 🧠 · You write with writerow("Ahana") instead of writerow(["Ahana"]). What happens?
AnswerA,h,a,n,a

A string is iterable, so each character becomes its own column. Always pass a list.

16.8 Debugging drill

🐞Find the bug
buggy.py
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.
avgcsv.py
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

💻 Must-practise: Read "marks.csv" and write a new file "toppers.csv" containing only students who scored more than 90.
Show solution
toppers.py
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.

Chapter 17 · Unit 1 — Programming

Exception Handling

Stopping your program from crashing when something goes wrong — try, except, else, finally, and the common exceptions CBSE expects you to name.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap 🧠 Higher-Order

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.

🧑‍🏫If you are confused… why catch errors? Real-world example: A vending machine that jams shouldn't explode — it should say "sorry, try again" and refund you. Exception handling is that graceful "sorry" instead of a crash. The user typing "abc" when you expected a number shouldn't kill your whole program.

17.2 Common exceptions to know

ExceptionHappens when…
ValueErrorint("abc") — wrong value for the type
ZeroDivisionErrordividing by zero
TypeError"5" + 3 — incompatible types
IndexErrorlist/string index out of range
KeyErrormissing dictionary key
NameErrorusing a variable that isn't defined
FileNotFoundErroropening a file that doesn't exist
Exam alert "Name the exception raised by ___" is a very common 1-mark question. Learn the table above — especially ValueError, ZeroDivisionError, IndexError, and KeyError.

17.3 The try–except block

Syntax

syntax
try:
    # risky code that might fail
except ErrorType:
    # runs only if that error happens
divide.py
try:
    a = int(input("Number: "))
    print(100 / a)
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Please enter a valid number")
If user types 0Cannot divide by zero
If user types "abc"Please enter a valid number
📌Remember You can have multiple except blocks, one per error type. Python runs the first one that matches the error that actually occurred.

17.4 else and finally

BlockRuns when…
tryalways attempted first
exceptonly if a matching error occurs
elseonly if no error occurred
finallyalways, error or not
full.py
try:
    x = 10 / 2
except ZeroDivisionError:
    print("Error")
else:
    print("Success:", x)      # no error -> runs
finally:
    print("Done (always runs)")
OutputSuccess: 5.0 Done (always runs)
Exam alert — 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.
⚠️Common traps
  • A bare except: catches every error, hiding bugs. Prefer naming the specific exception.
  • Order matters: put specific exceptions before a general Exception.
  • try must be followed by at least one except or finally.
▶ TRY IT YOURSELF (predict which block runs)
Line 4 divides by zero — decide which except would catch it.
// output appears here

17.5 Quick Quiz

Q1. An exception is an error that occurs…
Exceptions are runtime errors, caught with try/except.
Q2. int("hello") raises…
The string can't be converted to an int → ValueError.
Q3. Which block always runs?
finally executes whether or not an exception occurred.
Q4. else in try/except runs when…
The else block runs only if the try succeeded with no exception.

17.6 Output prediction

P1 · try: print(5/0) except ZeroDivisionError: print("oops")
Outputoops
P2 🧠 · try: print("A") except: print("B") finally: print("C")
OutputA C

No error, so B is skipped; C (finally) always runs.

P3 🧠 · L=[1,2]; try: print(L[5]) except IndexError: print("bad index")
Outputbad index

Index 5 is out of range → IndexError, caught cleanly.

17.7 Debugging drill

🐞Find the bug
buggy.py
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:

fixed.py
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/except catches it
  • Multiple except blocks 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.
safediv.py
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

💻 Must-practise: Open a file that may not exist and print its contents, showing a friendly message instead of crashing if it's missing.
Show solution
safeopen.py
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.

Chapter 18 · Unit 1 — Data Structures

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.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap 🧠 Higher-Order

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).

🧑‍🏫If you are confused… what LIFO means Real-world example: A pile of plates. You add a plate on top, and you take a plate from the top. The plate you put on last is the one you grab first. You can't pull the bottom plate out without removing the ones above it. That's exactly a stack.

18.2 Stack operations

OperationMeaningList method used
pushAdd an item to the toplist.append(x)
popRemove & return the top itemlist.pop()
peek / topLook at the top item without removinglist[-1]
isEmptyCheck if the stack has no itemslen(list) == 0
📌Remember — a stack IS a list, used with discipline In CBSE Python, a stack is just a normal list where you only ever use append() to add and pop() to remove. The "top" is the last element (list[-1]).

18.3 Push and pop in action

stack.py
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
OutputStack: [10, 20, 30] Popped: 30 Now: [10, 20] Top now: 20
Exam alert — trace the order Push 10, 20, 30; then pop three times gives 30, 20, 10 — the reverse of insertion. Being able to trace push/pop sequences and predict the output is a guaranteed board question.

18.4 The empty-stack trap

underflow.py
stack = []
# stack.pop()   -> IndexError: pop from empty list

if len(stack) == 0:
    print("Stack is empty (underflow)")
else:
    print(stack.pop())
OutputStack is empty (underflow)
⚠️Common trap — underflow Popping from an empty stack raises an IndexError. Always check isEmpty (len(stack)==0) before popping or peeking. This is called stack underflow.

18.5 A menu-driven stack (exam pattern)

menustack.py
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
Output8 8 5 Underflow
💡Applications of a stack (know these for theory marks) Undo/redo in editors, the browser Back button, reversing a sequence, checking balanced brackets, and function-call handling (the "call stack"). All use LIFO.
▶ TRY IT YOURSELF (numbers/print supported)
This mirrors popping a stack that had 10,20,30 pushed.
// output appears here

18.6 Quick Quiz

Q1. A stack follows the principle…
Last In, First Out — the last pushed item is popped first.
Q2. Which list method performs a push?
append() adds to the top (end) of the stack.
Q3. Popping from an empty stack causes…
Popping an empty list raises IndexError — check isEmpty first.
Q4. Push 1,2,3 then pop once. The popped value is…
The last pushed (3) is removed first.

18.7 Output prediction

P1 · Push A,B,C. Pop, pop. Print top.
OutputA

After two pops (C then B), the top is A.

P2 🧠 · s=[1,2,3]; s.append(s.pop()+s.pop()); print(s)
Output[1, 5]

First pop()→3, second pop()→2, sum 5 appended. List had 1 left, so [1, 5].

18.8 Debugging drill

🐞Find the bug
buggy.py
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.
stackfns.py
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.
reverse_stack.py
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

💻 Must-practise: Use a stack to check whether brackets in a string are balanced, e.g. "(a+b)" is balanced, "(a+b" is not.
Show solution
balanced.py
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.

Chapter 19 · Unit 1 — Algorithms

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.

⭐ Very Important for Boards 🔥 Frequently Asked 🧠 Higher-Order ⚠️ Common Trap

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).

🧑‍🏫If you are confused… what linear search is Real-world example: Looking for a friend in a queue by walking from the front and checking each person until you spot them. You might get lucky early, or check everyone. That's linear search.
linear.py
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
Output3 -1
📌Remember the convention A search function returns the index if found, and −1 if not found. Returning −1 for "not present" is a standard convention examiners expect.

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.

🧑‍🏫If you are confused… how bubbling works Analogy: Like heavier bubbles sinking and lighter ones rising in water — after each pass, the biggest unsorted value settles into its final place at the end. Repeat until everything is in order.
bubble.py
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]))
Output[1, 2, 4, 5]

Trace of pass 1 on [5, 1, 4, 2]

CompareActionList 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.

Exam alert — swap syntax Python swaps two values in one line: 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.

🧑‍🏫If you are confused… insertion sort Real-world example: Sorting playing cards in your hand. You pick up each new card and slide it left until it sits in the right spot among the cards you've already arranged. That's insertion sort.
insertion.py
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]))
Output[1, 2, 3]
💡Quick comparison Both bubble and insertion sort are simple and fine for small lists. Linear search checks items one by one. Python's built-in sorted() / .sort() are faster in practice — but boards want you to understand and trace the manual algorithms.
▶ TRY IT YOURSELF (swap logic supported)
Practise the one-line swap that powers bubble sort.
// output appears here

19.4 Quick Quiz

Q1. Linear search returns what when the item is missing?
By convention, −1 signals "not found".
Q2. In bubble sort, after the first pass…
Each pass bubbles the biggest remaining value to its final position at the end.
Q3. Bubble sort compares…
It compares each pair of neighbours and swaps if out of order.
Q4. Which sort inserts each item into its correct place among sorted items to the left?
That's the defining idea of insertion sort.

19.5 Output / trace prediction

P1 · Linear search for 2 in [4,9,2,7] returns…
Output2

2 is at index 2.

P2 🧠 · One bubble pass on [3,2,1] gives…
Output[2, 1, 3]

3>2 swap → [2,3,1]; 3>1 swap → [2,1,3]. Largest (3) now at the end.

19.6 Debugging drill

🐞Find the bug
buggy.py
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.
PassList 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.
count_cmp.py
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

💻 Must-practise: Sort a list in descending order using bubble sort (change one operator).
Show solution
desc.py
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.

Chapter 20 · Unit 3 — Database

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.

⭐ Very Important for Boards 🔥 Frequently Asked ⚠️ Common Trap 🧠 Higher-Order
📌Prerequisite This chapter assumes you know basic SQL (CREATE, INSERT, SELECT, UPDATE, DELETE) from Unit 3. Here we focus on connecting Python to MySQL and running those SQL commands from Python code.

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.

🧑‍🏫If you are confused… what connectivity means Real-world example: MySQL is the warehouse where goods (data) are stored. Python is the shop assistant. Connectivity is the phone line between them — the assistant phones the warehouse to add stock, check quantities, or fetch an item. Without the phone line, they can't cooperate.

20.2 The interface module

Python uses the mysql.connector module to talk to MySQL. You import it first.

import.py
import mysql.connector
💡Easy marks "Which module is used to connect Python with MySQL?" → mysql.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.

StepWhat you doCode
1. ImportImport the moduleimport mysql.connector
2. ConnectOpen a connection to the databaseconnect(...)
3. CursorCreate a cursor to run SQLcon.cursor()
4. ExecuteRun an SQL querycur.execute(sql)
5. Fetch / CommitRead results, or save changesfetchall() / commit()

20.4 Making the connection

connect.py
import mysql.connector

con = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="yourpassword",
    database="school"
)

if con.is_connected():
    print("Connected successfully")
OutputConnected successfully

The four connection parameters

ParameterMeaning
hostWhere MySQL runs — usually "localhost" (same computer)
userMySQL username, commonly "root"
passwdThe MySQL password you set
databaseThe database name to use
⚠️Common trap A wrong password or database name raises an error at the 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.

select.py
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)
Sample output(1, 'Ahana', 95) (2, 'Ravi', 88)
📌Remember — each row is a tuple The database returns each record as a tuple, and fetchall() returns a list of tuples. Access a field by index: row[0], row[1], etc.

20.6 The three fetch methods

MethodReturns
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
Exam alert 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

insert.py
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")
Output1 record inserted
⚠️The most important trap in this chapter After any query that changes data — INSERT, UPDATE, DELETE — you MUST call 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.
🧑‍🏫If you are confused… why commit? Analogy: Editing a document is like changing data; 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.

param.py
roll = 4
name = "Sara"
marks = 87

sql = "INSERT INTO student VALUES (%s, %s, %s)"
cur.execute(sql, (roll, name, marks))
con.commit()
💡Tip The %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

close.py
con.close()   # release the connection when done

20.10 Full example — search by condition

full.py
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()
Sample outputRoll: 1 Name: Ahana Roll: 3 Name: Meera
▶ TRY IT YOURSELF (tuple/index logic supported)
Practise reading tuple fields the way you'd read a fetched DB row.
// output appears here

20.11 Quick Quiz

Q1. Which module connects Python to MySQL?
CBSE uses the mysql.connector module.
Q2. After an INSERT you must call…
Changes are only saved permanently after commit().
Q3. fetchone() returns…
It returns the next single row as a tuple (or None).
Q4. What object carries SQL to the database?
The cursor executes queries and holds results.

20.12 Behaviour prediction

P1 · fetchall() on a table with 3 rows returns a…
Answerlist of 3 tuples
P2 🧠 · You INSERT a row but never call commit(). After the program ends, the row is…
Answergone (not saved)

Without commit, the change is rolled back when the connection closes.

20.13 Debugging drill

🐞Find the bug
buggy.py
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".
books.py
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

💻 Must-practise: Write a program that asks the user for a roll number and displays that student's record from the "student" table (use a parameterised query).
Show solution
findstudent.py
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.

Revision · Quick Reference

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.

⭐ Print this 💡 Last-minute revision
🧭How to use Don't read this top to bottom the first time — it's a reference, not a lesson. Learn each topic from its chapter, then use this sheet to refresh quickly before the exam.

1. Core syntax

TaskSyntax
Comment# this is a comment
Printprint(a, b, sep=" ", end="\n")
Input (always string)x = input("prompt")
Integer inputn = int(input("prompt"))
Assignmentx = 5
Multiple assignmenta, b = 1, 2
Swap (no temp)a, b = b, a
Import moduleimport math

2. Data types & mutability

TypeExampleMutable?
int70
float95.5
str"CBSE"❌ Immutable
boolTrue / False
list[1, 2, 3]✅ Mutable
tuple(1, 2, 3)❌ Immutable
dict{"a": 1}✅ Mutable
📌Memory hook Mutable = list & dict. Everything else you use (int, float, str, tuple, bool) is immutable. Check any type with type(x); convert with int() / float() / str().

3. Operators

CategoryOperators
Arithmetic+ - * / // % **
Comparison== != < > <= >=
Logicaland or not
Assignment= += -= *= //= %=
Membershipin, not in
Special divisionsExample → Result
/ true division (float)7 / 2 → 3.5
// floor division7 // 2 → 3
% remainder7 % 2 → 1
** power2 ** 3 → 8
📌Precedence (high → low) *** / // %+ - → comparisons → notandor. Brackets always win.

4. Control flow

conditionals
if cond:
    ...
elif cond2:
    ...
else:
    ...
loops
for i in range(start, stop, step):
    ...
while cond:
    ...        # remember to update!
# break = exit loop | continue = skip iteration
range() callProduces
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

MethodDoesExample → 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)lengthlen("abc") → 3
📌Slicing s[start:stop:step] — stop excluded. s[::-1] reverses. s[-1] = last char. First index is 0.

6. List methods

MethodDoes
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
⚠️Traps 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

PointDetail
Createt = (1, 2, 3)
One elementt = (5,) — comma required!
Immutablecan't change items
Only 2 methodscount(), index()
Unpackinga, b, c = t

8. Dictionary methods

MethodDoes
d[key]access (KeyError if missing)
d.get(key, default)safe access, no crash
d[key] = valadd 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
📌Rules Keys unique & immutable (str/num/tuple — not list). Loop values with for k, v in d.items():

9. Functions

function
def name(param, default=2):
    return value    # exits + sends back

name(argument)       # call
PointDetail
Parameter vs argumentdefinition vs call value
print vs returnprint shows; return gives back (reusable)
No returnfunction returns None
Default paramsmust come after non-default
3 typesbuilt-in, module, user-defined
ModuleCommon functions
mathsqrt, floor, ceil, pow, pi
randomrandint(a,b) (both ends), random() (0–1)

10. Scope

PointDetail
Localinside a function; gone after it ends
Globaltop level; readable everywhere
Assigning inside a functionmakes a local by default
global xneeded to reassign a global inside a function
LEGBLocal → Enclosing → Global → Built-in

11. File handling

ModeMeaningMissing file
"r"read (default)Error
"w"write (erases!)Creates
"a"append (keeps old)Creates
"r+"read + writeError
+bbinary: rb wb ab
text files
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
binary (pickle)
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)
csv
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
📌File must-remembers "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/except
try:
    risky()
except ValueError:
    ...          # specific error
except ZeroDivisionError:
    ...
else:
    ...          # runs if NO error
finally:
    ...          # ALWAYS runs
ExceptionCause
ValueErrorint("abc")
ZeroDivisionErrordivide by 0
TypeError"5" + 3
IndexErrorindex out of range
KeyErrormissing dict key
NameErrorundefined variable
FileNotFoundErrorfile doesn't exist
EOFErrorpickle load past end

13. Stack (LIFO)

OperationCode
pushstack.append(x)
popstack.pop()
peek / topstack[-1]
isEmptylen(stack) == 0
📌Remember Last In First Out. Popping empty → IndexError (underflow). Apps: undo, back button, reversing, balanced brackets.

14. Searching & sorting

AlgorithmKey idea
Linear searchcheck each item; return index or −1
Bubble sortswap adjacent pairs; biggest bubbles to end each pass
Insertion sortinsert each item into the sorted left part
bubble core
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

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()
StepFetch methodReturns
1 importfetchone()one tuple
2 connectfetchmany(n)n tuples (list)
3 cursorfetchall()all rows (list)
4 executerowcountrows affected
5 fetch/commit
⚠️#1 error Forgetting 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)

MistakeFix
= vs == in conditionsuse == to compare
Doing maths on input()wrap in int()/float()
range stop includedstop is excluded
while with no updateinfinite loop — add update
editing a string by indexstrings immutable — rebuild
L = L.sort()sort returns None; call then use L
append vs extendappend = 1 item; extend = each
missing dict keyuse .get()
print vs returnreturn to reuse a value
using local outside functionreturn it, or use global
"w" wiping a fileuse "a" to keep data
writing a number to filef.write(str(x))
CSV blank rowsopen with newline=""
forgetting commit()commit after INSERT/UPDATE/DELETE
popping empty stackcheck 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
📌One-line reminders Indentation is grammar · input is a string · stop is excluded · strings/tuples immutable · sort returns None · commit your DB changes · close your files · stack is LIFO.
Revision · Study Plans

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.

⭐ Plan your prep 💡 Tick & track
🧭Pick your plan More than 3 weeks left → follow the 30-day plan. About a week left → the 7-day sprint. Exam tomorrow → jump to the 24-hour checklist. Each checkbox you tick is remembered on this device.
📊
Revision progress
0%

📅 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.

Sprint priority If you can't finish everything, guarantee these: output prediction, file handling programs, SQL connectivity (commit!), and the top-errors table. They carry the most marks for the least time.

⏰ 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

📌The night-before rule Confidence comes from revision you've already done, not from new topics learned in a panic. Trust your preparation, do a calm read-through of the cheat sheet, and rest.
Exam Prep · Mock Paper

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.

⭐ Full 70 marks 🔥 Board pattern 💻 Timed: 3 hours
📋General instructions This paper has 35 questions across 5 sections, all compulsory. Section A: 1 mark each (Q1–18). Section B: 2 marks each (Q19–25). Section C: 3 marks each (Q26–29). Section D: 4 marks each (Q30–32). Section E: 5 marks each (Q33–35). Internal choices are given in some questions. Write clean, indented code.

🧭How to use this Set a 3-hour timer. Write answers on paper. Only after finishing (or after your time is up) reveal the solutions one by one and mark yourself honestly using the scheme shown. Note every mistake — that list is your real study guide.

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.

buggy
n = int(input("Enter: ")
if n % 2 = 0
    print("Even")
else
    print("Odd")
Solution
corrected
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
SQL
-- (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.


📊Score yourself Add up: Section A (18) + B (14) + C (12) + D (12) + E (15) = 70. Above 55 is excellent, 40–55 solid, below 40 means revisit the weak chapters and retry after two days. Keep your mistake list — retrying the exact questions you missed is the fastest way to improve.
Exam Prep · Mock Paper

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.

⭐ Full 70 marks 🔥 Board pattern 💻 Timed: 3 hours
📋General instructions 35 questions, all compulsory, across 5 sections. Section A: Q1–18 (1 mark). Section B: Q19–25 (2 marks). Section C: Q26–29 (3 marks). Section D: Q30–32 (4 marks). Section E: Q33–35 (5 marks). Write clean, indented code and show outputs where asked.

🧭Same rules 3-hour timer, answers on paper, solutions revealed only after finishing. Compare your Paper 2 score against Paper 1 — the gap tells you whether your revision is working.

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:

buggy
def greet(name):
print("Hello" + name)
for i in range(3)
    greet("Sam")
Solution
corrected
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
SQL
-- (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.


📊Compare your two papers Section A (18) + B (14) + C (12) + D (12) + E (15) = 70. Put your Paper 1 and Paper 2 scores side by side. A rising score confirms your revision plan is working; a flat or lower score points to specific chapters — go back to those, then attempt the exact questions you missed.
Exam Prep · Question Bank

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.

⭐ Topic-wise practice 🔥 Board-style 💡 Drill weak areas
🧭How to use These are labelled original / board-style — not copied past papers. Pick the chapter you're weakest in, do those questions on paper, then check. The difficulty chips (Easy Medium Hard) tell you how much a real board question of that type usually stretches you.

📘 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
SQL
-- (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.


Practice strategy Do every Easy question in a chapter until you get them right without looking. Then Medium. Save Hard for when the basics are solid — but don't skip them, because the 4- and 5-mark board questions are built from exactly these patterns (digit extraction, frequency dictionaries, stack tricks, CSV conversion, and commit()).
Exam Prep · Masterclass

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.

⭐ High-yield ⚠️ Trap-focused 🔥 Exam favourites
🧭How to work these For debugging: read every line slowly, checking the four usual suspects — colons, indentation, = 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:

buggy
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:

buggy
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:

buggy
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:

buggy
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:

buggy
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:

buggy
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:

buggy
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:

buggy
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: [].

⚠️Correction The real output is [], 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.

📌The debugging checklist Colons after if/for/while/def/else · consistent indentation · == 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.
🧠Teach me like a tutor Output questions aren't about speed — they're about discipline. The students who lose marks are the ones who trust their eyes. The students who score full marks keep a tiny variable table and update it every single line, including the boring ones. Slow is smooth, smooth is fast. Trace O12 again from scratch and you'll see why finishing the trace matters.
Guide complete

🎉 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.

What's included 20 teaching chapters · master cheat sheet · 30/7/1-day revision plans · 2 full mock papers with solutions · a topic-wise question bank · and a debugging & output masterclass. Everything follows the same teaching sequence: concept → explanation → example → line-by-line → common mistakes → practice → CBSE questions → challenge.

📚 Unit 1 — Programming & core concepts

#Chapter
1–6Fundamentals · Variables & Data Types · Operators · Input/Output · Conditionals · Loops
7–10Strings · Lists · Tuples · Dictionaries
11–12Functions · Scope
13–16File Handling overview · Text Files · Binary Files (pickle) · CSV Files
17–19Exception Handling · Stack · Searching & Sorting

🗄️ Unit 3 — Database

#Chapter
20SQL / Python Connectivity

🎯 Exam prep suite

SectionWhat it's for
Master Cheat SheetOne-page reference for last-minute revision
Revision Plans30-day, 7-day & 24-hour trackable schedules
Mock Paper 1 · Mock Paper 2Two full 70-mark timed papers with solutions
Question BankTopic-wise drills tagged by difficulty
Debugging & OutputThe two highest-yield question types
Suggested path Learn chapter by chapter, ticking each done. When the syllabus is covered, follow a revision plan, sit the two mock papers a few days apart, drill your weak chapters in the question bank, and finish with the debugging & output masterclass the day before. You're ready.
🧠One last word This whole guide is only useful if you write code with your own hands. Read a concept, then close the page and type the example from memory. Get it wrong, fix it, repeat. That struggle is the learning. You've got everything you need here — now go build the habit. Good luck.
🚀🐍

Wait Bro..

I am coming Soon! This subject is still being built with the same zero-to-hero love. Hang tight.