KS4J277 2.2.1 34 min read 10 question quiz 20 exam marks

Programming Fundamentals

Variables, constants, the three programming constructs, operators and how to write code that an examiner can follow and award marks to.

Variables and constants

A variable is a named location in memory that holds a value which can change while the program runs.

A constant is a named value that is fixed and cannot be changed once set.

Python
score = 0            # variable, will change
lives = 3            # variable
VAT_RATE = 0.20      # constant by convention in Python
PI = 3.14159         # constant

Why use constants

  • The value appears once, so changing it means editing one line rather than hunting through the program
  • The name explains what the number means, so VAT_RATE is far clearer than 0.2
  • The value cannot be changed accidentally, which prevents a whole class of bugs
Naming matters for marks

Use meaningful names. totalPrice is better than t in every possible way, and examiners note it as good practice.

Variables as labelled boxes, with the code that makes themSix lines of code on the left and the boxes they create on the right. The equals sign is assignment: it stores the value on its right in the variable named on its left. Every variable is like a labelled box with a name, a value and a data type. name holds the string Asha, age holds the whole number 15, price holds the decimal 2.5 and passed holds True. The fifth line, age equals age plus one, takes the 15 out and puts 16 in, which shows that the value of a variable can change while its name stays the same. PI is a constant: a value that must never change, written in capitals by convention and shown with a padlock. A card at the bottom left gives the naming rules: use letters, digits and underscores, do not start with a digit and never use a space.variables.py1name = "Asha"2age = 153price = 2.504passed = True5age = age + 16PI = 3.14159Naming a variabletotal_scorewords joined by _age2digits are fine inside2nd_placecannot start with a digitmy scoreno spacesWhat the computer keepsname"Asha"strage16intreplaces 15price2.5floatpassedTrueboolPI3.14159a constant: never changes12345
  1. = stores a value in a variable: the name on the left, the value on the right.
  2. A variable is a labelled box with a name, a value and a data type.
  3. The value can change. age = age + 1 takes the 15 out and puts 16 in.
  4. A constant holds a value that must never change. By convention it is written in capitals.
  5. Names use letters, digits and underscores. No spaces, and no digit first.
The name stays. The value is what you can swap.

The three constructs

Sequence

Instructions are carried out one after another, in order.

Python
name = input("What is your name? ")
greeting = "Hello " + name
print(greeting)

Selection

The program chooses between different paths based on a condition.

Python
mark = int(input("Enter the mark: "))

if mark >= 70:
    print("Distinction")
elif mark >= 50:
    print("Pass")
else:
    print("Fail")

Note the order. If the first condition were mark >= 50, then a mark of 80 would print "Pass" and never reach the distinction branch. Order the conditions from most restrictive to least.

Iteration

Instructions are repeated.

Count controlled loops repeat a known number of times.

Python
for i in range(5):
    print("Line", i)

Condition controlled loops repeat until a condition changes.

Python
password = ""
while password != "opensesame":
    password = input("Enter the password: ")
print("Access granted")
range(5) gives 0, 1, 2, 3, 4

It runs five times but never reaches 5. range(1, 6) gives 1 to 5. This is where most off by one errors come from.

Nested constructs

Constructs can be placed inside each other.

Python
for row in range(3):
    for col in range(3):
        if row == col:
            print("X", end=" ")
        else:
            print(".", end=" ")
    print()

The inner loop completes entirely for each single iteration of the outer loop, so this runs nine times in total.

