impera Open Impera

IB Diploma Computer Science · Computational thinking and problem-solving

Programming

1Variables, data types and operators

A variable is a named storage location whose value can change while the program runs. A constant holds a value that should not change, such as VAT_RATE = 0.2 (written in capitals by convention).

Common data types:

  • Integer (int): whole numbers, such as 42 or −7.
  • Real / floating point (float): numbers with a fractional part, such as 3.14.
  • Boolean (bool): True or False.
  • Character and string (str): text, such as "Pebble".

Choosing the right type matters: it decides how much memory is used and which operations are allowed. Casting converts between types: int("42") + 1 gives 43, and str(3.5) + "!" gives "3.5!". Input from the keyboard always arrives as a string, so it must be cast before doing arithmetic.

Operators in Python:

  • Arithmetic: + - * / (division gives a float: 7 / 2 is 3.5), // (integer division: 7 // 2 is 3), % (modulus, the remainder: 7 % 2 is 1), (power: 2 10 is 1024).
  • Comparison: == != < <= > >=, which give a Boolean.
  • Logical (Boolean): and, or, not.
Example

n % 2 == 0 is True exactly when n is even.

Check yourself

What is the value of 17 % 5 in Python?

  • 85

  • 3

  • 2

  • 3.4

Show the answer

2

% gives the remainder: 17 = 3 × 5 + 2.

2Selection and iteration

Selection chooses which code to run:

mark = int(input("Mark: "))
if mark >= 70:
    grade = "7"
elif mark >= 50:
    grade = "5"
else:
    grade = "fail"
print(grade)

Iteration repeats code:

  • A for loop (count-controlled) repeats a known number of times, or once for each item in a collection: for i in range(5) runs with i = 0, 1, 2, 3, 4.
  • A while loop (condition-controlled) repeats while a condition is true. It may run zero times, and it can loop forever if the condition never becomes false.

Input validation with a while loop:

age = int(input("Age: "))
while age < 11 or age > 19:
    print("Please enter an age from 11 to 19")
    age = int(input("Age: "))

Nested structures put one inside another, such as a loop inside a loop to visit every cell of a grid.

Check yourself

How many times does the body of "for i in range(2, 10, 2)" run?

  • 8

  • 10

  • 5

  • 4

Show the answer

4

i takes the values 2, 4, 6 and 8; the end value 10 is excluded.

3Strings

A string is a sequence of characters, each with an index starting at 0.

  • len("Pebble") is 6.
  • Indexing: "Pebble"[0] is "P", and "Pebble"[-1] is "e" (counting from the end).
  • Slicing: "Pebble"[1:4] is "ebb" (from index 1 up to, but not including, 4).
  • Concatenation joins strings: "Peb" + "ble".
  • Methods: .upper(), .lower(), .strip() (remove surrounding spaces), .split(",") (split into a list), .find("b") (index of the first match), .replace("a", "o").
  • Strings in Python are immutable: methods return a new string rather than changing the old one.
Worked example

Count the vowels in a word

  1. Start a counter at 0.
  2. Loop through each character of the word, converted to lower case.
  3. If the character is in "aeiou", add 1 to the counter.
  4. For "Computer", the vowels are o, u and e, so the result is 3.
Check yourself

What is "Science"[2:5]?

  • "Sci"

  • "cie"

  • "ienc"

  • "ien"

Show the answer

"ien"

Indexes 2, 3 and 4: i, e, n.

4Lists, arrays and 2D data

A list (Python's flexible array) stores many values under one name, accessed by index.

scores = [72, 65, 80]
scores.append(91)
print(scores[0], len(scores))
  • A static data structure (a classic array) has a fixed size set when it is created; it is memory-efficient and fast to index.
  • A dynamic data structure (such as a Python list) can grow and shrink while the program runs, but uses extra memory to manage this.
  • A 2D array (a list of lists) stores a table. marks[1][2] means row 1, column 2.

A 2D array: marks[row][column]

Worked example

The average of each row

  1. marks = [[72, 65, 80], [55, 90, 61]].
  2. Row 0: (72 + 65 + 80) ÷ 3 = 72.3.
  3. Row 1: (55 + 90 + 61) ÷ 3 = 68.7.
  4. In code: for row in marks: print(sum(row) / len(row)).
Check yourself

In marks = [[72, 65, 80], [55, 90, 61]], what is marks[1][0]?

  • 72

  • 90

  • 65

  • 55

Show the answer

55

Row 1 is [55, 90, 61]; its item 0 is 55.

5Functions, procedures and scope

A subroutine is a named block of code that performs one task and can be called many times.

  • A function returns a value; a procedure carries out actions but returns nothing.
  • Parameters are the variables listed in the definition; arguments are the actual values passed in when it is called.
def total(items):
    result = 0
    for value in items:
        result = result + value
    return result

print(total([3, 5, 9]))

This prints 17.

  • Scope: a local variable (like result) exists only inside its subroutine. A global variable is available everywhere, but globals make programs harder to debug, so local variables and parameters are preferred.
  • Benefits of subroutines (modularity): code is reused rather than repeated, each part can be written and tested separately, teams can split the work, and programs are easier to read and maintain.
  • Libraries are collections of ready-made, tested subroutines, such as Python's math and random modules.
Check yourself

What is the difference between a function and a procedure?

  • A procedure has parameters; a function does not

  • There is no difference

  • Functions can only be used once

  • A function returns a value; a procedure does not

Show the answer

A function returns a value; a procedure does not

Both are subroutines.

6Files, exceptions and recursion

Files store data permanently, after the program ends.

with open("scores.txt", "a") as f:
    f.write("Amara,72\n")

with open("scores.txt") as f:
for line in f:
name, mark = line.strip().split(",")
print(name, int(mark))

Mode "r" reads, "w" writes (replacing the file) and "a" appends to the end.

Exception handling stops a program crashing when something goes wrong at runtime, such as bad input or a missing file:

try:
    age = int(input("Age: "))
except ValueError:
    print("Please type a whole number")

Recursion: a recursive function calls itself on a smaller version of the problem. It needs a base case that stops the recursion, or it will run until the call stack overflows.

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

factorial(5) gives 120. Each call waits on the call stack until the call below it returns.

Recursion: factorial(4) calls itself until the base case, then the results return up the call stack

Recursion can make some problems (trees, divide-and-conquer sorts) much simpler to write, but it uses more memory than a loop because every call is kept on the stack.

Check yourself

What happens if a recursive function has no base case?

  • It runs once and then stops without returning a value

  • It keeps calling itself until the call stack overflows

  • It returns 0 automatically after the first call ends

  • It is turned into a loop automatically by the compiler

Show the answer

It keeps calling itself until the call stack overflows

The base case is what stops it.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera