VM-LEARNING /class.xii ·track.cs ·ch-1-1 session: 2026_27
$cd ..

~/Revision of Python topics covered in Class XI

root@vm-learning ~ $ open ch-1-1
UNIT 1 ▪ CHAPTER 1
01
Revision of Python topics covered in Class XI
Problem-Solving · Tokens · Data Types · Operators · I/O · Errors · Flow · Loops · Strings · Lists · Tuples · Dicts · Modules
This chapter is a concise refresher of every Python topic covered in Unit 2 of Class XI (Chapters 7–20). Every heading of the original fourteen chapters is retained so you can cross-reference your Class XI notes, but the explanations have been tightened into tables, bullets and short code snippets. Read this once before starting the new Class XII material (user-defined functions, exception handling, file I/O and stacks) — those chapters build directly on every topic revised here.
How to use this revision.
  • If everything below feels familiar, skim it once and move on.
  • If something feels new, stop and revisit the corresponding chapter of your Class XI book — the full explanation, worked programs and Indian-context examples are all there.
  • Every one of the fourteen Class XI chapters has at least one sub-heading here; nothing in the syllabus has been dropped.
§1 · Introduction to Problem Solving

1.1 The Five Steps of Problem Solving

Every programming task follows the same five-step workflow:

  1. Analyse — understand the problem (inputs, outputs, constraints).
  2. Design — develop an algorithm on paper.
  3. Code — translate the algorithm into Python syntax.
  4. Test — run on sample inputs and compare with expected output.
  5. Debug — locate and fix errors, then retest.

1.1.1 Step 1 — Analysing the Problem

Identify Input, Output and Processing before writing any code.

1.1.2 Step 2 — Developing an Algorithm

Write language-independent steps in plain English.

1.1.3 Step 3 — Coding

Translate the algorithm into Python.

1.1.4 Step 4 — Testing

Run the program on known inputs and check the output.

1.1.5 Step 5 — Debugging

Find logical mistakes revealed during testing and fix them.

1.2 What is an Algorithm?

An algorithm is a finite, ordered sequence of unambiguous steps that solves a problem.

1.2.1 Characteristics of a Good Algorithm

1.3 Representing an Algorithm — Flowcharts

1.3.1 Standard Flowchart Symbols

SymbolNameUse
OvalTerminalStart / Stop
ParallelogramI/OInput or output
RectangleProcessAny calculation / assignment
DiamondDecisionYes / No branching
ArrowFlow lineDirection of control
CircleConnectorJoins two parts of the chart

1.3.2 Flowchart — With a Decision

A diamond splits the flow; each branch ends back on the main line (or at Stop).

1.4 Representing an Algorithm — Pseudocode

1.4.1 Pseudocode Conventions

Use keywords like INPUT, OUTPUT, IF … THEN … ELSE, WHILE, FOR, END IF. Indent the body of every block.

1.4.2 Flowchart vs. Pseudocode — When to use Which

FlowchartPseudocode
StyleVisual / graphicalText / English-like
Best forSmall algorithms, decisions, teaching beginnersLarger algorithms — translates easily to code
SpaceTakes more areaCompact

1.5 Decomposition

Decomposition means breaking a big problem into smaller, independent sub-problems that can be solved one at a time.

1.5.1 Example — Build a Student Report-Card Program

Split into: (a) read marks, (b) compute total & percentage, (c) assign grade, (d) print report.

1.5.2 Benefits of Decomposition

§2 · Getting Started with Python

2.1 Introduction to Python

Python is a high-level, interpreted, dynamically-typed, object-oriented, general-purpose programming language created by Guido van Rossum in 1991.

2.2 Features of Python

2.3 Your First Program — “Hello, World!”

print("Hello, World!")

2.4 Execution Modes — Interactive vs. Script

2.4.1 Comparison

Interactive modeScript mode
How to startType python in terminal / open IDLE shellSave code in .py file; run with python file.py
Prompt>>>No prompt — runs top-to-bottom
Best forQuick experiments / testing one lineReal programs that must be re-run
Saved?No — lost when shell closesYes — file is permanent

2.5 Python Character Set

