8.1 Programming Concepts
8.1 Programming Concepts
Page 1 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Pseudocode
Python
Page 2 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
What is a constant?
A constant is an identifier set once in the lifetime of a program Your notes
Constants are named in all uppercase characters
Constants aid the readability and maintainability
If a constant needs to be changed, it should only need to be altered in one place in the whole program
Pseudocode
CONSTANT PI ← 3.142
Python
PI = 3.142
VAT = 0.20
PASSWORD = "letmein"
Page 3 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Data Types
Your notes
Data Types
What is a data type?
A data type is a classification of data into groups according to the kind of data they represent
Computers use different data types to represent different types of data in a program
The basic data types include:
Real Numbers with a fractional part (decimal) REAL 3.14, -2.5, 0.0
It is important to choose the correct data type for a given situation to ensure accuracy and efficiency
in the program
Data types can be changed within a program, this is called casting
Page 4 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Boolean LightSensor ← True lightSensor = True
WORKED EXAMPLE
Name and describe the most appropriate programming data type for each of the examples of data
given. Each data type must be different
[6]
Data: 83
Data: [email protected]
Data: True
Answers
Data type name: Integer [1]
Data type description: The number is a whole number [1]
Data type name: String [1]
Data type description: It is a group of characters [1]
Data type name: Boolean [1]
Data type description: The value is True (or could be False) [1]
Page 5 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Examples
Pseudocode (INPUT <identifier>) Python
What is an output?
An output is a value sent to an output device from a computer program
Typical output devices include:
Monitor - Displaying text, images or graphics
Speaker - Playing audio
Printer - Creating physical copies of documents or images
Page 6 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
OUTPUT "Love the name ", Name print("Love the name "+name)
Page 7 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Sequence
Your notes
Sequence
What is sequence?
Sequence refers to lines of code which are run one line at a time
The lines of code are run in the order that they written from the first line of code to the last line of code
Sequence is crucial to the flow of a program, any instructions out of sequence can lead to
unexpected behaviour or errors
Example 1
A simple program to ask a user to input two numbers, number two is subtracted from number one and
the result is outputted
Line Pseudocode
02 INPUT Num1
04 INPUT Num2
06 OUTPUT Result
A simple swap of line 01 and line 02 would lead to an unexpected behaviour, the user would be
prompted to input information without knowing what they should enter
Example 2
Python example
Page 8 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
"""
This function calculates the area of a rectangle Your notes
Inputs:
length: The length of the rectangle
width: The width of the rectangle
Returns:
The area of the rectangle
"""
# Calculate area
return area
width = 3
In the example, the sequence of instructions is wrong and would cause a runtime error
In the calculate_area() function a value is returned before it is assigned
The correct sequence is:
# Calculate area
area = length * width
return area
Page 9 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Selection
Your notes
What is Selection?
Selection is when the flow of a program is changed, depending on a set of conditions
The outcome of this condition will then determine which lines or block of code is run next
Selection is used for validation, calculation and making sense of a user's choices
There are two ways to write selection statements:
if... then... else...
case...
If Statements
What is an If statement?
As If statements allow you to execute a set of instructions if a condition is true
They have the following syntax:
IF <condition>
THEN
<statement>
ENDIF
A detailed look at a Python IF statement:
Page 10 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Example
Concept Pseudocode Python
THEN print("Correct")
ELSE print("Wrong")
ENDIF print("Error")
Nested Selection
What is nested selection?
Page 11 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Nested selection is a selection statement within a selection statement, e.g. an If inside of another If
Nested means to be 'stored inside the other' Your notes
Example
Pseudocode
THEN
THEN
ELSE
ENDIF
ELSE
THEN
ENDIF
ENDIF
Python
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
result = "Merit"
result = "Pass
else:
result = "Fail"
Case Statements
What is a case statement?
A case statement can mean less code but it only useful when comparing multiple values of the same
variable
If statements are more flexible and are generally used more in languages such as Python
The format of a CASE statement is:
CASE OF <identifier>
<value 1> : <statement>
<value 2>: <statement>
....
OTHERWISE <statement>
ENDCASE
Page 13 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
ENDCASE
EXAM TIP
Make sure to include all necessary components in the selection statement:
the condition,
the statement(s) to execute when the condition is true
any optional statements to execute when the condition is false
Use proper indentation to make the code easier to read and understand
Be careful with the syntax of the programming language being used, as it may differ slightly
between languages
Make sure to test the selection statement with various input values to ensure that it works as
expected
WORKED EXAMPLE
Write an algorithm using pseudocode that:
Inputs 3 numbers
Outputs the largest of the three numbers
[3]
Exemplar answer
Psuedocode
INPUT A
INPUT B
INPUT C
IF A > B
THEN
IF A > C
THEN
Page 14 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
OUTPUT A
ENDIF
ELSE
OUTPUT B
ENDIF
Python
print(A)
elif B > C:
print(B)
else:
print(C)
Page 15 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Iteration
Your notes
What is iteration?
Iteration is repeating a line or a block of code using a loop
Iteration can be:
Count controlled
Condition controlled
Nested
Page 16 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Examples
Iteration Pseudocode Python
NEXT X
OUTPUT X print(x)
OUTPUT X print(x)
Page 17 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
REPEAT
<statement>
UNTIL <condition>
UNTIL Guess ← 42
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
WHILE <condition> DO
<statements>
ENDWHILE
A detailed look at a Python WHILE statement:
Page 19 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
END WHILE
Nested Iteration
What is nested selection?
Nested iteration is a loop within a loop, e.g. a FOR inside of another FOR
Nested means to be 'stored inside the other'
Example
Pseudocode
Total ← 0
RowTotal ← 0
FOR Column ← 1 TO 10
NEXT Column
NEXT Row
Page 20 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Python
Your notes
// Program to print a multiplication table up to a given number
// Prompt the user to enter a number
number=int(input("Enter a number: "))
// Set the initial value of the counter for the outer loop
outer_counter = 1
// Set the initial value of the counter for the inner loop
inner_counter = 1
// Inner loop to print the multiplication table for the current number
while inner_counter <= 10:
Page 21 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Pseudocode Python
Total ← 0 total = 0
OUTPUT Total
Pseudocode Python
Count ← 0 count = 0
ENDIF
Page 22 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
NEXT I
WORKED EXAMPLE
Write an algorithm using pseudocode that:
Inputs 20 numbers
Outputs how many of these numbers are greater than 50
[3]
Answer
FOR x ← 1 TO 20 [1]
INPUT Number
IF Number > 50
THEN
NEXT x
Page 23 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
String Handling
Your notes
String Handling
What is string manipulation?
String manipulation is the use of programming techniques to modify, analyse or extract information
from a string
Examples of string manipulation include:
Case conversion (modify)
Length (analyse)
Substrings (extract)
Case conversion
The ability to change a string from one case to another, for example, lower case to upper case
Length
The ability to count the number of characters in a string, for example, checking a password meets the
minimum requirement of 8 characters
Page 24 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
ENDIF
Substring
The ability to extract a sequence of characters from a larger string in order to be used by another
function in the program, for example, data validation or combining it with other strings
Extracting substrings is performed using 'slicing', using specific start and end to slice out the desired
characters
Substring has a start position of 1 in pseudocode and 0 in Python
WORKED EXAMPLE
The function Length(x) finds the length of a string x. The function substring(x,y,z) finds a substring of x
starting at position y and z characters long. The first character in x is in position 1.
Write pseudocode statements to:
Store the string “Save my exams” in x
Find the length of the string and output it
Extract the word exams from the string and output it
[6]
Answer
Page 25 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
X ← "Save my exams"
[1] for calling the function length. [1] for using the correct parameter X
Y←9
Z←5
OUTPUT SUBSTRING(X,Y,Z)
Page 26 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Arithmetic Operators
Operator Pseudocode Python
Addition + +
Subtraction - -
Multiplication * *
Division / /
To demonstrate the use of common arithmetic operators, three sample programs written in Python are
given below
Comments have been included to help understand how the arithmetic operators are being used
Arithmetic operators #1 - a simple program to calculate if a user entered number is odd or even
Arithmetic operators #2 - a simple program to calculate the area of a circle from a user inputted
radius
Page 27 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Arithmetic operators #3 - a simple program that generates 5 maths questions based on user
inputs and gives a score of how many were correctly answered at the end
Your notes
Python code
# -----------------------------------------------------------------------
# Arithmetic operators #1
# -----------------------------------------------------------------------
# Get the user to input a number
user_input = int(input("Enter a number: "))
# -----------------------------------------------------------------------
# Arithmetic operators #2
# -----------------------------------------------------------------------
# Get the radius from the user
radius = float(input("Enter the radius of the circle: "))
# ------------------------------------------------------------------------
# Arithmetic operators #3
# ------------------------------------------------------------------------
# Set the score to 0
score = 0
# Loop 5 times
for x in range(5):
num1 = int(input("Enter the first number: "))
operator = input("Enter the operator (+, -, *): ")
num2 = int(input("Enter the second number: "))
user_answer = int(input("What is "+str(num1)+str(operator)+str(num2)+"? "))
Page 28 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Logical Operators
Operator Pseudocode Python
Equal to == ==
Boolean Operators
A Boolean operators is a logical operator that can be used to compare two or more values and return a
Boolean value (True or False) based on the comparison
There are 3 main Boolean values:
AND: Returns True if both conditions are True
OR: Returns True if one or both conditions are True
NOT: Returns the opposite of the condition (True if False, False if True)
To demonstrate the use of common Boolean operators, three sample programs written in Python are
given below
Page 29 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Comments have been included to help understand how the Boolean operators are being used
Common Boolean operators #1 - a simple program that assigns Boolean values to two variables Your notes
and outputs basic comparisons
Common Boolean operators #2 - a simple program to output a grade based on a users score
Common Boolean operators #3 - a simple program reads a text files and searches for an inputted
score
Python code
# -----------------------------------------------------------
# Common Boolean operators #1
# -----------------------------------------------------------
# Assign a Boolean value to a and b
a = True
b = False
# -----------------------------------------------------------
# Common Boolean operators #2
# -----------------------------------------------------------
# Take input for the score from the user
score = int(input("Enter the score: "))
# -----------------------------------------------------------
# Common Boolean operators #3
# -----------------------------------------------------------
# Open the file for reading
Page 30 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
file = open("scores.txt","r")
# Set flags to false
end_of_file = False Your notes
found = False
score = input("Enter a score: ")
# While it's not the end of the file and the score has not been found
while not end_of_file and not found:
# read the line
scores = file.readline().strip()
# if the line equals the score
if score == str(scores):
found = True
print("Score found")
# if the line is empty
if scores == "":
end_of_file = True
print("Score not found")
file.close()
EXAM TIP
Boolean operators are often used in conditional statements such as if, while, and for loops
Boolean operators can be combined with comparison operators
Be careful when using the NOT operator, as it can sometimes lead to unexpected results
It is always a good idea to test your code with different inputs to ensure that it works as
expected
Page 31 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Procedures
Procedures are defined using the PROCEDURE keyword in pseudocode or def keyword in Python
A procedure can be written as:
PROCEDURE <identifier>
<statements>
ENDPROCEDURE
Or if parameters are being used:
Page 32 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Pseudocode
END PROCEDURE
Python
def ageCheck(age):
else:
CALL <identifier>
CALL <identifier>(Value1,Value2...)
Calling a procedure
Pseudocode
CALL Calculate_area
CALL Calculate_area(5,3)
Python
Page 33 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
ageCheck(21)
Examples
A Python program using procedures to display a menu and navigate between them
Procedures are defined at the start of the program and the main program calls the first procedure to
start
In this example, no parameters are needed
Procedures
# Procedure definition
def main_menu():
# Procedure definition
def addition():
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print(num1 + num2)
Page 34 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
def subtraction():
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: ")) Your notes
print(num1 - num2)
def multiplication():
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print(num1 * num2)
def division():
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print(num1 / num2)
# Main program
main_menu() # Calls the main_menu procedure
Functions
Functions are defined using the FUNCTION keyword in pseudocode or def keyword in Python
Functions always return a value so they do not use the CALL function, instead they are called within an
expression
A function can be written as:
Pseudocode
Page 35 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
RETURN area
Python
def squared(number):
squared = number^2
return squared
Examples
A Python program using a function to calculate area and return the result
Two options for main program are shown, one which outputs the result (# 1) and one which stores the
result so that it can be used at a later time (# 2)
Functions
# Main program #1
length = int(input("Enter the length: "))
width = int(input("Enter the width: "))
print(area(length, width))
# Main program #2
length = int(input("Enter the length: ")) length
width = int(input("Enter the width: "))
area = area(length, width) # Stores the result of the function in a variable
print("The area is " + str(area) + " cm^2")
Page 36 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
WORKED EXAMPLE
Your notes
An economy-class airline ticket costs £199. A first-class airline ticket costs £595.
(A) Create a function, flightCost(), that takes the number of passengers and the type of ticket as
parameters, calculates and returns the price to pay.
You do not have to validate these parameters
You must use :
a high-level programming language that you have studied [4]
(B) Write program code, that uses flightCost(), to output the price of 3 passengers flying economy.
You must use :
a high-level programming language that you have studied [3]
How do I answer this question?
(A)
Define the function, what parameters are needed? where do they go?
How do you calculate the price?
Return the result
(B)
How do you call a function?
What parameters does the function need to return the result?
Answers
Part Python
if type == "economy":
return cost
B print(flightCost("economy", 3)
OR
x = flightCost("economy", 3)
Page 37 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
print(x)
Your notes
Page 38 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Python example
In this python code, you can see that the localVariable (with the value 10) is declared inside of the
function printValue
This means that only this function can access and change the value in the local variable
It cannot be accessed by other modules in the program
Local variables
def printValue():
localVariable = 10 # Defines a local variable inside the function
print("The value of the local variable is:", localVariable)
Global Variables
What is a global variable?
A global variable is a variable declared at the outermost level of a program.
They are declared outside any modules such as functions or procedures
Global variables have a global scope, which means they can be accessed and modified from any part
of the program
Python example
In this python code, you can see that the globalVariable (with the value 10) is declared outside of the
function printValue
Page 39 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
This means that this function and any other modules can access and change the value in the global
variable
Your notes
Global variables
def printValue():
global globalVariable
print("The value into the variable is:", globalVariable)
Page 40 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Library Routines
Your notes
Library Routines
What are library routines?
A library routine is reusable code that can be used throughout a program
The code has been made public through reusable modules or functions
Using library routines saves programmers time by using working code that has already been tested
Some examples of pre-existing libraries are:
Random
Round
Random
The random library is a library of code which allows users to make use of 'random' in their programs
Examples of random that are most common are:
Random choices
Random numbers
Random number generation is a programming concept that involves a computer generating a random
number to be used within a program to add an element of unpredictability
Examples of where this concept could be used include:
Simulating the roll of a dice
Selecting a random question (from a numbered list)
National lottery
Cryptography
number = random.randint(1,10)
Page 41 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
number = random.randint(-1.0,10.0)
Your notes
Random choice import random
choice = random.choice()
Examples in Python
Random code
National lottery
import random
Page 42 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
number = random.choice(lottery_numbers)
# Add the chosen number to the list of chosen numbers Your notes
chosen_numbers.append(number)
Round
The round library is a library of code which allows users to round numerical values to a set amount of
decimal places
An example of rounding is using REAL values and rounding to 2 decimal places
The round library can be written as:
ROUND(<identifier>, <places>)
Page 43 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Maintaining Programs
Your notes
Maintaining Programs
How do you write programs that are easy to maintain?
Easy to maintain programs are written using techniques that make code easy to read
Programmers should be consistent with the use of techniques such as:
Layout - spacing between sections
Indentation - clearly defined sections of code
Comments - explaining key parts of the code
Meaningful variable names - describe what is being stored
White space - adding suitable spaces to make it easy to read
Sub-programs - Functions or procedures used where possible
When consistency is applied, programs are easy to maintain
# -----------------------------------------------------------------------
"""
Calculates the area of a triangle given its base and height.
Inputs:
base (float): The length of the triangle's base (positive value).
height (float): The height of the triangle from the base (positive value).
Returns:
The calculated area of the triangle (float).
Raises:
ValueError: If either base or height is non-positive.
Page 44 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
"""
# ----------------------------------------------------------------------- Your notes
if base <= 0 or height <= 0:
return area
def main():
# -----------------------------------------------------------------------
# Prompts the user for triangle base and height, calculates and prints the area
# -----------------------------------------------------------------------
try:
print(f"Error: {error}")
# ------------------------------------------------------------------------
# Main program
# ------------------------------------------------------------------------
main()
Page 45 of 45
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers