impera Open Impera

A levels Computer Science · Programming and data

Programming fundamentals

1Variables, constants and assignment

A variable is a named location in memory whose value can change while the program runs. A constant is named once and never changes, for example VAT_RATE = 0.2.

  • Assignment gives a variable a value: total = total + price.
  • Use meaningful identifiers (score, not s) so the code explains itself.
  • Constants make code easier to update (change one line) and stop a value being changed by mistake.
VAT_RATE = 0.2
price = 50
total = price * (1 + VAT_RATE)
print(total)      # 60.0

The basic arithmetic operators are +, −, *, / (real division), // (integer division, called DIV) and % (remainder, called MOD). For example, 17 // 5 = 3 and 17 % 5 = 2.

Check yourself

What is 23 MOD 4?

  • 5

  • 5.75

  • 4

  • 3

Show the answer

3

23 = 5 × 4 + 3.

2Selection and iteration

Every program can be built from three structures: sequence, selection and iteration.

mark = int(input("Mark: "))
if mark >= 70:
    grade = "A"
elif mark >= 50:
    grade = "C"
else:
    grade = "U"
LoopTypeWhen to use
forcount-controlled (definite)the number of repeats is known
whilecondition-controlled, checked at the startmay run zero times
repeat ... untilcondition-controlled, checked at the endalways runs at least once

Validation with a while loop keeps asking until the input is acceptable:

age = int(input("Age: "))
while age < 0 or age > 120:
    age = int(input("Try again: "))
Check yourself

Which loop always runs its body at least once?

  • while (a pre-condition loop)

  • repeat ... until (a post-condition loop)

  • None of them, it depends on data

  • for (a count-controlled loop)

Show the answer

repeat ... until (a post-condition loop)

Checked at the end.

3Subroutines, parameters and scope

A subroutine is a named block of code that performs a task. A function returns a value; a procedure does not.

def area(width, height):      # parameters
    return width * height

room = area(4, 5) # arguments 4 and 5; room = 20

  • Parameters are the names in the definition; arguments are the values passed in.
  • Parameters can be passed by value (a copy, so the original cannot change) or by reference (the address, so the subroutine can change the original).
  • A local variable exists only inside its subroutine. A global variable can be used anywhere, but makes code harder to test and debug.

Benefits of subroutines: code is reused rather than repeated, each part can be tested on its own, and teams can work on different subroutines at once.

Check yourself

What is the difference between a function and a procedure?

  • A procedure returns a value; a function does not

  • There is no difference

  • A function cannot take parameters

  • A function returns a value; a procedure does not

Show the answer

A function returns a value; a procedure does not

Return value.

4Recursion

A recursive subroutine calls itself. It needs a base case that stops the recursion, and each call must move closer to that base case.

def factorial(n):
    if n == 1:            # base case
        return 1
    return n * factorial(n - 1)

factorial(4): each call waits on the call stack until the base case returns, then the results are multiplied on the way back up.

Each call is pushed onto the call stack with its own parameters, local variables and return address. If there is no base case, the stack fills up and the program crashes with a stack overflow.

RecursionIteration
often shorter and closer to the mathsusually faster
uses more memory (one stack frame per call)uses a fixed amount of memory
natural for trees and divide-and-conquernatural for simple repeats
Check yourself

What happens if a recursive function has no base case?

  • It runs once

  • It calls itself until the call stack overflows

  • It returns 0

  • It turns into a loop automatically

Show the answer

It calls itself until the call stack overflows

Never stops.

5Strings, random numbers and exceptions

Common string operations:

OperationExampleResult
lengthlen("pebble")6
substring"pebble"[1:4]"ebb"
position"pebble".find("b")2
concatenation"peb" + "ble""pebble"
character codeord("A")65
convertint("42"), str(42)42, "42"

Random numbers are generated by a pseudo-random algorithm, for example random.randint(1, 6) for a dice roll.

Exception handling stops a program crashing when something goes wrong at run time:

try:
    n = int(input("Number: "))
except ValueError:
    print("That was not a whole number")
Check yourself

What is "computer"[3:6]?

  • "mpu"

  • "put"

  • "pute"

  • "omp"

Show the answer

"put"

Indexes 3, 4, 5.

6Structured programming and trace tables

Structured programming builds a program from small subroutines using only sequence, selection and iteration, with clear interfaces. This makes code easier to read, test and maintain.

A trace table records the value of each variable as a program runs. It is used to find logic errors by hand.

Worked example

Tracing a loop

  1. Code: total = 0, then for i in range(1, 4): total = total + i * i.
  2. i = 1: total = 1.
  3. i = 2: total = 1 + 4 = 5.
  4. i = 3: total = 5 + 9 = 14.

Types of test data: normal (typical valid values), boundary (at the edges of the valid range, both just inside and just outside) and erroneous (invalid values that should be rejected).

Check yourself

For an age that must be 0 to 120, which value is boundary data?

  • 45

  • 120

  • 500

  • "ten"

Show the answer

120

At the edge.

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