- 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.1 The Five Steps of Problem Solving
Every programming task follows the same five-step workflow:
- Analyse — understand the problem (inputs, outputs, constraints).
- Design — develop an algorithm on paper.
- Code — translate the algorithm into Python syntax.
- Test — run on sample inputs and compare with expected output.
- 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
- Finiteness — it must terminate.
- Definiteness — every step is unambiguous.
- Input & Output — zero or more inputs, one or more outputs.
- Effectiveness — each step can be performed in finite time.
- Generality — it solves a class of problems, not just one instance.
1.3 Representing an Algorithm — Flowcharts
1.3.1 Standard Flowchart Symbols
| Symbol | Name | Use |
|---|---|---|
| Oval | Terminal | Start / Stop |
| Parallelogram | I/O | Input or output |
| Rectangle | Process | Any calculation / assignment |
| Diamond | Decision | Yes / No branching |
| Arrow | Flow line | Direction of control |
| Circle | Connector | Joins 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
| Flowchart | Pseudocode | |
|---|---|---|
| Style | Visual / graphical | Text / English-like |
| Best for | Small algorithms, decisions, teaching beginners | Larger algorithms — translates easily to code |
| Space | Takes more area | Compact |
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
- Each piece is easier to write and test.
- Team-members can work on different pieces.
- Reusable sub-programs become future library functions.
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
- Easy to learn, read and write
- Free & open-source
- Interpreted (no separate compile step)
- Cross-platform / portable
- Dynamically typed — type of a variable is decided at run-time
- Rich standard library (“batteries included”)
- Supports procedural, object-oriented and functional programming
- Extensible — can call C / C++ code
2.3 Your First Program — “Hello, World!”
2.4 Execution Modes — Interactive vs. Script
2.4.1 Comparison
| Interactive mode | Script mode | |
|---|---|---|
| How to start | Type python in terminal / open IDLE shell | Save code in .py file; run with python file.py |
| Prompt | >>> | No prompt — runs top-to-bottom |
| Best for | Quick experiments / testing one line | Real programs that must be re-run |
| Saved? | No — lost when shell closes | Yes — 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.
_, then letters / digits / _; case-sensitive; keywords not allowed; no spaces or special symbols.2.6.3 Literals
| Kind | Examples |
|---|---|
| Numeric | 10, 3.14, 2+3j |
| String | "Hi", 'a', """doc""" |
| Boolean | True, False |
| Special | None |
| 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.
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 (#)
2.9.2 Multi-line “comments” (triple-quoted strings)
2.9.3 Why write comments?
- Explain why the code does something (what it does should be obvious from the code).
- Leave a trail so someone reading it six months later understands the intent.
- Temporarily disable a line while debugging.
3.1 The Built-in Data Type Tree
| Category | Type | Example |
|---|---|---|
| Numeric | int, float, complex, bool | 10, 3.14, 2+3j, True |
| Sequence | str, list, tuple | "hi", [1,2], (1,2) |
| Mapping | dict | {'a':1} |
| Set | set, frozenset | {1,2,3} |
| None | NoneType | None |
3.2 Using type() to Inspect a Value
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
| Type | Typical size | Example |
|---|---|---|
| int | Arbitrary precision | 100 |
| float | ~15 decimal digits | 3.14 |
| complex | Two floats | 1+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
| Syntax | Mutable? | Hashable? | |
|---|---|---|---|
| str | "abc" | No | Yes |
| list | [1,2,3] | Yes | No |
| tuple | (1,2,3) | No | Yes |
3.6 Mapping — dict (Dictionary)
Unordered (insertion-ordered since Python 3.7) collection of key : value pairs. Keys must be unique and hashable.
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
| Mutable | Immutable |
|---|---|
| list, dict, set, bytearray | int, float, complex, bool, str, tuple, frozenset, None, bytes |
3.8.2 Seeing it in action with id()
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?
- Mutables cannot be dictionary keys or elements of a set.
- Passing a mutable into a function lets the function change it; immutables are safe.
- Two references to the same mutable share state — a frequent source of bugs.
4.1 The Seven Families of Operators
- Arithmetic
- Relational / Comparison
- Logical
- Assignment (simple & augmented)
- Identity
- Membership
- Bitwise (for advanced reading)
4.2 Arithmetic Operators
| Op | Meaning | Example (a=7,b=2) |
|---|---|---|
+ | Addition | 9 |
- | Subtraction | 5 |
* | Multiplication | 14 |
/ | True division (float) | 3.5 |
// | Floor / integer division | 3 |
% | Modulus (remainder) | 1 |
** | Exponent | 49 |
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.
4.8 Membership Operators — in & not in
4.9 The Whole Menu — One-page Cheat Sheet
| Family | Operators |
|---|---|
| Arithmetic | + - * / // % ** |
| Relational | == != < > <= >= |
| Logical | and or not |
| Assignment | = += -= *= /= //= %= **= |
| Identity | is is not |
| Membership | in not in |
4.9.1 Operator Precedence (preview)
Highest → Lowest: ** · unary + - ~ · * / // % · + - · comparisons · not · and · or.
5.1 Expression vs. Statement
| Expression | Statement |
|---|---|
| Produces a value | Performs 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().
5.5 Input from the Console — input()
5.5.1 Always a string — remember to convert
5.5.2 Reading several numbers on one line
5.6 Output to the Console — print()
5.6.1 Multiple arguments
5.6.2 The sep and end parameters
5.6.3 Formatted Output — f-strings
5.7 A Tiny Interactive Program
6.1 The Three Kinds of Errors
| Kind | When detected | Example |
|---|---|---|
| Syntax error | Before running | prin("hi") |
| Run-time error (exception) | During execution | 1/0 → ZeroDivisionError |
| Logical error | Program runs, gives wrong result | area = 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
- Missing colon after
if / while / for / def. - Unmatched quotes or brackets.
- Using
=instead of==in a condition.
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
| Exception | Triggered when… |
|---|---|
ZeroDivisionError | divide / mod by zero |
ValueError | right type, wrong value — int("abc") |
TypeError | wrong type — "x" + 2 |
NameError | variable not defined |
IndexError | list index out of range |
KeyError | missing dictionary key |
FileNotFoundError | file 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
- Off-by-one in loops.
- Wrong operator (
andvs.or). - Using the wrong variable name that happens to exist.
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
| Feature | Syntax | Run-time | Logical |
|---|---|---|---|
| When caught | Before run | During run | Never — runs to end |
| Python stops? | Yes | Yes (unless handled) | No |
| Hardest to find | Easy | Medium | Hard |
7.1 The Three Patterns of Flow
- Sequential — top-to-bottom execution.
- Conditional — choose one path over another based on a condition.
- Iterative — repeat a block until a condition is satisfied.
7.2 Indentation — How Python Groups Statements
7.2.1 The rules
- A block is a set of consecutive lines at the same indentation level.
- Python’s convention is 4 spaces per level — never mix tabs and spaces.
- The indent must match exactly within the block.
7.2.2 Common indentation mistakes
- Mixing tabs and spaces.
- Indenting the first statement after
ifinconsistently with the next. - Forgetting to indent after a
deforfor.
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
| Pattern | Keyword(s) | Runs a block |
|---|---|---|
| Sequential | — | Once, in order |
| Conditional | if / elif / else | Zero or one time |
| Iterative | for / while | Zero or many times |
8.1 The if Statement (single branch)
8.2 The if-else Statement (two branches)
8.3 The if-elif-else Statement (multi-branch)
8.4 Nested if — an if inside another
8.5 Conditional Expression (one-line if-else)
8.6 CBSE Worked Programs
8.6.1 Program 1 — Absolute Value of a Number
8.6.2 Program 2 — Sort Three Numbers in Ascending Order
8.6.3 Program 3 — Divisibility of a Number
8.6.4 Bonus — FizzBuzz (divisibility classic)
8.7 Compact Summary of the Three Forms
| Form | Branches | Use when… |
|---|---|---|
if | 1 | Only act if a condition is true |
if-else | 2 | Exactly two mutually exclusive actions |
if-elif-else | 3+ | Many mutually exclusive cases |
9.1 The for Loop
Iterates over any iterable (string, list, tuple, range, dict, file…).
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.
9.1.2 Looping over a sequence directly
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.
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 for ↔ while — 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.
9.4 break and continue
9.4.1 break — exit the loop early
9.4.2 continue — skip to the next iteration
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”.
9.5 Nested Loops
A loop inside another loop — common for tables, matrices and pattern programs.
9.6 CBSE Suggested Programs
9.6.1 Pattern programs
9.6.2 Summation of a series
9.6.3 Factorial of a positive number
9.6.4 Bonus — Fibonacci series
9.6.5 Bonus — Prime check
9.7 A Loop Cheat Sheet
for | while | |
|---|---|---|
| Best for | Fixed count / iterating over a collection | Unknown count — loop until condition |
| Guarantees termination | Yes (iterable is finite) | Only if the body changes the condition |
| Needs counter? | No (supplied by range() or iterable) | Usually yes — you maintain it |
10.1 Creating a String
Single, double or triple quotes — all equivalent. Triple-quoted strings can span multiple lines.
10.1.1 Escape characters
| Escape | Meaning |
|---|---|
\n | Newline |
\t | Tab |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
\r | Carriage return |
10.2 Basic Operations
10.2.1 Concatenation +
10.2.2 Repetition *
10.2.3 Membership in / not in
10.2.4 Length — len()
10.3 Indexing
Positive indices start at 0, negative indices count from the end.
10.4 Slicing [start:stop:step]
10.5 Strings Are Immutable
Cannot modify a character in-place. Re-create the string instead.
10.6 Traversing a String
10.7 String Methods — Overview
Every method returns a new string; the original is unchanged.
10.8 Case-conversion methods
10.9 Search-and-count methods
| Method | Does 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.
| Method | True 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
10.12 Splitting and joining
10.13 Beyond the Syllabus — Other Useful str Methods
10.13.1 More string methods
center(w),ljust(w),rjust(w)— padding.zfill(w)— zero-pad numeric strings.format(),f"…"— formatted output.
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
10.14.2 Palindrome check
10.14.3 Count upper-case, lower-case, digits, spaces
10.14.4 Convert case (every letter)
11.1 Creating a List
11.2 Indexing — Accessing an Element
11.3 List Operations
11.3.1 Concatenation +
11.3.2 Repetition *
11.3.3 Membership in / not in
11.3.4 Slicing [start:stop:step]
11.3.5 Length — len()
11.4 Lists Are Mutable
11.5 Traversing a List
11.6 Built-in FUNCTIONS that work on Lists
| Function | Does |
|---|---|
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
11.7.2 Removing items — remove, pop, clear
11.7.3 Querying items — count and index
11.7.4 Ordering — sort, reverse, sorted
11.7.5 Other handy methods — copy
11.7.6 One-page cheat sheet
| Method | Purpose |
|---|---|
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
11.9 Worked Programs
11.9.1 Maximum, Minimum, Mean of a list
11.9.2 Linear search
11.9.3 Frequency of each element
11.9.4 Bonus — Swap even-position and odd-position elements
11.10 List vs String — Side-by-Side
| List | String | |
|---|---|---|
| Mutable? | Yes | No |
| Elements | Any type, mixed | Characters only |
| Concat / Repeat | Yes | Yes |
| Slicing | Yes | Yes |
| Methods | append, sort, … | upper, find, … |
12.1 Creating a Tuple
12.2 Indexing
12.3 Tuple Operations
12.3.1 Concatenation +
12.3.2 Repetition *
12.3.3 Membership in / not in
12.3.4 Slicing [start:stop:step]
12.3.5 Length — len()
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)
12.6 Nested Tuples
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!
| Method | Does |
|---|---|
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
12.8.2 Linear search on a tuple
12.8.3 Frequency of each element
12.9 List vs Tuple — Side-by-Side
| List | Tuple | |
|---|---|---|
| Syntax | [1,2,3] | (1,2,3) |
| Mutable? | Yes | No |
| Methods | 11 (append, pop, …) | 2 (count, index) |
| Speed | Slower | Faster (small) — safe to share |
| Dict key / set item? | No | Yes |
13.1 Creating a Dictionary
13.2 Accessing an Item
13.2.1 Safe access — get(key, default)
13.2.2 Test for a key — in
13.3 Dictionaries Are Mutable
13.4 Traversing a Dictionary
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()
13.6.2 Access & add — get, setdefault, update
13.6.3 Remove — pop, popitem, clear, del
13.6.4 Construct — fromkeys & copy
13.6.5 Cheat sheet — every CBSE method & function at a glance
| Method | Purpose |
|---|---|
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
13.7.2 Employee name → salary dictionary
13.7.3 Bonus — Words longer than a given length
13.8 Comparing the Four Collections
| List | Tuple | Set | Dict | |
|---|---|---|---|---|
| Syntax | […] | (…) | {…} | {k:v} |
| Ordered? | Yes | Yes | No | Insertion-ordered |
| Indexable? | Yes | Yes | No | By key |
| Mutable? | Yes | No | Yes | Yes |
| Duplicates? | Yes | Yes | No | Keys unique |
14.1 Four Ways to Import
14.1.1 Which form should I use?
- Small script using many names from one module → plain
import module. - You use only a few names, frequently →
from module import a, b. - Never use
from module import *in production code — it pollutes the namespace.
14.1.2 Exploring a module
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
| Function | Use |
|---|---|
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, tan | Trig (radians) |
degrees(r) / radians(d) | Angle conversion |
factorial(n) | n! |
gcd(a,b) | Greatest common divisor |
14.3 The random Module
| Function | Returns |
|---|---|
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
random.choices(seq, k)— k items with replacement (& optional weights).random.gauss(mu, sigma)— normally-distributed float.
14.4 The statistics Module
| Function | Returns |
|---|---|
mean(data) | Arithmetic mean |
median(data) | Middle value |
median_low / median_high | Lower / 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
14.5.2 Guess-the-number game
14.5.3 Hypotenuse of a right triangle
14.5.4 Roll two dice 10 000 times — frequency of each total
14.6 Modules — One-page Summary
math— deterministic maths:sqrt,ceil,floor,log, trig, constants.random— pseudo-random numbers:random,randint,choice,shuffle.statistics— descriptive statistics on a sample:mean,median,mode,stdev,variance.
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; useint()/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) withbreak,continue, loopelse. - Strings are immutable; lists & dicts are mutable; tuples are immutable.
- Standard library modules
math,random,statisticsare in the syllabus.