KS48525 3.2.1 to 3.2.5 30 min read 10 question quiz 17 exam marks

Programming Fundamentals

Data types, variables and constants, every operator AQA can ask about, and the three programming constructs that between them can express any algorithm ever written.

Data types

A data type tells the computer what kind of value a variable holds, which decides how many bits it uses, what operations are legal on it and how the bits are interpreted.

AQA names five data types. Learn the names exactly.

Data typeHoldsExample
IntegerA whole number, positive or negative-40, 0, 2025
RealA number with a fractional part3.14, -0.5, 2.0
BooleanOne of exactly two valuesTrue, False
CharacterA single character'K', '7', ' '
StringA sequence of characters"Hello", "7", ""
7 and "7" are not the same thing

The integer 7 can be multiplied. The string "7" is a single character that happens to look like a digit, and multiplying it either fails or repeats it. Nearly every "why does my program crash" question in an exam turns on this.

Why the type matters to the machine

The bit pattern 01000001 is the integer 65, the character A, or part of a real number, depending entirely on what type the program says it is. The bits alone mean nothing. The type is what gives them meaning.

That is also why type errors are so common: the computer will happily do something with a value, it just may not be the thing you meant.

The data types, and changing one into anotherThe five basic data types, one card each. An integer is a whole number such as 42, written int in Python. A real number has a decimal point such as 3.14, written float. A Boolean has only two values, True and False, shown as a switch that is on and a switch that is off. A character is a single symbol such as the letter A, and a string is text inside quote marks. A phone number is stored as a string, because you never do arithmetic on it and because storing it as a number would drop the leading zero, turning 07700 into 7700. Casting changes a value from one type to another: int of the text 42 gives the number 42, str of the number 42 gives the text 42, and int of 3.9 gives 3 because the decimal part is cut off rather than rounded.Integer42-7 0 2025whole numbersintReal3.140.5 -2.75with a decimal pointfloatBooleanTrue Falseonly two valuesboolCharacterAz 7 ?one single symbolstrString"Hi""07700 900123"text in quotesstr1A phone number is a string07700900123you never add phone numbersa number would lose the 007700 as a number = 7700so it is stored as text2Casting: changing type"42"int()42to a whole number42str()"42"to text3.9int()3cuts off the .93
  1. Five data types: integer, real, Boolean, character and string.
  2. A phone number is a string: you never add them, and a number would lose the leading 0.
  3. Casting changes a value from one type to another: int(), str(), float().
Choose the type from what you will do with the value, not from how it looks.
Casting between types: int, float and str, and when it failsCasting converts a value from one data type to another. int of the text 42 gives the whole number 42. int of 3.7 gives 3, because it cuts off the decimal part and does not round. str of the number 5 gives the text 5, so it can be joined to words. float of the text 3.14 gives the decimal number 3.14. The input function always gives back text, so a number typed by a user must be converted, as in age equals int of input. Some conversions fail: int of the text hello raises a ValueError, so input should be checked before it is converted.int("42")42stringint()42integertext to a whole numberint(3.7)3.7floatint()3integercuts off the decimal part: it does not roundstr(5)5integerstr()"5"stringa number to text, so it can be joined to wordsfloat("3.14")"3.14"stringfloat()3.14floattext to a decimal number1234input() always gives text5age = int(input("Age? "))print(age + 1)convert it before doing sums with itSome conversions fail6Output>>> int("hello")ValueError: invalid literalso check the input before converting it
  1. int() turns text into a whole number.
  2. int() on a float cuts off the decimals. It does not round.
  3. str() turns a number into text.
  4. float() turns text into a decimal number.
  5. input() always returns text, so convert it before doing sums.
  6. A conversion that does not make sense raises an error, so validate first.
Casting does not change the original. It makes a new value of the type you asked for.

Variables and constants

A variable is a named location in memory whose value can change while the program runs. A constant is a named value that is fixed when the program is written and cannot change while it runs.

OCR reference language
CONSTANT vat ← 0.2
price ← 40
total ← price + (price * vat)
OUTPUT total

Why constants exist at all

You could simply write 0.2 everywhere it is needed. Three reasons not to:

  • Readability. price * vat says what is happening. price * 0.2 does not.
  • One place to change. If the rate changes, you edit one line rather than hunting through a program for every 0.2, and you cannot miss one.
  • Safety. The compiler or interpreter will stop you accidentally assigning to a constant, which catches a whole class of bug before the program ever runs.
Use a constant when the value is fixed for the whole run

The test is not "does it change" but "should the program be allowed to change it". A VAT rate, the number of players in a game, the maximum length of a password: all constants.

Assignment

The ← symbol in AQA pseudo-code means assignment: work out the value on the right, then store it in the name on the left. It does not mean equality.

