Python Chapter 2 — types, expressions and I/O
Priority key · Priorities guide emphasis; they do not remove taught scope.
Exam recall
Track both value and type.
/divides;//floors;%is consistent with floor division.input()returns text; range bounds and random bounds differ.
Types determine what expressions mean priority/high
| Python type | Meaning | Example |
|---|---|---|
int | Integer | 7 |
float | Floating-point approximation | 2.5 |
bool | Truth value | True |
str | Immutable text sequence | "007" |
input() returns a string. Convert with int() or float() when arithmetic is required; conversion can fail for unsuitable text. Keep identifiers as strings if leading zeroes or non-numeric characters matter. str() produces a textual representation, and type() inspects an object’s type.
Assignment binds a name to a value/object. = assigns; == compares. In total = total + value, evaluate the right side using the old total before assigning the new one. a, b = b, a evaluates the right-hand values before assigning, so it swaps them.
Operators and precedence priority/high
Two questions should accompany every trace: what is the value, and what is its type? The value printed as7 can result from an integer expression, whereas7.0 is a float and "7" is text. The next operation may behave differently for each.
+, -, *, /, //, %, ** perform arithmetic. / returns a floating-point quotient; // floors the quotient, so -7 // 3 is −3, not −2. % is the remainder consistent with a == (a // b) * b + a % b for integers and nonzero b. Thus -7 % 3 is 2. ** exponentiates; ^ is not exponentiation in Python. Python numeric-type reference.
Use parentheses to make intended grouping clear. Exponentiation binds more strongly than unary minus: -2**2 is −4, whereas (-2)**2 is 4. Multiplication/division precede addition/subtraction. Comparisons precede not, then and, then or. Short-circuit evaluation can guard unsafe work: len(values) > 0 and values[0] == 5 checks non-emptiness first.
String + concatenates and string * repeats: "3" + "4" is "34"; 3 + 4 is 7. Mixing a string and integer with + does not automatically convert either one. Floating-point values may approximate decimals; formatting a result does not change its underlying stored value.
Input and output priority/medium
def format_cost(quantity, unit_price):
cost = quantity * unit_price
return f"${cost:.2f}":.2f formats two decimal places. print(a, b) separates arguments with a space by default and ends with a newline; sep and end can change these. Match the exact output format when a question specifies it.
Formatting changes how a value is displayed; it does not turn the stored value into a more accurate calculation. For example, a minimum field width pads a short result but does not cut a long result to that width.
Identifiers may contain letters, digits and underscores, cannot start with a digit, and cannot be reserved keywords; names are case-sensitive. Escape sequences include \n for newline, \t for tab and \\ for a literal backslash. A format such as f"{value:8.2f}" uses a minimum width of eight characters and two decimal places; a longer result is not automatically truncated.
For taught library use: math.sqrt(x) computes a square root, math.floor(x) rounds down, math.ceil(x) rounds up, and math.pi supplies π. random.randint(a, b) includes both endpoints; random.randrange(a, b) excludes b; random.random() is in [0.0,1.0). Choose bounds before generating a grid: a random valid row of n rows is randint(0, n-1), not randint(0, n).
Worked example — original
Convert 3671 seconds into hours, remaining minutes and seconds:
def split_time(total_seconds):
hours = total_seconds // 3600
remainder = total_seconds % 3600 # Remove complete hours before finding minutes.
minutes = remainder // 60
seconds = remainder % 60
return hours, minutes, secondsThe result is (1, 1, 11). The second division uses the remainder after hours, not the original total, so minutes stay below 60. The input contract assumes a nonnegative integer.
Practice
Exam focus: types and expressions underpin the Python questions throughout the HCI promos. HCI 2024 Q8 asks for suitable attribute types; representation questions distinguish numeric values from strings. The supplied evidence supports this as foundational knowledge, not a separate prediction that every listed operator will be tested.
Trace method: apply parentheses/precedence → compute the value → record the type → perform assignment. Check bounds when a random function is involved: the last legal list index is one less than its length.
13A — original. Evaluate 17 // 5, 17 % 5, -7 // 3, -7 % 3, "4" * 3 and 2 + 3 * 4. State each result’s type.
13B — original. Write boxes_needed(items, capacity) returning the minimum number of boxes required. Inputs are integers, items ≥ 0 and capacity > 0. Do not use floating-point arithmetic. Test (0, 6), (12, 6) and (13, 6).
Hints
13B: whole boxes plus one extra box only when a remainder exists.
Revision checklist
- 13.1 Choose int, float, bool or str based on the meaning of a value.
- 13.2 Use valid identifiers, assignment and type conversion.
- 13.3 Predict arithmetic precedence, division, floor division, remainder and exponentiation.
- 13.4 Handle negative operands correctly where allowed.
- 13.5 Read input and recognise that input() initially returns a string.
- 13.6 Use escape sequences, concatenation and print parameters appropriately.
- 13.7 Format numeric precision and minimum field width accurately.
- 13.8 Import and use the taught math and random functions with correct argument bounds.
- 13.9 Predict value and type after each step in a short program.
Visual revision mindmap

Open this mindmap and its text version · All 21 mindmaps
Your mindmap framework
Centre: Python Chapter 2 — types, expressions and I/O. Build the six branches below. For each subbranch, add a short definition, a labelled sample and one exam trap from memory; then check the chapter.
flowchart LR C["13 • Revision map"] C --> B0["Types and values"] C --> B1["Names and assignment"] C --> B2["Operators"] C --> B3["Input and output"] C --> B4["Libraries and bounds"] C --> B5["Visual checks and mistakes"]
-
Types and values
- int, float, bool and str.
- Identifier versus arithmetic quantity.
- Literal value versus textual representation.
- Type conversion and possible failure.
-
Names and assignment
- Valid, case-sensitive identifiers.
- Right-hand expression evaluated first.
- Name binding and reassignment.
- Tuple unpacking; simultaneous swap.
-
Operators
- Arithmetic and precedence.
- Division versus floor division.
- Remainder consistent with quotient.
- Boolean operations and short-circuit guards.
-
Input and output
- input returns a string.
- print: separator and ending.
- Escapes: newline, tab and backslash.
- Format precision versus minimum field width.
-
Libraries and bounds
- Imports and qualified calls.
- sqrt, floor, ceil and pi.
- randint includes both endpoints.
- randrange excludes stop; random in [0, 1).
-
Visual checks and mistakes
- Expression → evaluation steps → value → type.
- Trace −7 // 3 and −7 % 3.
- Split seconds into hours, remaining minutes and seconds.
- Avoid: ^ means power; formatting increases accuracy; upper list index = length.
Close the notes and test the map: explain one branch aloud, sketch its sample, then answer a linked practice question. Mark any missing link to revisit.
Source trail
9569 §§1.2.1–1.2.2,1.3; school Getting Started with Python.
School Tutorial 2; arithmetic and random-generation portions of HCI 2022 Q9, 2023 Q8, 2024 Q9.
Source guide records provenance and original-paper locations.