1. Tokens and data types
A program is made of tokens: keywords (if, while, True), identifiers (names you choose: letters, digits and _ but not starting with a digit; case-sensitive), literals (25, 3.75, "Agra"), operators and punctuators.
Types: int, float, complex, bool, str, list, tuple, dict, None. Use type(x) to check.
Mutable (can change in place): list, dict. Immutable: numbers, bool, str, tuple.
t = (4, 6, 8)
t[0] = 5
raises TypeError: 'tuple' object does not support item assignment.
| Token | What it is | Examples |
|---|---|---|
| Keyword | Reserved word with a fixed meaning | if, for, while, True, None |
| Identifier | Name chosen by the programmer | total_fee, _count, marks2 |
| Literal | A fixed value written in the code | 25, 3.75, "Pune", True |
| Operator | Symbol that acts on values | +, //, **, ==, and, in |
| Punctuator | Symbol that organises code | ( ), [ ], { }, :, , |
| Type | Example | Mutable? |
|---|---|---|
int, float, complex | 42, 3.5, 2+3j | No |
bool | True, False | No |
str | "Kochi" | No |
tuple | (12, "B") | No |
list | [72, 85, 64] | Yes |
dict | {"pen": 10} | Yes |
NoneType | None | No |
Key terms
- Token
The smallest meaningful unit of a program: keyword, identifier, literal, operator or punctuator.
- Mutable
An object that can be changed in place after creation (list, dict).
- Immutable
An object that cannot be changed in place (int, float, str, tuple).
2. Operators and expressions
Arithmetic: / always gives a float; // floors towards minus infinity; % takes the sign of the divisor; ** is right-associative.
print(-17 // 5, -17 % 5)
print(2 ** 3 ** 2)
print(10 / 4, 10 // 4)
Output:
-4 3
512
2.5 2
Logical operators return one of their operands: 0 or 7 gives 7; not > and > or in priority. Identity (is) compares objects; equality (==) compares values. Conversion: int() truncates, str() makes text, float() makes a decimal.
| Priority | Operators | Note |
|---|---|---|
| 1 (highest) | ( ) | Brackets first |
| 2 | ** | Right to left: 2 ** 3 ** 2 is 2 ** 9 |
| 3 | unary - | -2 ** 2 is -(2 ** 2) |
| 4 | * / // % | Left to right |
| 5 | + - | Left to right |
| 6 | comparisons, in, is | Can be chained: 1 < x < 9 |
| 7 | not | |
| 8 | and | |
| 9 (lowest) | or |
| Category | Operators | Example and result |
|---|---|---|
| Arithmetic | + - * / // % ** | 17 // 5 gives 3; 17 % 5 gives 2 |
| Relational | == != < > <= >= | 4 == 4.0 gives True |
| Logical | not and or | not 0 gives True |
| Identity | is, is not | same object or not |
| Membership | in, not in | "a" in "chai" gives True |
| Assignment | = += -= *= //= | x += 3 means x = x + 3 |
| Code | Output | Why |
|---|---|---|
int("42") + int(3.9) | 45 | int() truncates 3.9 to 3 |
str(5) * 2 | 55 | string repetition |
bool("0") | True | non-empty string is truthy |
float(7) // 2 | 3.0 | float operand gives a float |
True + True | 2 | True counts as 1 |
Key terms
- Floor division
The // operator: divides and rounds down to the nearest whole number (towards minus infinity).
- Precedence
The order in which operators in an expression are applied.
- Short-circuit evaluation
and/or stop as soon as the result is known and return the operand that decided it.
3. Flow of control
Selection: if … elif … else — exactly one block runs. Iteration: for goes through a sequence; range(start, stop, step) stops before stop. while repeats while a condition is True; the body must update the variable.
Jumps: break leaves the innermost loop; continue skips to the next pass; a loop else runs only when there was no break; pass does nothing.
for n in [9, 15, 21]:
if n % 7 == 0:
print("found", n)
break
else:
print("none")
Output: found 21
| Call | Values produced |
|---|---|
range(5) | [0, 1, 2, 3, 4] |
range(2, 9, 3) | [2, 5, 8] |
range(10, 0, -4) | [10, 6, 2] |
range(3, 3) | [] |
| Statement | Effect | Example result |
|---|---|---|
break | Leaves the innermost loop at once | Diwa |
continue | Skips the rest of this pass, goes to the next | Dwl |
loop else | Runs only if the loop ended without break | no multiple of 5 |
pass | Does nothing (a placeholder) | — |
| Pass | Digit d = n % 10 | r after r * 10 + d | n after n //= 10 |
|---|---|---|---|
| 1 | 7 | 7 | 260 |
| 2 | 0 | 70 | 26 |
| 3 | 6 | 706 | 2 |
| 4 | 2 | 7062 | 0 |
Key terms
- Dry run
Tracing a program by hand, recording variable values after each step in a trace table.
- Infinite loop
A loop whose condition never becomes False, usually because the update is missing.
- Loop else
An else block after a loop that runs only if the loop ends without break.
4. Strings
A string is an immutable sequence of characters. Indexing: s[0] first, s[-1] last. Slicing: s[a:b:c] (a included, b excluded, step c); s[::-1] reverses.
Methods (all return new values): upper(), lower(), title(), capitalize(), count(), find() (−1 if absent), replace(), split(), join(), strip(), isalpha(), isdigit(), isalnum().
s = "chai"
s.upper()
print(s, s.upper())
Output: chai CHAI — the first call's result was thrown away.
Slice of s = "Monsoon Mela" | Result |
|---|---|
s[2:7] | 'nsoon' |
s[-4:] | 'Mela' |
s[::3] | 'Msne' |
s[::-1] | 'aleM noosnoM' |
s[:3] + s[-3:] | 'Monela' |
| Call (t = "a bus at nine") | Result |
|---|---|
t.upper() | 'A BUS AT NINE' |
t.title() | 'A Bus At Nine' |
t.count("a") | 2 |
t.find("bus") | 2 |
t.replace("bus", "train") | 'a train at nine' |
t.split() | ['a', 'bus', 'at', 'nine'] |
"-".join(["9", "30"]) | '9-30' |
" hi ".strip() | 'hi' |
"R2D2".isalnum() | True |
Key terms
- Slice
A part of a sequence taken with [start:stop:step]; start included, stop excluded.
- find()
Returns the index of the first occurrence of a substring, or −1 if it is not found.
5. Lists and tuples
Lists are mutable: append(), insert(), extend(), remove(), pop(), sort(), reverse(), index(), count(); slice assignment L[1:4] = [0] replaces a part.
Aliasing: M = L gives a second name for the same list; L[:] or L.copy() makes a new list.
L = [1, 2, 3]
M = L
N = L[:]
L.append(4)
print(M, N)
Output: [1, 2, 3, 4] [1, 2, 3]
Tuples are immutable: indexing, slicing, count(), index(), + and * make new tuples; one item needs a comma, (5,); unpacking: a, b = (1, 2).
| Statement | List afterwards |
|---|---|
L.append(1) | [5, 3, 8, 1] |
L.insert(0, 9) | [9, 5, 3, 8, 1] |
L.extend([2, 2]) | [9, 5, 3, 8, 1, 2, 2] |
L.remove(2) | [9, 5, 3, 8, 1, 2] |
L.pop() | [9, 5, 3, 8, 1] (popped 2) |
L.sort() | [1, 3, 5, 8, 9] |
| m (current mark) | top after the if |
|---|---|
| 72 | 72 |
| 85 | 85 |
| 64 | 85 |
| 91 | 91 |
| 58 | 91 |
Operation on t = (3, 8, 3, 1) | Result |
|---|---|
t[1] | 8 |
t[-1] | 1 |
t.count(3) | 2 |
t.index(8) | 1 |
t + (5,) | (3, 8, 3, 1, 5) |
len(t) | 4 |
Key terms
- Aliasing
Two or more names referring to the same mutable object, so a change through one is seen through all.
- Tuple unpacking
Assigning the items of a tuple to the same number of names in one statement.
6. Dictionaries
A dictionary holds key: value pairs; keys are unique and must be immutable (numbers, strings, tuples). d[k] = v adds or updates; d[k] on a missing key raises KeyError; d.get(k, default) does not. Methods: keys(), values(), items(), update(), pop(), len(); del d[k] removes a pair. A for loop over a dictionary goes through its keys in insertion order.
stock = {"rice": 40, "dal": 15}
stock.update({"oil": 8, "dal": 20})
print(stock)
Output: {'rice': 40, 'dal': 20, 'oil': 8}
| Statement | Result |
|---|---|
d["pad"] = 40 | {'ink': 12, 'pen': 25, 'pad': 40} |
d["ink"] = 15 | {'ink': 15, 'pen': 25, 'pad': 40} |
d.get("ruler", 0) | 0 |
del d["pen"] | {'ink': 15, 'pad': 40} |
list(d.items()) | [('ink', 15), ('pad', 40)] |
| Word read | freq after the update |
|---|---|
| red | {'red': 1} |
| blue | {'red': 1, 'blue': 1} |
| red | {'red': 2, 'blue': 1} |
| green | {'red': 2, 'blue': 1, 'green': 1} |
| blue | {'red': 2, 'blue': 2, 'green': 1} |
| red | {'red': 3, 'blue': 2, 'green': 1} |
| Feature | list | tuple | dict |
|---|---|---|---|
| Brackets | [ ] | ( ) | {key: value} |
| Mutable? | Yes | No | Yes |
| Access by | index | index | key |
| Duplicates | allowed | allowed | keys unique |
| Can be a dict key? | No | Yes (if items immutable) | No |
Key terms
- Key
The unique, immutable label used to look up a value in a dictionary.
- KeyError
The error raised when a dictionary is indexed with a key it does not contain.
Exam tips
Common mistakes
- Writing
-17 // 5as -3: floor division rounds down, giving -4. - Working
2 ** 3 ** 2left to right: it is2 ** 9. - Thinking
s.upper()changes s, or thatM = Lcopies a list. - Forgetting that
range(1, 10)stops at 9. - Printing lists or dictionaries without the exact brackets, quotes and spaces Python uses.
- Missing
:afterif,for,while,def; using=in place of==.
How marks are usually awarded
- Output questions: marks for each correct line or value, as stated; the format must match.
- Error-finding: ½ or 1 mark for each error found and corrected.
- Programs: marks for input, correct logic, and the output; any correct method earns full marks.
- Theory (2–3 marks): one point per mark, with a short code example where it helps.