Data Types and Collections

A program is only useful if it represents data correctly. A mark, a name, a password, a menu choice, and a truth value should not all be treated the same way. The data type determines what operations are valid and what mistakes are likely.

Values, Variables, and Assignment

A variable is a name that refers to a value.

student_name = "Aisha"
mark = 76
has_submitted = True

The assignment operator = stores a value under a name. It does not mean mathematical equality.

Caption: Assignment evaluates the expression on the right first, then stores the result under the name on the left.

mark = mark + 5

This means: take the current value of mark, add 5, then store the new value back into mark.

When tracing assignment, keep a small state table:

StatementValue of mark after statement
mark = 7676
mark = mark + 581

This habit is more reliable than trying to remember the values mentally.

Common Data Types

Conceptual typePython exampleNotes
integer12whole numbers, indices, counts
real12.5Python uses float for real-valued approximations
char"A"Python has no separate char type; use a one-character string
string"S1234567A"text; can contain digits that should not be calculated
BooleanTruecondition result or flag

Use type() when learning or debugging:

value = "45"
print(type(value))

This prints <class 'str'>, so arithmetic cannot be done safely until conversion.

Type Conversion

Python may convert values automatically in some mixed numeric expressions, but beginner code should usually make conversions explicit.

whole_number = int("42")
measurement = float("3.5")
label = str(108)

int() converts a suitable value to an integer, float() converts it to a real-valued approximation, and str() creates text. Conversion may fail when the source text is unsuitable, such as int("four").

Input Is a String

Python’s input() function always returns a string.

raw_age = input("Age: ")
age = int(raw_age)

If the user types 17, raw_age is "17", not 17. Convert only when the input is expected to behave like a number.

price = float(input("Price: "))
quantity = int(input("Quantity: "))
total = price * quantity
print(total)

Common bug:

age = input("Age: ")
print(age + 1)  # error: age is a string

Correct version:

age = int(input("Age: "))
print(age + 1)

Operators

Arithmetic operators include:

OperatorMeaningExample
+addition2 + 3 gives 5
-subtraction7 - 3 gives 4
*multiplication2 * 3 gives 6
/real division20 / 8 gives 2.5
//integer division20 // 8 gives 2
%remainder20 % 8 gives 4
**exponentiation2 ** 3 gives 8

The % operator is often used to test divisibility:

if number % 2 == 0:
    print("even")

Characters and Strings

The syllabus distinguishes a character from a string. Python does not have a separate char type, so a character is represented by a string of length 1.

initial = "A"
name = "Aisha"

A string is a sequence of zero or more characters.

name = "computing"
print(name[0])
print(name[1:4])

Indexing starts at 0. For "computing", name[0] is "c".

Strings are immutable. This means an existing string cannot be changed in place.

word = "cat"
new_word = "b" + word[1:]

The original word remains "cat". The expression creates a new string "bat".

Useful string operations include:

message = "  Hello  "
clean = message.strip()
lowercase = clean.lower()
position = clean.find("ll")

Common methods include lower(), upper(), strip(), find(), count(), startswith(), and endswith(). String methods return new strings or other results; they do not change the original string directly.

ASCII and Unicode allow characters to be stored as numbers. Python provides:

code = ord("A")      # 65
character = chr(66)  # "B"

Use ord() when a program needs the code point of one character, and chr() to convert a valid code point back to a character.

Library Functions

The syllabus expects use of common library functions for input/output, strings, and mathematical operations. Some useful built-in functions are len(), abs(), round(), min(), and max().

values = [4, 9, 2]
print(len(values))
print(max(values))

Functions from a module must be imported before use:

import math
 
radius = 3
area = math.pi * radius ** 2

Lists as 1D Arrays

The syllabus refers to one-dimensional arrays. In Python teaching code, lists are normally used for this role.

scores = [72, 85, 68]
scores.append(91)
scores[0] = 75

Important ideas:

  • index starts at 0;
  • len(scores) gives the number of items;
  • scores[-1] gives the last item;
  • lists are mutable, so an item can be replaced.

Example:

scores = [72, 85, 68]
total = 0
 
for score in scores:
    total = total + score
 
average = total / len(scores)
print(average)

Nested Lists as 2D Arrays

A two-dimensional array can be represented as a list of lists.

Caption: In a 2D list, the first index selects the row; the second index selects the item within that row.

marks = [
    [82, 74, 91],
    [65, 88, 79],
]
 
print(marks[1][1])

This prints 88. The first index 1 selects the second row. The second index 1 selects the second item in that row.

Traversing Collections

A list can be processed by value:

for score in scores:
    print(score)

or by index:

for index in range(len(scores)):
    print(index, scores[index])

Use direct traversal when only the values are needed. Use index-based traversal when the position is also needed or when an item must be replaced.

For a 2D list, nested loops visit rows and columns:

for row in marks:
    for value in row:
        print(value)

Choosing the Right Representation

Use a number when the value will be calculated.

mark = 75

Use a string when the value is text or an identifier where the digits are not meant for arithmetic.

student_id = "S1234567A"

Use a Boolean when the value answers a yes/no question.

is_valid = mark >= 0 and mark <= 100

Use a list when there are many values with the same role.

temperatures = [28.1, 29.4, 30.2]

Common Bugs

  • Forgetting that input() gives a string.
  • Confusing = assignment with == comparison.
  • Using an index that is outside the list.
  • Forgetting that strings cannot be changed in place.
  • Mixing integer division // and real division /.
  • Storing numeric-looking identifiers as integers, which may remove leading zeroes.

Practice Trace

Trace this code:

values = [3, 5, 7]
values[1] = values[0] + values[2]
print(values)

After the assignment, values[1] becomes 3 + 7, so the list is [3, 10, 7].

Check Your Understanding

Try these before looking back at the explanations:

  1. What is the type of the value returned by input()?
  2. Why is "0123" usually stored as a string instead of an integer?
  3. If scores = [4, 6, 8], what is scores[0] + scores[2]?
  4. In grid[2][0], which index selects the row?

Answers:

  1. str.
  2. The leading zero is part of the identifier; converting to an integer would lose it.
  3. 12.
  4. The first index, 2, selects the row.