Python understands: letters (A–Z, a–z), digits (0–9), special symbols (+ - * / % = < > ( ) [ ] { } , . : ; ' " # @ _ &), whitespace and almost the whole Unicode range (so Hindi, emoji etc. are valid inside strings and comments).

2.6 Python Tokens

A token is the smallest individual unit of a Python program. Five kinds:

2.6.1 Keywords

Reserved words with a fixed meaning — 35 in Python 3 (e.g. if, else, for, while, def, return, True, False, None, and, or, not, in, is, import, from, as, class, try, except, finally, raise, pass, break, continue, lambda, global, nonlocal, with, yield, del, assert, async, await, elif).

2.6.2 Identifiers

Names given to variables, functions, classes, modules.

Rules — start with a letter or _, then letters / digits / _; case-sensitive; keywords not allowed; no spaces or special symbols.

2.6.3 Literals

KindExamples
Numeric10, 3.14, 2+3j
String"Hi", 'a', """doc"""
BooleanTrue, False
SpecialNone
Collection[1,2], (1,2), {1,2}, {'a':1}

2.6.4 Operators

Symbols that act on operands (+ - * / % == != and or not etc.) — covered in §4.

2.6.5 Punctuators

Symbols that organise a statement: , . : ; ( ) [ ] { } ' " # and so on.

2.7 Variables

A variable is a name attached to a value in memory. Created by assignment — no separate declaration.

age = 17 name = "Asha"

2.7.1 How an assignment works — the Box Model

Python creates an object in memory and makes the variable point to it. Reassignment makes the same name point to a new object; the old one is garbage-collected when nothing references it.

2.8 L-Value and R-Value

An L-value (left of =) must be something that can hold a value (a variable). An R-value (right of =) can be any expression that produces a value. So x = 5 is legal but 5 = x is not.

2.9 Comments

2.9.1 Single-line comments (#)

# this is a comment x = 10 # inline comment

2.9.2 Multi-line “comments” (triple-quoted strings)

"""This string is not assigned to any variable, so Python evaluates and discards it — effectively acting as a multi-line comment."""

2.9.3 Why write comments?

§3 · Python Data Types

3.1 The Built-in Data Type Tree

CategoryTypeExample
Numericint, float, complex, bool10, 3.14, 2+3j, True
Sequencestr, list, tuple"hi", [1,2], (1,2)
Mappingdict{'a':1}
Setset, frozenset{1,2,3}
NoneNoneTypeNone

3.2 Using type() to Inspect a Value

type(10) # <class 'int'> type(3.14) # <class 'float'> type("hi") # <class 'str'> type([1,2]) # <class 'list'>

3.3 Numeric Types — Numbers

3.3.1 Integer — int

Whole numbers of unlimited size: 0, -17, 2**1000. Literals may be written as 0b… (binary), 0o… (octal) or 0x… (hex).

3.3.2 Floating-point — float

Numbers with a fractional part: 3.14, -0.5, 2.5e3 (= 2500.0).

3.3.3 Complex — complex

Two floats combined as a + bj: 2 + 3j. Access real/imag via .real and .imag.

3.3.4 Quick comparison

TypeTypical sizeExample
intArbitrary precision100
float~15 decimal digits3.14
complexTwo floats1+2j

3.4 Boolean — bool

True and False are the only two Boolean values. Internally True == 1 and False == 0.

3.5 Sequence Types

3.5.1 String — str

Immutable ordered sequence of Unicode characters: "Python".

3.5.2 List

Mutable ordered sequence of any items: [1, 2, "a", 3.0].

3.5.3 Tuple

Immutable ordered sequence: (1, 2, 3).

3.5.4 String vs List vs Tuple — at a glance

SyntaxMutable?Hashable?
str"abc"NoYes
list[1,2,3]YesNo
tuple(1,2,3)NoYes

3.6 Mapping — dict (Dictionary)

Unordered (insertion-ordered since Python 3.7) collection of key : value pairs. Keys must be unique and hashable.

marks = {"Asha": 85, "Rahul": 78} marks["Asha"] # 85

3.7 The None Type

None is the single value of type NoneType, used to signal “no value”. Common as the default return of a function that only does side-effects.

3.8 Mutable vs. Immutable Data Types

3.8.1 Classification

MutableImmutable
list, dict, set, bytearrayint, float, complex, bool, str, tuple, frozenset, None, bytes

3.8.2 Seeing it in action with id()

x = 5 print(id(x)) x = x + 1 # new object — id changes a = [1, 2] print(id(a)) a.append(3) # same object — id unchanged

3.8.3 Visualising the difference

Reassigning an immutable value creates a new object and rebinds the name. Modifying a mutable value edits the existing object — every name that pointed to it now sees the change.

3.8.4 Why does the distinction matter?

§4 · Python Operators

4.1 The Seven Families of Operators

  1. Arithmetic
  2. Relational / Comparison
  3. Logical
  4. Assignment (simple & augmented)
  5. Identity
  6. Membership
  7. Bitwise (for advanced reading)

4.2 Arithmetic Operators

OpMeaningExample (a=7,b=2)
+Addition9
-Subtraction5
*Multiplication14
/True division (float)3.5
//Floor / integer division3
%Modulus (remainder)1
**Exponent49

4.3 Relational (Comparison) Operators

==, !=, <, >, <=, >= — all return a Boolean.

4.4 Logical Operators

and, or, not. Short-circuit: and stops at the first False, or stops at the first True.

4.5 Assignment Operator — =

Binds the value on the right to the name on the left. Multiple assignment is allowed: a = b = c = 0, and tuple unpacking: x, y = 1, 2.

4.6 Augmented Assignment Operators

+= -= *= /= //= %= **= — shorthand combining an operation with assignment. x += 1 is equivalent to x = x + 1.

4.7 Identity Operators — is & is not

Compare object identity (same memory address, checked with id()), not just equality.

a = [1, 2]; b = [1, 2] a == b # True (values equal) a is b # False (different objects)

4.8 Membership Operators — in & not in

"a" in "apple" # True 5 not in [1, 2, 3] # True "name" in {"name":"Ria"} # True (checks keys)

4.9 The Whole Menu — One-page Cheat Sheet

FamilyOperators
Arithmetic+ - * / // % **
Relational== != < > <= >=
Logicaland or not
Assignment= += -= *= /= //= %= **=
Identityis is not
Membershipin not in

4.9.1 Operator Precedence (preview)

Highest → Lowest: ** · unary + - ~ · * / // % · + - · comparisons · not · and · or.

§5 · Expressions, Statements, Type Conversion & I/O

5.1 Expression vs. Statement

ExpressionStatement
Produces a valuePerforms an action
Can stand on the right of =Cannot
3 + 4 , len(s)x = 3 + 4 , print(x) , if c:

5.2 Precedence of Operators — Full Table

Follows the order of §4.9.1. Use parentheses whenever the intent is not obvious from the expression.

5.2.1 Associativity

Most operators are left-associative (a - b - c == (a - b) - c). Exponent ** is right-associative (2**3**2 == 2**(3**2) == 512).

5.3 Evaluating an Expression — Step by Step

Apply the highest-precedence operator first, then work outward, respecting associativity.

5.4 Type Conversion

5.4.1 Implicit Conversion (Type Coercion)

Python automatically widens a narrower type to a wider one: int + float → float, int + bool → int.

5.4.2 Explicit Conversion (Type Casting)

Use built-in functions: int(), float(), str(), bool(), list(), tuple(), set(), dict().

int("42") # 42 float("3.14") # 3.14 str(100) # "100" list("abc") # ['a','b','c']

5.5 Input from the Console — input()

name = input("Your name: ") # always a string

5.5.1 Always a string — remember to convert

age = int(input("Age: ")) # int cgpa = float(input("CGPA: ")) # float

5.5.2 Reading several numbers on one line

a, b = map(int, input("Enter two ints: ").split())

5.6 Output to the Console — print()

5.6.1 Multiple arguments

print("Hello", "World") # separated by space

5.6.2 The sep and end parameters

print("A", "B", sep="-") # A-B print("line1", end=" | ") print("line2") # line1 | line2

5.6.3 Formatted Output — f-strings

name, marks = "Asha", 87 print(f"{name} scored {marks}/100") # Asha scored 87/100 pi = 3.14159 print(f"{pi:.2f}") # 3.14

5.7 A Tiny Interactive Program

length = float(input("Length: ")) breadth = float(input("Breadth: ")) print(f"Area = {length * breadth}")
§6 · Errors in Python

6.1 The Three Kinds of Errors

KindWhen detectedExample
Syntax errorBefore runningprin("hi")
Run-time error (exception)During execution1/0 → ZeroDivisionError
Logical errorProgram runs, gives wrong resultarea = l + b (should be *)

6.2 Syntax Errors

6.2.1 What Python shows you

A SyntaxError message with the offending line and a caret (^) pointing to the problem position.

6.2.2 Common syntax mistakes

6.2.3 Indentation errors — a special case

IndentationError is raised when the indentation is wrong for the current block.

6.3 Run-time Errors (Exceptions)

6.3.1 Common built-in exceptions

ExceptionTriggered when…
ZeroDivisionErrordivide / mod by zero
ValueErrorright type, wrong value — int("abc")
TypeErrorwrong type — "x" + 2
NameErrorvariable not defined
IndexErrorlist index out of range
KeyErrormissing dictionary key
FileNotFoundErrorfile doesn’t exist

6.3.2 Reading a traceback

Read bottom-up: the last line names the exception; the lines above trace the call-chain that led to it.

6.3.3 How to prevent run-time errors

Validate input before using it, check for zero, check that a key / index exists, and wrap risky code in try … except (covered in Ch 3 of this class).

6.4 Logical Errors

6.4.1 A classic example

Calculating average without dividing by count, or using + where * was intended.

6.4.2 Common logical-error patterns

6.4.3 How to hunt logical errors — debugging

Add print() traces, step through with a debugger, or write small test cases with known answers.

6.5 Side-by-side Comparison

FeatureSyntaxRun-timeLogical
When caughtBefore runDuring runNever — runs to end
Python stops?YesYes (unless handled)No
Hardest to findEasyMediumHard
§7 · Flow of Control — Introduction

7.1 The Three Patterns of Flow

  1. Sequential — top-to-bottom execution.
  2. Conditional — choose one path over another based on a condition.
  3. Iterative — repeat a block until a condition is satisfied.

7.2 Indentation — How Python Groups Statements

7.2.1 The rules

7.2.2 Common indentation mistakes

7.3 Sequential Flow

Default. Each statement runs once, in order.

7.4 Conditional Flow

Select one of several branches depending on a Boolean test — if, if-else, if-elif-else (detailed in §8).

7.5 Iterative Flow

Repeat a block while (or as long as) a condition holds — while or for (detailed in §9).

7.6 Putting It Together

Real programs mix all three — sequential initialisation, a loop, and conditional decisions inside the loop.

7.7 Comparison at a Glance

PatternKeyword(s)Runs a block
SequentialOnce, in order
Conditionalif / elif / elseZero or one time
Iterativefor / whileZero or many times
§8 · Conditional Statements

8.1 The if Statement (single branch)

if marks >= 33: print("Pass")

8.2 The if-else Statement (two branches)

if marks >= 33: print("Pass") else: print("Fail")

8.3 The if-elif-else Statement (multi-branch)

if m >= 90: grade = "A1" elif m >= 80: grade = "A2" elif m >= 70: grade = "B1" elif m >= 60: grade = "B2" else: grade = "C"

8.4 Nested if — an if inside another

if age >= 18: if has_licence: print("May drive") else: print("Apply for licence")

8.5 Conditional Expression (one-line if-else)

status = "Pass" if marks >= 33 else "Fail"

8.6 CBSE Worked Programs

8.6.1 Program 1 — Absolute Value of a Number

n = int(input("Number: ")) print(-n if n < 0 else n)

8.6.2 Program 2 — Sort Three Numbers in Ascending Order

a, b, c = map(int, input("Three ints: ").split()) small = a if a<b and a<c else (b if b<c else c) large = a if a>b and a>c else (b if b>c else c) middle = a+b+c - small - large print(small, middle, large)

8.6.3 Program 3 — Divisibility of a Number

n = int(input("n: ")) d = int(input("d: ")) print("Divisible" if n % d == 0 else "Not divisible")

8.6.4 Bonus — FizzBuzz (divisibility classic)

for i in range(1, 16): if i % 15 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i)

8.7 Compact Summary of the Three Forms

FormBranchesUse when…
if1Only act if a condition is true
if-else2Exactly two mutually exclusive actions
if-elif-else3+Many mutually exclusive cases
§9 · Iterative Statements (Loops)

9.1 The for Loop

Iterates over any iterable (string, list, tuple, range, dict, file…).

for ch in "CBSE": print(ch)

9.1.1 The range() function

range(start, stop, step) produces integers from start up to but not including stop, stepping by step. start defaults to 0, step to 1. All three must be integers; step may be negative.

list(range(5)) # [0,1,2,3,4] list(range(2, 8)) # [2,3,4,5,6,7] list(range(1, 10, 2)) # [1,3,5,7,9] list(range(10, 0, -1)) # [10,9,…,1]

9.1.2 Looping over a sequence directly

for mark in [85, 78, 92]: print(mark)

9.1.3 Flowchart of a for loop

Start → take next item → if exhausted, go to else / after-loop; otherwise run the body and loop back.

9.2 The while Loop

Repeats while a condition is true.

n = int(input("n: ")) fact = 1 while n > 1: fact *= n n -= 1 print(fact)

9.2.1 Flowchart of a while loop

Start → evaluate condition → if false, exit; if true, run body and go back to the condition.

9.3 forwhile — Conversion

Any for loop can be written as a while loop, and vice versa. Use for when you know how many times; while when you loop until a condition becomes false.

# for i in range(1, 6): print(i) i = 1 while i < 6: print(i) i += 1

9.4 break and continue

9.4.1 break — exit the loop early

for n in nums: if n == target: print("Found") break

9.4.2 continue — skip to the next iteration

for n in nums: if n % 2 == 0: continue print(n) # only odd numbers

9.4.3 The else clause of a loop

The loop’s else runs only if the loop finished without encountering break. Perfect for search loops where else = “not found”.

for n in nums: if n == target: print("Hit"); break else: print("Miss")

9.5 Nested Loops

A loop inside another loop — common for tables, matrices and pattern programs.

for i in range(1, 4): for j in range(1, 4): print(i*j, end=" ") print()

9.6 CBSE Suggested Programs

9.6.1 Pattern programs

n = 5 for i in range(1, n+1): print("*" * i)

9.6.2 Summation of a series

# 1 + 1/2 + 1/3 + … + 1/n n = int(input()) s = 0 for i in range(1, n+1): s += 1/i print(s)

9.6.3 Factorial of a positive number

n = int(input()) fact = 1 for i in range(2, n+1): fact *= i print(fact)

9.6.4 Bonus — Fibonacci series

a, b = 0, 1 for _ in range(10): print(a, end=" ") a, b = b, a+b

9.6.5 Bonus — Prime check

n = int(input()) is_prime = n > 1 for d in range(2, int(n**0.5)+1): if n % d == 0: is_prime = False break print("Prime" if is_prime else "Not prime")

9.7 A Loop Cheat Sheet

forwhile
Best forFixed count / iterating over a collectionUnknown count — loop until condition
Guarantees terminationYes (iterable is finite)Only if the body changes the condition
Needs counter?No (supplied by range() or iterable)Usually yes — you maintain it
§10 · Strings

10.1 Creating a String

Single, double or triple quotes — all equivalent. Triple-quoted strings can span multiple lines.

a = 'CBSE' b = "Python" c = """line 1 line 2"""

10.1.1 Escape characters

EscapeMeaning
\nNewline
\tTab
\\Backslash
\'Single quote
\"Double quote
\rCarriage return

10.2 Basic Operations

10.2.1 Concatenation +

"Hello, " + "World" # "Hello, World"

10.2.2 Repetition *

"ab" * 3 # "ababab"

10.2.3 Membership in / not in

"Py" in "Python" # True

10.2.4 Length — len()

len("hello") # 5

10.3 Indexing

Positive indices start at 0, negative indices count from the end.

s = "CBSE" s[0] # 'C' s[-1] # 'E'

10.4 Slicing [start:stop:step]

s = "Python" s[0:3] # "Pyt" s[::2] # "Pto" s[::-1] # "nohtyP" (reversed)

10.5 Strings Are Immutable

Cannot modify a character in-place. Re-create the string instead.

s = "cat" # s[0] = 'b' # TypeError s = "b" + s[1:] # "bat"

10.6 Traversing a String

for ch in "CBSE": print(ch)

10.7 String Methods — Overview

Every method returns a new string; the original is unchanged.

10.8 Case-conversion methods

s = "Hello World" s.upper() # "HELLO WORLD" s.lower() # "hello world" s.title() # "Hello World" s.swapcase() # "hELLO wORLD" s.capitalize() # "Hello world"

10.9 Search-and-count methods

MethodDoes what
s.find(sub)Index of first match, -1 if absent
s.index(sub)Same as find but raises ValueError if absent
s.count(sub)Number of non-overlapping occurrences
s.startswith(p)True if s begins with p
s.endswith(p)True if s ends with p

10.10 Classification methods — is…()

All return a Boolean. Return True only for non-empty strings that match the rule.

MethodTrue when every character is…
isalpha()A letter
isdigit()A digit 0–9
isalnum()Letter or digit
isspace()Whitespace
isupper() / islower()Upper / lower-case
istitle()Title-cased

10.11 Trimming and replacing

" hi ".strip() # "hi" " hi ".lstrip() # "hi " " hi ".rstrip() # " hi" "cat cat".replace("cat", "dog") # "dog dog"

10.12 Splitting and joining

"a,b,c".split(",") # ['a','b','c'] "apple banana".split() # ['apple','banana'] "-".join(['2026','04','23']) # "2026-04-23"

10.13 Beyond the Syllabus — Other Useful str Methods

10.13.1 More string methods

10.13.2 Built-in FUNCTIONS that work with strings

len(), max(), min(), sorted(), reversed(), ord(), chr().

10.14 Worked Programs

10.14.1 Count vowels in a string

s = input().lower() print(sum(1 for ch in s if ch in "aeiou"))

10.14.2 Palindrome check

s = input().lower() print("Palindrome" if s == s[::-1] else "Not")

10.14.3 Count upper-case, lower-case, digits, spaces

u = l = d = sp = 0 for ch in input(): if ch.isupper(): u += 1 elif ch.islower(): l += 1 elif ch.isdigit(): d += 1 elif ch.isspace(): sp += 1 print(u, l, d, sp)

10.14.4 Convert case (every letter)

print(input().swapcase())
§11 · Lists

11.1 Creating a List

empty = [] nums = [1, 2, 3] mix = [1, "hi", 3.14, [4, 5]] from_str = list("abc") # ['a','b','c']

11.2 Indexing — Accessing an Element

nums = [10, 20, 30] nums[0] # 10 nums[-1] # 30

11.3 List Operations

11.3.1 Concatenation +

[1,2] + [3,4] # [1,2,3,4]

11.3.2 Repetition *

[0] * 5 # [0,0,0,0,0]

11.3.3 Membership in / not in

3 in [1,2,3] # True

11.3.4 Slicing [start:stop:step]

a = [10,20,30,40,50] a[1:4] # [20,30,40] a[::-1] # [50,40,30,20,10]

11.3.5 Length — len()

len([1,2,3]) # 3

11.4 Lists Are Mutable

a = [1,2,3] a[0] = 99 # a == [99,2,3] a[1:3] = [8,9] # slice assignment

11.5 Traversing a List

for item in nums: print(item)

11.6 Built-in FUNCTIONS that work on Lists

FunctionDoes
len(a)Number of elements
max(a) / min(a)Largest / smallest
sum(a)Sum of numeric elements
sorted(a)New sorted list
reversed(a)Reverse iterator
any(a) / all(a)Any/all truthy

11.7 Built-in METHODS on Lists

11.7.1 Adding items — append, extend, insert

a = [1,2] a.append(3) # [1,2,3] a.extend([4,5]) # [1,2,3,4,5] a.insert(0, 0) # [0,1,2,3,4,5]

11.7.2 Removing items — remove, pop, clear

a.remove(3) # removes the first 3 a.pop() # removes & returns last a.pop(0) # removes at index 0 a.clear() # []

11.7.3 Querying items — count and index

a = [1,2,2,3] a.count(2) # 2 a.index(3) # 3

11.7.4 Ordering — sort, reverse, sorted

a = [3,1,2] a.sort() # in-place → [1,2,3] a.sort(reverse=True) a.reverse() # in-place reverse b = sorted(a) # returns NEW list

11.7.5 Other handy methods — copy

b = a.copy() # shallow copy

11.7.6 One-page cheat sheet

MethodPurpose
append(x)Add one item at end
extend(iter)Add each item from iterable
insert(i,x)Insert at index i
remove(x)Delete first x
pop([i])Remove & return (last by default)
clear()Delete all items
count(x)Count occurrences
index(x)Index of first x
sort()In-place sort
reverse()In-place reverse
copy()Shallow copy

11.8 Nested Lists

matrix = [[1,2,3], [4,5,6], [7,8,9]] matrix[1][2] # 6 for row in matrix: for v in row: print(v, end=" ") print()

11.9 Worked Programs

11.9.1 Maximum, Minimum, Mean of a list

nums = [23, 45, 12, 78, 56] print(max(nums), min(nums), sum(nums)/len(nums))

11.9.2 Linear search

def search(a, key): for i, v in enumerate(a): if v == key: return i return -1

11.9.3 Frequency of each element

from collections import Counter a = [1,2,2,3,3,3,4] print(Counter(a)) # {3:3, 2:2, 1:1, 4:1}

11.9.4 Bonus — Swap even-position and odd-position elements

a = [10,20,30,40,50,60] for i in range(0, len(a)-1, 2): a[i], a[i+1] = a[i+1], a[i] print(a) # [20,10,40,30,60,50]

11.10 List vs String — Side-by-Side

ListString
Mutable?YesNo
ElementsAny type, mixedCharacters only
Concat / RepeatYesYes
SlicingYesYes
Methodsappend, sort, …upper, find, …
§12 · Tuples

12.1 Creating a Tuple

empty = () one = (5,) # note the trailing comma many = (1, 2, 3) no_parens = 4, 5, 6 # also a tuple from_list = tuple([1,2,3])

12.2 Indexing

t = (10, 20, 30) t[0] # 10 t[-1] # 30

12.3 Tuple Operations

12.3.1 Concatenation +

(1,2) + (3,4) # (1,2,3,4)

12.3.2 Repetition *

(0,) * 4 # (0,0,0,0)

12.3.3 Membership in / not in

2 in (1,2,3) # True

12.3.4 Slicing [start:stop:step]

t = (1,2,3,4,5) t[1:4] # (2,3,4) t[::-1] # (5,4,3,2,1)

12.3.5 Length — len()

len((1,2,3)) # 3

12.4 Tuples Are Immutable

No assignment to an index, no append, no sort. You can only build a new tuple from pieces of old ones.

12.5 Tuple Assignment (Unpacking)

x, y = 10, 20 # x=10, y=20 x, y = y, x # classic swap a, *rest = (1,2,3,4) # a=1, rest=[2,3,4]

12.6 Nested Tuples

point = ((1,2), (3,4)) point[1][0] # 3

12.7 Built-in Functions and Methods

12.7.1 Built-in FUNCTIONS (called as fn(t))

len, max, min, sum, sorted, tuple().

12.7.2 Tuple METHODS — only two!

MethodDoes
t.count(x)Number of times x appears
t.index(x)Index of the first x

12.8 Worked Programs

12.8.1 Maximum, Minimum, Mean of a tuple

t = (23, 45, 12, 78, 56) print(max(t), min(t), sum(t)/len(t))

12.8.2 Linear search on a tuple

def search(t, key): for i, v in enumerate(t): if v == key: return i return -1

12.8.3 Frequency of each element

t = (1,1,2,3,3,3) freq = {} for v in t: freq[v] = freq.get(v, 0) + 1 print(freq)

12.9 List vs Tuple — Side-by-Side

ListTuple
Syntax[1,2,3](1,2,3)
Mutable?YesNo
Methods11 (append, pop, …)2 (count, index)
SpeedSlowerFaster (small) — safe to share
Dict key / set item?NoYes
§13 · Dictionaries

13.1 Creating a Dictionary

empty = {} student = {"name": "Asha", "cls": 12, "marks": 87} d2 = dict(name="Rahul", cls=12) d3 = dict([("a", 1), ("b", 2)])

13.2 Accessing an Item

student["name"] # "Asha" student["missing"] # KeyError

13.2.1 Safe access — get(key, default)

student.get("email") # None (no KeyError) student.get("email", "N/A") # "N/A"

13.2.2 Test for a key — in

"name" in student # True (keys are checked, not values)

13.3 Dictionaries Are Mutable

student["cls"] = 12 # update student["subject"] = "CS" # add del student["subject"] # remove

13.4 Traversing a Dictionary

for k in student: # keys by default print(k, "=", student[k]) for k, v in student.items(): # pair at a time print(k, v)

13.5 Built-in FUNCTIONS that work on Dicts

len(d), max(d) / min(d) (on keys), sum(d.values()), sorted(d), dict().

13.6 Dictionary METHODS

13.6.1 The “view” methods — keys(), values(), items()

student.keys() # dict_keys(['name','cls','marks']) student.values() # dict_values(['Asha', 12, 87]) student.items() # dict_items([('name','Asha'), …])

13.6.2 Access & add — get, setdefault, update

student.get("age", 0) # default if absent student.setdefault("age", 17) # sets AND returns 17 student.update({"cls": 12, "house": "Blue"})

13.6.3 Remove — pop, popitem, clear, del

student.pop("house") # removes & returns "Blue" student.popitem() # removes & returns last (key, value) del student["cls"] student.clear() # empties it

13.6.4 Construct — fromkeys & copy

dict.fromkeys(['a','b','c'], 0) # {'a':0,'b':0,'c':0} d.copy() # shallow copy

13.6.5 Cheat sheet — every CBSE method & function at a glance

MethodPurpose
keys() / values() / items()View keys / values / pairs
get(k[,d])Safe read
setdefault(k,d)Read or insert-if-absent
update(other)Merge / overwrite
pop(k)Remove by key, return value
popitem()Remove last pair
clear()Empty the dict
fromkeys(seq, v)New dict from keys + default value
copy()Shallow copy

13.7 Worked Programs

13.7.1 Count the frequency of each character in a string

s = input() freq = {} for ch in s: freq[ch] = freq.get(ch, 0) + 1 print(freq)

13.7.2 Employee name → salary dictionary

emp = {} n = int(input("How many? ")) for _ in range(n): name = input("Name : ") sal = float(input("Salary: ")) emp[name] = sal print(emp)

13.7.3 Bonus — Words longer than a given length

def long_words(text, n): return [w for w in text.split() if len(w) > n] print(long_words("Data Structures are important", 4))

13.8 Comparing the Four Collections

ListTupleSetDict
Syntax[…](…){…}{k:v}
Ordered?YesYesNoInsertion-ordered
Indexable?YesYesNoBy key
Mutable?YesNoYesYes
Duplicates?YesYesNoKeys unique
§14 · Introduction to Python Modules

14.1 Four Ways to Import

import math # 1. full module import math as m # 2. with an alias from math import sqrt, pi # 3. selected names from math import * # 4. star import (discouraged)

14.1.1 Which form should I use?

14.1.2 Exploring a module

import math print(dir(math)) # list all names help(math.sqrt) # documentation

14.2 The math Module

14.2.1 Constants

math.pi ≈ 3.14159, math.e ≈ 2.71828, math.inf, math.nan.

14.2.2 Functions listed in the CBSE syllabus

FunctionUse
ceil(x)Smallest integer ≥ x
floor(x)Largest integer ≤ x
fabs(x)Absolute value (float)
sqrt(x)Square root
pow(x, y)x ** y (float)
exp(x)ex
log(x[, b])Natural log, or log base b
log10(x), log2(x)Common and binary log
sin, cos, tanTrig (radians)
degrees(r) / radians(d)Angle conversion
factorial(n)n!
gcd(a,b)Greatest common divisor

14.3 The random Module

FunctionReturns
random()Float in [0.0, 1.0)
randint(a, b)Int in [a, b] (both inclusive)
randrange(a, b[, s])Int like range()
uniform(a, b)Float in [a, b]
choice(seq)One random item
shuffle(lst)In-place random shuffle
sample(seq, k)k unique items
seed(n)Reproducible stream

14.3.1 A few useful bonus functions

14.4 The statistics Module

FunctionReturns
mean(data)Arithmetic mean
median(data)Middle value
median_low / median_highLower / upper of the middle pair
mode(data)Most frequent value
stdev(data)Sample standard deviation
variance(data)Sample variance

14.5 Putting It Together — Worked Programs

14.5.1 Marks-statistics report

import statistics as st marks = [78, 85, 63, 92, 74, 88, 71] print("Mean :", st.mean(marks)) print("Median :", st.median(marks)) print("Mode :", st.mode(marks)) print("Stdev :", round(st.stdev(marks), 2))

14.5.2 Guess-the-number game

import random target = random.randint(1, 100) while True: g = int(input("Guess: ")) if g < target: print("higher") elif g > target: print("lower") else: print("got it!"); break

14.5.3 Hypotenuse of a right triangle

import math a = float(input("a: ")) b = float(input("b: ")) print("c =", math.sqrt(a*a + b*b)) # or math.hypot(a, b)

14.5.4 Roll two dice 10 000 times — frequency of each total

import random from collections import Counter rolls = [random.randint(1,6) + random.randint(1,6) for _ in range(10000)] print(Counter(rolls))

14.6 Modules — One-page Summary

Quick-revision summary

  • Problem-solving workflow: analyse → design → code → test → debug; algorithms are shown as flowcharts or pseudocode.
  • Python is interpreted, dynamically-typed and object-oriented. Script files use .py.
  • Tokens: keywords, identifiers, literals, operators, punctuators.
  • Built-in types: int / float / complex / bool / str / list / tuple / dict / set / NoneType. Mutables: list, dict, set; the rest are immutable.
  • Seven operator families; exponent ** is right-associative.
  • I/O — input() always returns a string; use int() / float() to convert.
  • Three kinds of errors: syntax (before run), run-time / exception (during), logical (wrong result).
  • Flow — sequential, conditional (if/elif/else), iterative (for / while) with break, continue, loop else.
  • Strings are immutable; lists & dicts are mutable; tuples are immutable.
  • Standard library modules math, random, statistics are in the syllabus.
🧠Practice Quiz — test yourself on this chapter