The three constructs: sequence, selection and iterationEvery program is built from three constructs, one card each. Sequence is steps taken one after another in order: wake up, brush teeth, have breakfast, and in code the lines run once each from the top down. Selection is a choice: a decision diamond asks whether it is raining, and only one of the two branches is taken, an umbrella if yes and sunglasses if no, written in code as if and else. Iteration is repetition: a loop arrow carries Pixel round again, here five times, written as a for loop over range of five, and when the loop has finished the program carries on with the next line.SequenceSelectionIteration1wake up2brush teeth3have breakfastprint("Wake up")print("Brush teeth")print("Have breakfast")every line runs once,from the top downraining?yesnoumbrellasunglassesif raining:    print("Umbrella")else:    print("Sunglasses")only one branch runsdepending on the answer5 timesfor i in range(5):    print("Star jump")the block repeats,then the program moves on123
  1. Sequence: instructions run in order, each one once, from the top down.
  2. Selection: a condition is tested and only one branch of the program runs.
  3. Iteration: a block is repeated, a set number of times or until a condition changes.
Any algorithm, however big, is these three arranged in different ways.

Operators

Arithmetic

OperatorMeaningExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/Division7 / 23.5
MOD or %Remainder7 % 21
DIV or //Integer division7 // 23
^ or **Exponent2 ** 38

MOD is extremely useful. number % 2 == 0 tests whether a number is even. seconds % 60 gives the seconds part of a time.

Comparison

OperatorMeaning
==Equal to
!=Not equal to
<Less than
<=Less than or equal to
>Greater than
>=Greater than or equal to
One equals sign assigns, two compare

x = 5 puts 5 into x. x == 5 asks whether x is 5. Mixing these up is the single most common beginner error.

Boolean

  • AND is true only when both conditions are true
  • OR is true when at least one is true
  • NOT reverses a condition
Python
if age >= 13 and age <= 19:
    print("Teenager")

if day == "Saturday" or day == "Sunday":
    print("Weekend")

if not logged_in:
    print("Please sign in")
Arithmetic and comparison operatorsThe arithmetic operators as seven cards: plus, minus, multiply, divide, DIV, MOD and power, each with a worked example. Seven divided by two is 3.5. DIV gives the whole number of times it goes in, so 7 DIV 2 is 3, written with a double slash in Python, and MOD gives what is left over, so 7 MOD 2 is 1, written with a percent sign. A picture shows it as seven cookies shared between two people: three each, and one left over. Below, the comparison operators give True or False: 5 equals 5 is True, 5 is not equal to 5 is False, 5 greater than or equal to 6 is False and 5 less than 6 is True. A warning shows the commonest slip: a single equals sign stores a value, while a double equals sign asks whether two values are equal.+add7 + 2= 9-subtract7 - 2= 5*multiply7 * 2= 14/divide7 / 2= 3.5//DIV7 // 2= 3%MOD7 % 2= 1**power2 ** 3= 81DIV and MOD: 7 cookies, 2 people3 each3 each1 left over7 // 2 = 3 (DIV)7 % 2 = 1 (MOD)2Comparing: True or False5 == 5True5 != 5False5 >= 6False5 < 6True= stores a value== asks "are they equal?"34
  1. Arithmetic: + - * / then DIV, MOD and power.
  2. DIV is how many whole times it goes in. MOD is what is left over.
  3. Comparisons ask a question, and the answer is always True or False.
  4. = stores a value. == asks whether two values are equal.
MOD is the clock operator: it is what is left when you have gone round as many times as you can.

Writing code the exam can mark

Paper 2 asks you to write code in Python, in OCR reference language, or in another high level language. Whichever you choose, a few habits make a large difference.

Habits that earn marks

  1. Indent consistently. In Python, indentation is the structure. In reference language it makes your logic readable.
  2. Use meaningful variable names. numberOfGuesses beats n.
  3. Convert input types. input() always returns a string, so use int() or float() when you need a number.
  4. Comment anything non obvious, briefly.
  5. Close every structure. In reference language, every if needs an endif and every while needs an endwhile.
  6. Read the question for the exact requirements. If it says validate the input, a program without validation cannot get full marks however elegant it is.

A complete example

Python
# Ask for 5 marks, then report the average and the highest

TOTAL_STUDENTS = 5
marks = []

for i in range(TOTAL_STUDENTS):
    valid = False
    while not valid:
        entry = input("Enter mark " + str(i + 1) + ": ")
        if entry.isdigit() and 0 <= int(entry) <= 100:
            valid = True
        else:
            print("Please enter a whole number between 0 and 100.")
    marks.append(int(entry))