OCR reference language
count ← count + 1

As mathematics that is nonsense. As assignment it is perfectly sensible: take the current value of count, add one, put the answer back into count.

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.

Operators

AQA divides operators into three groups, and the specification names all of them.

Arithmetic operators

OperatorMeaningExampleResult
+Add7 + 29
-Subtract7 - 25
*Multiply7 * 214
/Real division7 / 23.5
DIVInteger division, the whole part only7 DIV 23
MODModulus, the remainder7 MOD 21

DIV and MOD are examined constantly, because together they let you take a number apart. seconds DIV 60 gives whole minutes and seconds MOD 60 gives the seconds left over. n MOD 2 = 0 tests whether n is even. n MOD 10 gives the last digit.

Relational operators

= equal to, ≠ not equal to, < less than, > greater than, ≤ less than or equal to, ≥ greater than or equal to.

Every one of these produces a Boolean. That is the whole point of them: they turn a comparison into something selection and iteration can test.

Boolean operators

AND is true only when both sides are true. OR is true when at least one side is true. NOT reverses.

OCR reference language
IF age ≥ 13 AND age ≤ 19 THEN
    OUTPUT 'teenager'
ENDIF
The classic mistake

IF grade = 'A' OR 'B' does not work. The right hand side of the OR must be a complete comparison, so it has to be IF grade = 'A' OR grade = 'B'. Examiners set this deliberately.

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.

The three constructs

Every program ever written is built from three things.

Sequence

Statements run in the order they are written, one after another. Order matters: you cannot use a variable before you have given it a value.

Selection

The program chooses between paths based on a condition.

OCR reference language
IF mark ≥ 70 THEN
    grade ← 'Distinction'
ELSE IF mark ≥ 50 THEN
    grade ← 'Merit'
ELSE IF mark ≥ 40 THEN
    grade ← 'Pass'
ELSE
    grade ← 'Fail'
ENDIF

The order of those conditions is doing real work. A mark of 80 satisfies all three tests, and it gets Distinction only because that test comes first. Reverse the order and every passing student gets a Pass.

Iteration

The program repeats statements. AQA distinguishes two kinds, and the distinction is examined.

Count controlled iteration repeats a number of times known before the loop starts.

OCR reference language
FOR i ← 1 TO 5
    OUTPUT i * i
ENDFOR

Condition controlled iteration repeats while a condition holds, and nothing decides in advance how many times that will be.

OCR reference language
REPEAT
    password ← USERINPUT
UNTIL password = stored

A WHILE loop tests the condition before the body, so it may run zero times. A REPEAT UNTIL loop tests afterwards, so it always runs at least once. That difference is worth a mark on its own.

Choosing the loop in an exam answer

"The number of items in the list is known, so a count controlled FOR loop is appropriate" earns the mark. "I would use a for loop" does not.

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.

Key terms you must be able to define

Variable
A named memory location whose value can change while the program is running.
Constant
A named value fixed when the program is written, which cannot be changed while it runs.
Assignment
Working out the value of an expression and storing the result in a named location.
Data type
A classification that tells the computer how to interpret and store a value.
Integer
A whole number, with no fractional part.
Real
A number that may have a fractional part.
Boolean
A data type with exactly two possible values, True and False.
DIV
Integer division, giving only the whole number part of the result.
MOD
The modulus operator, giving the remainder after an integer division.
Sequence
Statements carried out one after another in the order written.
Selection
Choosing between different paths through a program based on a condition.
Iteration
Repeating a section of a program, either a set number of times or while a condition holds.
Count controlled iteration
A loop that repeats a number of times known before it starts.
Condition controlled iteration
A loop that repeats while a condition is true, for an unknown number of repeats.

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 memory location whose value can change while the program is running.
DefineConstant
AnswerA named value fixed when the program is written, which cannot be changed while it runs.
DefineAssignment
AnswerWorking out the value of an expression and storing the result in a named location.
DefineData type
AnswerA classification that tells the computer how to interpret and store a value.
DefineInteger
AnswerA whole number, with no fractional part.
DefineReal
AnswerA number that may have a fractional part.
DefineBoolean
AnswerA data type with exactly two possible values, True and False.
DefineDIV
AnswerInteger division, giving only the whole number part of the result.

Reach the top grade on this topic

Top answers on this topic are precise in three ways.

They name the construct and justify it. Not "use a loop" but "use a condition controlled loop, because the number of attempts the user needs is not known in advance".

They talk about types as constraints, not labels. A grade 9 answer says that casting the input to an integer is necessary because USERINPUT returns a string and a string cannot be compared numerically. A grade 5 answer says "you need to change it to a number".

