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.
score = 0 # variable, will change
lives = 3 # variable
VAT_RATE = 0.20 # constant by convention in Python
PI = 3.14159 # constantWhy 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_RATEis far clearer than0.2 - The value cannot be changed accidentally, which prevents a whole class of bugs
Use meaningful names. totalPrice is better than t in every possible way, and examiners note it as good practice.
- = stores a value in a variable: the name on the left, the value on the right.
- A variable is a labelled box with a name, a value and a data type.
- The value can change. age = age + 1 takes the 15 out and puts 16 in.
- A constant holds a value that must never change. By convention it is written in capitals.
- Names use letters, digits and underscores. No spaces, and no digit first.
The three constructs
Sequence
Instructions are carried out one after another, in order.
name = input("What is your name? ")
greeting = "Hello " + name
print(greeting)Selection
The program chooses between different paths based on a condition.
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.
for i in range(5):
print("Line", i)Condition controlled loops repeat until a condition changes.
password = ""
while password != "opensesame":
password = input("Enter the password: ")
print("Access granted")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.
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.
- Sequence: instructions run in order, each one once, from the top down.
- Selection: a condition is tested and only one branch of the program runs.
- Iteration: a block is repeated, a set number of times or until a condition changes.
Operators
Arithmetic
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | Division | 7 / 2 | 3.5 |
MOD or % | Remainder | 7 % 2 | 1 |
DIV or // | Integer division | 7 // 2 | 3 |
^ or ** | Exponent | 2 ** 3 | 8 |
MOD is extremely useful. number % 2 == 0 tests whether a number is even. seconds % 60 gives the seconds part of a time.
Comparison
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
<= | Less than or equal to |
> | Greater than |
>= | Greater than or equal to |
x = 5 puts 5 into x. x == 5 asks whether x is 5. Mixing these up is the single most common beginner error.
Boolean
ANDis true only when both conditions are trueORis true when at least one is trueNOTreverses a condition
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: + - * / then DIV, MOD and power.
- DIV is how many whole times it goes in. MOD is what is left over.
- Comparisons ask a question, and the answer is always True or False.
- = stores a value. == asks whether two values are equal.
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
- Indent consistently. In Python, indentation is the structure. In reference language it makes your logic readable.
- Use meaningful variable names.
numberOfGuessesbeatsn. - Convert input types.
input()always returns a string, so useint()orfloat()when you need a number. - Comment anything non obvious, briefly.
- Close every structure. In reference language, every
ifneeds anendifand everywhileneeds anendwhile. - 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
# 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.
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
- 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.
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
for i in range(3) execute the loop body?if score = 100: in Python?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.
- 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
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.
- 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
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.
- 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
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.
- 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
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.
- 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
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.