average = sum(marks) / TOTAL_STUDENTS
highest = max(marks)

print("Average:", round(average, 1))
print("Highest:", highest)

Notice: a constant for the fixed value, validation before use, meaningful names, and clear output.

Key terms you must be able to define

Variable
A named location in memory holding a value that can change while the program runs.
Constant
A named value that is fixed and cannot be changed once it has been set.
Sequence
Instructions carried out one after another in the order written.
Selection
Choosing between different paths through a program based on a condition.
Iteration
Repeating a block of instructions, either a set number of times or until a condition is met.
Count controlled loop
A loop that repeats a known, fixed number of times.
Condition controlled loop
A loop that repeats until a condition becomes true or false.
MOD
The modulus operator, which returns the remainder after division.
DIV
Integer division, which returns the whole number part of a division.
Nested loop
A loop placed inside another loop.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineVariable
AnswerA named location in memory holding a value that can change while the program runs.
DefineConstant
AnswerA named value that is fixed and cannot be changed once it has been set.
DefineSequence
AnswerInstructions carried out one after another in the order written.
DefineSelection
AnswerChoosing between different paths through a program based on a condition.
DefineIteration
AnswerRepeating a block of instructions, either a set number of times or until a condition is met.
DefineCount controlled loop
AnswerA loop that repeats a known, fixed number of times.
DefineCondition controlled loop
AnswerA loop that repeats until a condition becomes true or false.
DefineMOD
AnswerThe modulus operator, which returns the remainder after division.

Reach the top grade on this topic

Programming marks are won by completeness, not cleverness.

Answer exactly what is asked. If the question requires input, validation, a calculation and an output, the mark scheme has a mark for each. A brilliant program missing the validation loses that mark regardless.

Choose the right loop. A known number of repetitions means a for loop. An unknown number, such as repeating until the user types quit, means a while loop. Choosing wrongly is often penalised.

Order your conditions correctly. With overlapping ranges, put the most restrictive first. if mark >= 70 must come before elif mark >= 50.

Handle the input type. In Python, input() returns a string. Comparing that string with a number will never behave as intended.

  • Write a validated input loop from memory
  • Trace a nested loop and state exactly how many times the inner body runs
  • Use MOD to test for even numbers and to extract digits
  • Explain the difference between a variable and a constant, with a reason for using each

Mistakes that cost marks here

Avoid these
  • Using a single equals sign in a condition instead of a double equals.
  • Forgetting to convert input to an integer before doing arithmetic or a numeric comparison.
  • Assuming range(5) includes 5. It gives 0 to 4.
  • Ordering elif conditions from least restrictive to most, so higher values never reach the correct branch.
  • Writing a while loop where nothing inside can ever change the condition, creating an infinite loop.
  • Using single letter variable names throughout, which makes the code hard to follow and hard to mark.
Fun fact

Every program ever written, from a calculator to an operating system, is built from just three structures: sequence, selection and iteration. This was proved mathematically in 1966 and is called the structured program theorem.

Knowledge check

0 of 10 answered
1What is the difference between a variable and a constant?
2What does 17 MOD 5 evaluate to?
3How many times does for i in range(3) execute the loop body?
4Which loop should be used when the number of repetitions is not known in advance?
5What does 17 DIV 5 evaluate to?
6Which condition correctly tests whether a number stored in n is even?
7What is wrong with if score = 100: in Python?
8In a nested loop where the outer runs 4 times and the inner runs 5 times, how many times does the inner body execute in total?
9Which expression is true when age is 15?
10Why should a program use a constant for a VAT rate rather than typing 0.2 throughout?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

20 marks
1State the difference between a variable and a constant, and give one reason a programmer would use a constant.3 marks
State

Mark scheme0 / 3
  • LA variable can change value while the program runs
  • LA constant cannot be changed once set
  • LReason such as preventing accidental change, or only needing to edit one line if the value changes
