Skip to content
Skip to page content
soylai.com

Python Revision Tour — Notes

6 sections 6 min readBeta

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.

Table of the five kinds of tokens: keywords such as if and while, identifiers such as total_fee, literals such as 25 and Pune, operators such as plus and floor division, and punctuators such as brackets, colon and comma
TokenWhat it isExamples
KeywordReserved word with a fixed meaningif, for, while, True, None
IdentifierName chosen by the programmertotal_fee, _count, marks2
LiteralA fixed value written in the code25, 3.75, "Pune", True
OperatorSymbol that acts on values+, //, **, ==, and, in
PunctuatorSymbol that organises code( ), [ ], { }, :, ,
Mutable = can be changed in place.
TypeExampleMutable?
int, float, complex42, 3.5, 2+3jNo
boolTrue, FalseNo
str"Kochi"No
tuple(12, "B")No
list[72, 85, 64]Yes
dict{"pen": 10}Yes
NoneTypeNoneNo

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.

Table of operator precedence from highest to lowest: brackets, exponent (right to left), unary minus, multiplication and division group, addition and subtraction, comparisons, not, and, or
PriorityOperatorsNote
1 (highest)( )Brackets first
2**Right to left: 2 ** 3 ** 2 is 2 ** 9
3unary --2 ** 2 is -(2 ** 2)
4* / // %Left to right
5+ -Left to right
6comparisons, in, isCan be chained: 1 < x < 9
7not
8and
9 (lowest)or
Table of operator categories: arithmetic, relational, logical, identity, membership and assignment, with an example of each; 17 floor-divided by 5 gives 3 and 17 mod 5 gives 2
CategoryOperatorsExample and result
Arithmetic+ - * / // % **17 // 5 gives 3; 17 % 5 gives 2
Relational== != < > <= >=4 == 4.0 gives True
Logicalnot and ornot 0 gives True
Identityis, is notsame object or not
Membershipin, not in"a" in "chai" gives True
Assignment= += -= *= //=x += 3 means x = x + 3
Table of type-conversion examples, each run in Python: int of the string 42 plus int of 3.9 gives 45; the string 5 repeated twice gives 55; bool of the string zero is True; float 7 floor-divided by 2 gives 3.0; True plus True gives 2
CodeOutputWhy
int("42") + int(3.9)45int() truncates 3.9 to 3
str(5) * 255string repetition
bool("0")Truenon-empty string is truthy
float(7) // 23.0float operand gives a float
True + True2True 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

Only one block of an if-elif-else ever runs.
The stop value is never included.
CallValues 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)[]
Forgetting the update makes an infinite loop.
Table of jump statements: break leaves the innermost loop, so looping over Diwali and breaking at l prints Diwa; continue skips vowels, printing Dwl; a loop else runs only when no break happens; pass does nothing
StatementEffectExample result
breakLeaves the innermost loop at onceDiwa
continueSkips the rest of this pass, goes to the nextDwl
loop elseRuns only if the loop ended without breakno multiple of 5
passDoes nothing (a placeholder)—
Dry run produced by running the loop in Python.
PassDigit d = n % 10r after r * 10 + dn after n //= 10
177260
207026
367062
4270620

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.

Positive indexes count from 0 at the left; negative ones from −1 at the right.
Start is included, stop is excluded; a negative step goes backwards.
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'
Methods return new values; the original string never changes.
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).

Starting list: L = [5, 3, 8].
StatementList 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]
Changing the list through one name is seen through the other.
Dry run produced by running the loop in Python.
m (current mark)top after the if
7272
8585
6485
9191
5891
A one-item tuple needs a comma: (5,).
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}

Starting dictionary: d = {"ink": 12, "pen": 25}.
StatementResult
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)]
Dry run produced by running the loop in Python.
Word readfreq 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}
Comparison table of list, tuple and dictionary: brackets, mutability, access by index or key, duplicates and whether each can be a dictionary key
Featurelisttupledict
Brackets[ ]( ){key: value}
Mutable?YesNoYes
Access byindexindexkey
Duplicatesallowedallowedkeys unique
Can be a dict key?NoYes (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 // 5 as -3: floor division rounds down, giving -4.
  • Working 2 ** 3 ** 2 left to right: it is 2 ** 9.
  • Thinking s.upper() changes s, or that M = L copies a list.
  • Forgetting that range(1, 10) stops at 9.
  • Printing lists or dictionaries without the exact brackets, quotes and spaces Python uses.
  • Missing : after if, 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.