They read code before judging it. Most "explain why this program does not work" questions have their answer in the order of the lines or the direction of a comparison. Trace two or three values through by hand before writing anything.

Mistakes that cost marks here

Avoid these
  • Writing IF x = 1 OR 2. Each side of a Boolean operator must be a complete comparison.
  • Confusing DIV and MOD. DIV gives the whole number of times it goes in, MOD gives what is left over.
  • Treating = as equality in an assignment. In pseudo-code AQA uses an arrow precisely to stop this confusion.
  • Saying a WHILE loop always runs at least once. It is REPEAT UNTIL that guarantees one pass.
  • Calling something a constant because it does not happen to change. A constant is declared as one and cannot be changed.
Fun fact

The three construct rule is not a teaching simplification. In 1966 Bohm and Jacopini proved mathematically that sequence, selection and iteration are enough to express every computable function. Nothing else is strictly necessary.

Knowledge check

0 of 10 answered
1What is the result of 17 DIV 5?
2What is the result of 17 MOD 5?
3Which data type would be most appropriate for storing a student's average grade of 68.4?
4Which of these is true of a REPEAT UNTIL loop but not a WHILE loop?
5What does the expression n MOD 2 = 0 test?
6Why would a programmer declare the number of players in a game as a constant?
7A program contains total ← total + price. What happens?
8Which construct would be most appropriate for processing every item in a list of 40 names?
9What is wrong with IF grade = 'A' OR 'B' THEN?
10A variable holds the value "25" as a string. What happens if the program tries to add 5 to it?
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.

17 marks
1State the difference between a variable and a constant.2 marks
State

Mark scheme0 / 2
  • LA variable can change value while the program is running
  • LA constant is fixed when the program is written and cannot change while it runs
Model answer

A variable is a named memory location whose value can be changed while the program is running. A constant is a named value that is set when the program is written and cannot be changed while the program runs.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2A program needs to work out how many complete minutes and how many remaining seconds there are in a total of 500 seconds. Write the two expressions needed and give their values.4 marks
Write

Mark scheme0 / 4
  • LUses DIV for the minutes, for example 500 DIV 60
  • LGives 8 minutes
  • LUses MOD for the seconds, for example 500 MOD 60
  • LGives 20 seconds
Model answer

The number of whole minutes is 500 DIV 60, which is 8, because sixty goes into five hundred eight complete times. The seconds left over are 500 MOD 60, which is 20, because eight lots of sixty is four hundred and eighty and five hundred minus four hundred and eighty is twenty.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Explain the difference between count controlled and condition controlled iteration, giving one example of when each would be used.4 marks
Explain

Mark scheme0 / 4
  • LCount controlled iteration repeats a number of times known before the loop starts
  • LCondition controlled iteration repeats while a condition is true, for an unknown number of repeats
  • LGives a sensible count controlled example, such as processing every item in a list of known length
  • LGives a sensible condition controlled example, such as repeating until valid input is entered
Model answer

Count controlled iteration repeats a fixed number of times that is known before the loop begins, so a FOR loop is used. Working through all forty names in a list is a count controlled task, because the length of the list is known. Condition controlled iteration repeats for as long as a condition remains true, and the number of repeats is not known in advance. Asking a user to re-enter a password until it matches is condition controlled, because there is no way to know 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.
4A student writes IF temperature > 30 OR temperature < 10 THEN. Explain what this condition tests and give one situation in which it would be false.3 marks
Explain

Mark scheme0 / 3
  • LIt is true when the temperature is above 30
  • LIt is also true when the temperature is below 10
  • LIt is false for any value from 10 to 30 inclusive, for example 20
Model answer

The condition uses OR, so it is true when at least one of the two comparisons is true. It is therefore true when the temperature is greater than 30 and true when the temperature is less than 10, which means it detects any temperature outside the comfortable range. It is false for any value from 10 to 30 inclusive, so a temperature of 20 would make it false.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5A program asks the user for their age and then tests whether they can vote. The programmer finds that the test never succeeds, even when 18 is entered. Explain the most likely cause and how it would be corrected.4 marks
Explain

Mark scheme0 / 4
  • LUSERINPUT or the equivalent returns a string
  • LThe program is comparing a string with an integer, which does not behave as expected
  • LThe input must be cast or converted to an integer
  • LThen the numeric comparison works correctly
Model answer

The most likely cause is that input is returned as a string, so the variable holds the two characters '1' and '8' rather than the number eighteen. Comparing a string with an integer either fails outright or compares character by character, so the test does not behave as intended and never succeeds. The correction is to cast the input to an integer as soon as it is read, for example age ← STRING_TO_INT(USERINPUT), after which the comparison age ≥ 18 works on two numbers and gives the right answer.

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