Model answer

A variable is a named memory location whose value can be changed at any point while the program is running, whereas a constant is given a value once and that value cannot be changed afterwards. A programmer would use a constant for a value such as a VAT rate or the maximum number of players, because it prevents the value being altered accidentally elsewhere in the program, and if the value ever does need updating it appears in only one place, so only one line has to be edited.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Explain the difference between a count controlled loop and a condition controlled loop, giving an example use for each.4 marks
Explain

Mark scheme0 / 4
  • LA count controlled loop repeats a known fixed number of times
  • LExample such as processing every item in an array of known length
  • LA condition controlled loop repeats until a condition is met, and the number of repetitions is not known in advance
  • LExample such as repeatedly asking for input until it is valid
Model answer

A count controlled loop repeats a known, fixed number of times, which is decided before the loop begins. It would be used, for example, to work through every element of an array of 20 marks, because the number of iterations required is known to be 20. A condition controlled loop repeats for as long as, or until, a particular condition holds, and the number of repetitions is not known when the loop starts. It would be used, for example, to keep asking the user to enter a password until they type the correct one, since there is no way to know in advance how many attempts they will need.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Write a program that asks the user to enter numbers repeatedly until they enter 0, then outputs how many numbers were entered and their total.6 marks
Write

Mark scheme0 / 6
  • LInitialises a counter and a total to zero
  • LUses a condition controlled loop
  • LTakes input inside the loop and converts it to a number
  • LStops the loop when 0 is entered
  • LAdds each valid number to the total and increments the counter
  • LOutputs both the count and the total after the loop
Model answer

count = 0 total = 0 number = int(input("Enter a number, or 0 to finish: ")) while number != 0: total = total + number count = count + 1 number = int(input("Enter a number, or 0 to finish: ")) print("You entered", count, "numbers") print("Their total is", total) The counter and total are initialised to zero before the loop. The first number is read before the loop so that the condition can be tested. The while loop continues for as long as the number entered is not 0, adding each value to the running total, increasing the counter and then reading the next number. When 0 is entered the loop ends without counting the 0 itself, and the count and total are output.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4A program contains the following selection statement, which is intended to award grades. Explain why a mark of 85 would be given the wrong grade.if mark >= 40 then print("Pass") elseif mark >= 70 then print("Distinction") endif3 marks
Explain

Mark scheme0 / 3
  • LThe conditions are tested in order from the top
  • L85 satisfies the first condition mark >= 40, so Pass is printed
  • LThe elseif is never reached, so the fix is to test the most restrictive condition first
Model answer

Selection statements are evaluated from the top downwards, and as soon as one condition is found to be true its block runs and the remaining branches are skipped entirely. A mark of 85 satisfies the first condition, because 85 is greater than or equal to 40, so the program prints Pass and the elseif testing for 70 or above is never reached. The fix is to reorder the conditions so that the most restrictive is tested first: check whether the mark is at least 70 and award Distinction, and only then check whether it is at least 40 and award Pass.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Explain what the MOD operator does and give two situations where it would be useful in a program.4 marks
Explain

Mark scheme0 / 4
  • LMOD returns the remainder after a division
  • LGives a correct example of its value, such as 17 MOD 5 being 2
  • LFirst use such as testing whether a number is even or odd
  • LSecond use such as extracting units of time, or cycling through a fixed set of values
Model answer

The MOD operator carries out a division and returns the remainder rather than the quotient, so 17 MOD 5 gives 2 because 5 goes into 17 three times with 2 left over. One useful application is testing whether a number is even or odd: if a number MOD 2 equals 0 then it divides exactly by two and is therefore even, which is a very common requirement in filtering and alternating logic. A second application is breaking a value into units, for example converting a total number of seconds into minutes and seconds, where the total DIV 60 gives the number of whole minutes and the total MOD 60 gives the seconds left over. MOD is also used to cycle a value within a fixed range, such as wrapping a player position around the edge of a game board.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 20