0% found this document useful (0 votes)
22 views29 pages

CSC ch8

Uploaded by

Dilruba Hasin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views29 pages

CSC ch8

Uploaded by

Dilruba Hasin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Chapter 8 Programming

Variables & Constants

What is a variable?
 A variable is an identifier that can change in the lifetime of a program
 Identifiers should be:
o In mixed case (Pascal case)
o Only contain letters (A-Z, a-z)
o Only contain digits (0-9)
o Start with a capital letter and not a digit
 A variable can be associated a datatype when it is declared
 When a variable is declared, memory is allocated based on the data type
indicated
Pseudocode
DECLARE <identifier> : <datatype>
DECLARE Age : INTEGER
DECLARE Price : REAL
DECLARE GameOver : BOOLEAN
Python
score = int() # whole number
cost = float() # decimal number
light = bool() # data can only have one or two values

What is a constant?
 A constant is an identifier set once in the lifetime of a program
 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 <identifier> ← <value>
CONSTANT PI ← 3.142
CONSTANT PASSWORD ← "letmein"
CONSTANT HIGHSCORE ← 9999
Python
PI = 3.142
VAT = 0.20
PASSWORD = "letmein"

1|Page
Chapter 8 Programming

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:
Data type Used for Pseudocode Example
Integer Whole numbers INTEGER 10, -5, 0
Numbers with a fractional part
Real REAL 3.14, -2.5, 0.0
(decimal)
Character Single character CHAR 'a', 'B', '6', '£'
"Hello world", "ABC",
String Sequence of characters STRING
"@#!%"
Boolean True or false values BOOLEAN True, False
 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

Programming data types


Data type Pseudocode Python
Integer Number ← 5 number = 5
Real RealNumber ← 3.14 realNumber = 3.14
Character FirstNameInitial ← "a" firstNameInitial = "a"
String Password ← "letmein" password = "letmein"
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]

2|Page
Chapter 8 Programming

Input & Output

What is an input?
 An input is a value that is read from an input device and then processed by a
computer program
 Typical input devices include:
o Keyboards - Typing text
o Mice - Selecting item, clicking buttons
o Sensors - Reading data from sensors such as temperature, pressure or
motion
o Microphone - Capturing audio, speech recognition
 Without inputs, programs are not useful as they can't interact with the
outside world and always produce the same result
 In programming the keyboard is considered the standard for user input
 If the command 'INPUT' is executed, a program will wait for the user to type
a sequence of characters
 In other programming languages different command words can be used

Examples
Pseudocode (INPUT <identifier>) Python
name=input("Enter your name:
INPUT Name
")
IF Name ← "James" OR Name ←
if name == "James" or name
"Rob" THEN...
== "Rob":
What is an output?
 An output is a value sent to an output device from a computer program
 Typical output devices include:
o Monitor - Displaying text, images or graphics
o Speaker - Playing audio
o Printer - Creating physical copies of documents or images
 In programming the monitor is considered the standard for user output
 If the command 'OUTPUT' is executed, a program will output to the screen
 In other programming languages different command words can be used
Examples
Pseudocode (OUTPUT <identifier(s)>) Python
name=input("Enter your name:
INPUT Name
")
IF Name ← "James" OR Name ←
if name == "James" or name ==
"Rob" THEN
"Rob":
OUTPUT "Great names!"
print("Great names!")
INPUT Name name=input("Enter your name:
IF Name ← "James" OR Name ← ")
"Rob" THEN if name == "James" or name ==
OUTPUT "Love the name ", "Rob":
Name print("Love the name "+name)

3|Page
Chapter 8 Programming

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
01 OUTPUT "Enter the first number"
02 INPUT Num1
03 OUTPUT "Enter the second number"
04 INPUT Num2
05 Result ← Num1 - 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
def calculate_area(length, width):
"""
This function calculates the area of a rectangle
Inputs:
length: The length of the rectangle
width: The width of the rectangle
Returns:
The area of the rectangle
"""
# Calculate area
return area
area = length * width
# ------------------------------------------------------------------------# Main program
# ------------------------------------------------------------------------
length = 5
width = 3
correct_area = calculate_area(length, width)
print(f"Correct area (length * width): {correct_area}")
 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

4|Page
Chapter 8 Programming

 The correct sequence is:


# Calculate area
area = length * width
return area

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:
o if... then... else...
o 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

Example
Concept Pseudocode Python
IF Answer ← "Yes" if answer == "Yes":
THEN print("Correct")
OUTPUT "Correct" elif answer == "No":
IF-THEN-ELSE ELSE print("Wrong")
OUTPUT "Wrong" else:
ENDIF print("Error")

Nested Selection
What is nested selection?
 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'

Example
Pseudocode
IF Player2Score > Player1Score
THEN
IF Player2Score > HighScore
THEN
OUTPUT Player2, " is champion and highest scorer"
ELSE

5|Page
Chapter 8 Programming

OUTPUT Player2, " is the new champion"


ENDIF
ELSE
OUTPUT Player1, " is still the champion"
IF Player1Score > HighScore
THEN
OUTPUT Player1, " is also the highest scorer"
ENDIF
ENDIF
Python
// Prompt the user to enter a number
print("Enter a number: ")
test_score = int(input())
// Outer statement to check the test_score is above 40
if test_score > 40:
// Inner statement to assign the result from the test
if test_score > 70:
result = "Distinction"
elif test_score > 55:
result = "Merit"
elif test_score > 40:
result = "Pass
else:
result = "Fail"
// Output the result
print(result)

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

Concept Pseudocode Python


CASE INPUT Move match day:
CASE OF Move case "Sat":
'W' : Posistion ← Posistion - 10 print("Saturday")

6|Page
Chapter 8 Programming

'E' : Posistion ← Posistion + 10


case "Sun":
'A' : Posistion ← Posistion - 1
print("Sunday")
'D' : Posistion ← Posistion + 10
case _:
OTHERWISE OUTPUT "Beep"
print("Weekday")
ENDCASE

Examiner Tip
 Make sure to include all necessary components in the selection statement:

o the condition,

o the statement(s) to execute when the condition is true

o 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
OUTPUT A
ELSE
OUTPUT C
ENDIF
ELSE
OUTPUT B
ENDIF
Python
if A > B AND A > C:
print(A)
elif B > C:
print(B)
else:

7|Page
Chapter 8 Programming

print(C)

8|Page
Chapter 8 Programming

What is iteration?
 Iteration is repeating a line or a block of code using a loop
 Iteration can be:
o Count controlled
o Condition controlled
o Nested

Count Controlled Loops

What is a count controlled loop?


 A count controlled loop is when the code is repeated a fixed number of
times (e.g. using a for loop)
 A count controlled loop can be written as:
FOR <identifier> ← <value1> TO <value2>
<statements>
NEXT <identifier>
 Identifiers must be an integer data type
 It uses a counter variable that is incremented or decremented after each
iteration
 This can be written as:
FOR <identifier> ← <value1> TO <value2> STEP <increment>
<statements>
NEXT <identifier>

Examples
Iteration Pseudocode Python
FOR X ← 1 TO 10
for x in range(10):
OUTPUT "Hello"
print("Hello")
NEXT X
This will print the word "Hello" 10 times
FOR X ← 2 TO 10 STEP for x in range(2,12,2):
2 print(x)
Count OUTPUT X # Python range function excludes end
controlled NEXT X value
This will print the even numbers from 2 to 10 inclusive
FOR X ← 10 TO 0 STEP for x in range(10,-1,-1):
-1 print(x)
OUTPUT X # Python range function excludes end
NEXT X value
This will print the numbers from 10 to 0 inclusive

9|Page
Chapter 8 Programming

Condition Controlled Loops

What is a condition controlled loop?


 A condition controlled loop is when the code is repeated until a condition is
met
 There are two types of condition controlled loops:
o Post-condition (REPEAT)
o Pre-condition (WHILE)
Post-condition loops (REPEAT)
 A post-condition loop is executed at least once
 The condition must be an expression that evaluates to a Boolean (True/False)
 The condition is tested after the statements are executed and only stops once
the condition is evaluated to True
 It can be written as:
REPEAT
<statement>
UNTIL <condition>
Iteration Pseudocode Python
REPEAT
INPUT Colour # NOT USED IN PYTHON
UNTIL Colour ← "red"
Post-condition
REPEAT
INPUT Guess # NOT USED IN PYTHON
UNTIL Guess ← 42

Pre-condition loops (WHILE)


 The condition must be an expression that evaluates to a Boolean (True/False)
 The condition is tested and statements are only executed if the condition
evaluates to True
 After statements have been executed the condition is tested again
 The loop ends when the condition evaluates to False
 It can be written as:
WHILE <condition> DO
<statements>
ENDWHILE
Iteration Pseudocode Python
WHILE Colour !=
"Red" DO while colour != "Red":
INPUT Colour colour = input("New colour")
ENDWHILE
temperature =
INPUT Temperature
Pre- float(input("Enter temperature:
WHILE Temperature
condition "))
> 37 DO
while temperature > 37:
OUTPUT "Patient
print("Patient has a fever")
has a fever"
temperature =
INPUT temperature
float(input("Enter temperature:
END WHILE
"))

10 | P a g e
Chapter 8 Programming

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
FOR Row ← 1 TO MaxRow
RowTotal ← 0
FOR Column ← 1 TO 10
RowTotal ← RowTotal + Amount[Row, Column]
NEXT Column
OUTPUT "Total for Row ", Row, " is ", RowTotal
Total ← Total + RowTotal
NEXT Row
OUTPUT "The grand total is ", Total
Python
// 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
// Outer loop to iterate through the multiplication table
while outer_counter <= number:
// 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:
// Calculate the product of the outer and inner counters
product = outer_counter * inner_counter
// Print the multiplication table entry
print(outer_counter, " x ", inner_counter, " = ",
product)
// Increment the inner counter
inner_counter = inner_counter + 1
// Move to the next number in the multiplication table
outer_counter = outer_counter + 1

Totalling & Counting

How do you use totalling in a program?


 Totalling involves adding up values, often in a loop
 A total variable is set to 0 at the beginning of the program and then updated
within a loop, such as:
Pseudocode Python
Total ← 0 total = 0
FOR I ← 1 to 10 for i in range(1, 11):

11 | P a g e
Chapter 8 Programming

INPUT Num
num = int(input("Enter a number: "))
TOTAL ← TOTAL + Num
total = total + num
NEXT I
print("Total:", total)
OUTPUT Total

How do you use counting in a program?


 Counting involves keeping track of the number of times a particular event
occurs
 A count variable is set to 0 and then updated within a loop, such as:
Pseudocode Python
Count ← 0
FOR I ← 1 to 10
count = 0
INPUT Num
for i in range(1, 11):
IF Num > 5
num = int(input("Enter a number: "))
THEN
if num > 5:
Count ← Count + 1
count = count + 1
ENDIF
print("Count:", count)
NEXT I
OUTPUT Count
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
Total ← Total + 1 [1]
NEXT x
PRINT total [1]

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:
o Case conversion (modify)
o Length (analyse)
o Substrings (extract)
Case conversion: The ability to change a string from one case
to another, for example, lower case to upper case
Function Pseudocode Python Output
Name ← "Sarah" Name = "Sarah"
Uppercase OUTPUT UCASE(Name) print(Name.upper()) "SARAH"

12 | P a g e
Chapter 8 Programming

Name ← "SARAH" Name = "SARAH"


Lowercase OUTPUT LCASE(Name) print(Name.lower()) "sarah"
Length: The ability to count the number of characters in a
string, for example, checking a password meets the minimum
requirement of 8 characters
Pseudocode Python Output
Password ← "letmein"
Password = "letmein"
OUTPUT 7
print(len(Password))
LENGTH(Password)
Password ← "letmein"
IF LENGTH(Password) >=
Password = "letmein"
8
if len(Password) >= 8:
THEN
print("Password
OUTPUT "Password "Password too
accepted")
accepted" short"
else:
ELSE
print("Password too
OUTPUT "Password too
short")
short"
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
Pseudocode Python Output
Word ← "Revision" Word = "Revision"
OUTPUT SUBSTRING(Word, 1, 3) print(Word[0:2]) "Rev"
Word ← "Revision" Word = "Revision"
OUTPUT SUBSTRING(Word, 3, 6) print(Word[2:5]) "visi"

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
X ← "Save my exams"
[1] for storing string in X
OUTPUT LENGTH(X)

13 | P a g e
Chapter 8 Programming

[1] for calling the function length. [1] for using the correct parameter X
Y ← 9
Z ← 5
OUTPUT SUBSTRING(X,Y,Z)
[1] for using the substring function.
[1] for correct parameters
[1] for outputting length and substring return values

What is an operator?
 An operator is a symbol used to instruct a computer to perform a specific
operation on one or more values
 Examples of common operators include:
o Arithmetic
o Logical
o Boolean
Arithmetic Operators
Operator Pseudocode Python
Addition + +
Subtraction - -
Multiplication * *
Division / /
Modulus (remainder after division) MOD %
Quotient (whole number division) DIV //
Exponentiation (to the power of) ^ **
 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
o Arithmetic operators #1 - a simple program to calculate if a user
entered number is odd or even
o Arithmetic operators #2 - a simple program to calculate the area of a
circle from a user inputted radius
o 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
Python code
# -----------------------------------------------------------------------
# Arithmetic operators #1
# -----------------------------------------------------------------------
# Get the user to input a number
user_input = int(input("Enter a number: "))
# if the remainder of the number divided by 2 is 0, the number is even
if user_input % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
# -----------------------------------------------------------------------
# Arithmetic operators #2
# -----------------------------------------------------------------------

14 | P a g e
Chapter 8 Programming

# Get the radius from the user


radius = float(input("Enter the radius of the circle: "))
# Calculate the area of the circle
area = 3.14159 * radius ** 2
# Display the calculated area
print("The area of the circle with
radius",radius,"is",area)
# ------------------------------------------------------------------------
# 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)+"? "))
# Check the answer and update the score
if operator == '+':
correct_answer = num1 + num2
elif operator == '-':
correct_answer = num1 - num2
elif operator == '*':
correct_answer = num1 * num2
if user_answer == correct_answer:
score = score + 1
else:
print("Sorry that's incorrect.")
print("Your score is:", score)

Logical Operators
Operator Pseudocode Python
Equal to == ==
Not equal to <> !=
Less than < <
Less than or equal to <= <=
Greater than > >
Greater than or 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:
o AND: Returns True if both conditions are True
o OR: Returns True if one or both conditions are True
o NOT: Returns the opposite of the condition (True if False, False if
True)

15 | P a g e
Chapter 8 Programming

 To demonstrate the use of common Boolean operators, three sample programs


written in Python are given below
 Comments have been included to help understand how the Boolean operators
are being used
o Common Boolean operators #1 - a simple program that assigns
Boolean values to two variables and outputs basic comparisons
o Common Boolean operators #2 - a simple program to output a grade
based on a users score
o 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
# print the result of a and b
print("a and b:", a and b)
# print the result of a or b
print("a or b:", a or b)
# print the result of not a
print("not a:", not a)
# -----------------------------------------------------------
# Common Boolean operators #2
# -----------------------------------------------------------
# Take input for the score from the user
score = int(input("Enter the score: "))
# Compare the score and output the corresponding grade
if score >= 90 and score <= 100:
print("Grade: A")
elif score >= 80 and score < 90:
print("Grade: B")
elif score >= 70 and score < 80:
print("Grade: C")
elif score < 70:
print("Fail")
# -----------------------------------------------------------
# Common Boolean operators #3
# -----------------------------------------------------------
# Open the file for reading
file = open("scores.txt","r")
# Set flags to false
end_of_file = False
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()

16 | P a g e
Chapter 8 Programming

# 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()

Examiner 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

What are functions and procedures?


 Functions and procedures are a type of sub program, a sequence of
instructions that perform a specific task or set of tasks
 Procedures and functions are defined at the start of the code
 Sub programs are often used to simplify a program by breaking it into
smaller, more manageable parts
 Sub programs can be used to:
o Avoid duplicating code and can be reused throughout a program
o Improve the readability and maintainability of code
o Perform calculations, to retrieve data, or to make decisions based on
input
 Parameters are values that are passed into a sub program
o Parameters can be variables or values and they are located in
brackets after the name of the sub program
o Example: FUNCTION
TaxCalculator(pay,taxcode) OR PROCEDURE
TaxCalculator(pay,taxcode)
 Sub programs can have multiple parameters
 To use a sub program you 'call' it from the main program
What's the difference between a function and procedure?
 A Function returns a value whereas a procedure does not

17 | P a g e
Chapter 8 Programming

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:

PROCEDURE <identifier>(<param1>:<data type>, <param2>:<data


type>...)
<statements>
ENDPROCEDURE

Creating a procedure
Pseudocode
PROCEDURE calculate_area(length: INTEGER, width: INTEGER)
area ← length * width
OUTPUT "The area is " + area
END PROCEDURE
Python
def ageCheck(age):
if age > 18:
print("You are old enough")
else:
print("You are too young")
 To call a procedure, it can be written as:

CALL <identifier>
CALL <identifier>(Value1,Value2...)
Calling a procedure
Pseudocode
CALL Calculate_area
CALL Calculate_area(5,3)
Python
ageCheck(21)
print(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():

18 | P a g e
Chapter 8 Programming

# Outputs the option


print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
# Asks the user to enter their choice
choice = int(input("Enter your choice: "))
if choice == 1:
addition()
elif choice == 2:
subtraction()
elif choice == 3:
multiplication()
elif choice == 4:
division()
elif choice == 5:
exit()
# Procedure definition
def addition():
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print(num1 + num2)
def subtraction():
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
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:

FUNCTION <identifier> RETURNS <data type>


<statements>
ENDFUNCTION
 Or if parameters are being used:

19 | P a g e
Chapter 8 Programming

FUNCTION <identifier>(<param1>:<data type>, <param2>:<data


type>...) RETURNS <data type>
<statements>
ENDFUNCTION
Creating and using a function
Pseudocode
FUNCTION calculate_area(length: INTEGER, width: INTEGER)
area ← length * width
RETURN area
ENDFUNCTION
// Output the value returned from the function
OUTPUT(calculate_area(5,3))
Python
def squared(number):
squared = number^2
return squared
// Output the value returned from the function
print(squared(4))
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
# Function definition, length and width are parameters
def area(length, width):
area = length * width # Calculate area
return area # Return area
# 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")
Worked Example
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?

20 | P a g e
Chapter 8 Programming

(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
def flightCost(passengers, type):
if type == "economy":
cost = 199 * passengers
A elif type == "first":
cost = 595 * passengers
return cost
print(flightCost("economy", 3)
OR
B x = flightCost("economy", 3)
print(x)

Local Variables

What is a local variable?


A local variable is a variable declared within a specific scope, such as a

function or a code block
 Local variables are accessible only within the block in which they are
defined, and their lifetime is limited to that particular block
 Once the execution of the block ends, the local variable is destroyed, and
its memory is released
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)
printValue() # Call the function

21 | P a g e
Chapter 8 Programming

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
 This means that this function and any other modules can access and change
the value in the global variable
Global variables
globalVariable = 10 # Defines a global variable
def printValue():
global globalVariable
print("The value into the variable is:",
globalVariable)
printValue() # Call the function

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:
o Random
o 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:
o Random choices
o 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:
o Simulating the roll of a dice
o Selecting a random question (from a numbered list)
o National lottery
o Cryptography

22 | P a g e
Chapter 8 Programming

Concept Pseudocode Python


import random
Random number = random.randint(1,10)
RANDOM(1,6)
numbers number = random.randint(-
1.0,10.0)
import random
Random choice choice = random.choice()
Examples in Python
Random code
# importing random library
import random
# asking user to enter a username and password
user = input("Enter a username: ")
pw = input("Enter a password: ")
# checking if the user and password are correct
if user == "admin" and pw == "1234":
# generating a random 4 digit code
code = random.randint(1000,9999)

print("Your code is", code)


National lottery
import random
# Create a list of numbers for the national lottery
lottery_numbers = list(range(1, 50))
# Create an empty list to store the chosen numbers
chosen_numbers = []
# Loop to pick 6 numbers from the list
for _ in range(6):
# Use random.choice to pick a number from the list
number = random.choice(lottery_numbers)
# Add the chosen number to the list of chosen numbers
chosen_numbers.append(number)
# Remove the chosen number from the list of available numbers
lottery_numbers.remove(number)
# Sort the chosen numbers in ascending order
chosen_numbers.sort()
# Output the chosen numbers
print("The winning numbers are:", chosen_numbers)

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>)

23 | P a g e
Chapter 8 Programming

Concept Pseudocode Python


Cost ← 1.9556 number = 3.14159 rounded_number =
OUTPUT round(number, 2)
Round ROUND(Cost,2) print(rounded_number)
// Outputs 1.95 // Outputs 3.14

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:
o Layout - spacing between sections
o Indentation - clearly defined sections of code
o Comments - explaining key parts of the code
o Meaningful variable names - describe what is being stored
o White space - adding suitable spaces to make it easy to read
o Sub-programs - Functions or procedures used where possible
 When consistency is applied, programs are easy to maintain

1-Dimensional Arrays

What is an array?
 An array is an ordered, static set of elements in a fixed-size memory location
 An array can only store 1 data type
 A 1D array is a linear array
 Indexes start at generally start at 0, known as zero-indexed
Concept Pseudocode Python
DECLARE scores:
scores = []
ARRAY[0:4]OF INTEGER
Creates a blank array with 5 elements
Creates a blank array
Create (0-4)
scores = [12, 10, 5,
scores ← [12, 10, 5, 2, 8]
2, 8]
Creates an array called scores with values assigned
colours[4] ← "Red" colours[4] = "Red"
Assignment
Assigns the colour "Red" to index 4 (5th element)
Example in Python
Creating a one-dimensional array called ‘array’ which contains 5 integers.
 Create the array with the following syntax:
array = [1, 2, 3, 4, 5]
 Access the individual elements of the array by using the following syntax:
array[index]
 Modify the individual elements by assigning new values to specific indexes
using the following syntax:
array[index] = newValue

24 | P a g e
Chapter 8 Programming

 Use the len function to determine the length of the array by using the
following syntax:
len(array)
 In the example the array has been iterated through to output each element
within the array. A for loop has been used for this
Python
# Creating a one-dimensional array
array = [1, 2, 3, 4, 5]
# Accessing elements of the array
print(array[0]) # Output: 1
print(array[2]) # Output: 3
# Modifying elements of the array
array[1] = 10
print(array) # Output: [1, 10, 3, 4, 5]
# Iterating over the array
for element in array:
print(element)
# Output:
# 1
# 10
# 3
# 4
# 5
# Length of the array
length = len(array)
print(length) # Output: 5

2-Dimensional Arrays

What is a 2-dimensional array?


 A 2D array extends the concept on a 1D array by adding another dimension
 A 2D array can be visualised as a table with rows and columns
 When navigating through a 2D array you first have to go down the rows and
then across the columns to find a position within the array
Concept Pseudocode Python
Create DECLARE
NamesAndNumbers :
NamesAndNumbers = [],[]
ARRAY[1:3, 1:3] OF
STRING
Creates a blank 2D array
Creates a blank 2D array
with 3 elements (0-2)
NamesAndNumbers[1, NamesAndNumbers =
2] ← "John" ["Rob","Paul","Hayley"],[10,
NamesAndNumbers[1, 5, 8]
3] ← "Emily"
NamesAndNumbers[2,
1] ← "25"
NamesAndNumbers[2,
2] ← "33"

25 | P a g e
Chapter 8 Programming

NamesAndNumbers[2,
3] ← "19"
NamesAndNumbers[3,
1] ← "Sarah"
NamesAndNumbers[3,
2] ← "12"
NamesAndNumbers[3,
3] ← "8"
Creates a 2D array called players with values assigned
NamesAndNumbers[0,1] NamesAndNumbers[0][1] =
← "Holly" "Holly"
Assignment
Assigns the name "Holly" to index 0, 1 (1st row, 2nd column) -
replaces "Paul"
Example in Python
Python
# Initialising a 2D array with 3 rows and 3 columns, with
the specified values
array_2d = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Accessing elements in the 2D array
print(array_2d[0][0]) # Output: 1
print(array_2d[1][2]) # Output: 6
Iterating through a 2-dimensions array
 When iterating through an array, a nested for loop can be used
Python
# Nested iteration to access items in the 2D array
for row in array_2d:
for item in row:
print(item, end=" ")
print() # Print a newline after each row
Examiner Tip
In the exam, the question will always give an example to demonstrate which
order the array is being read from.

Some questions can be X,Y and others can be Y, X. Always refer to the example
before giving your answer!

Worked Example
A parent records the length of time being spent watching TV by 4 children

Data for one week (Monday to Friday) is stored in a 2D array with the
identifier minsWatched.

The following table shows the array

Quinn Lyla Harry Elias


0 1 2 3
Monday 0 34 67 89 78

26 | P a g e
Chapter 8 Programming

Tuesday 1 56 43 45 56
Wednesday 2 122 23 34 45
Thursday 3 13 109 23 90
Friday 4 47 100 167 23
Write a line of code to output the number of minutes that Lyla watched TV on
Tuesday [1]

Write a line of code to output the number of minutes that Harry watched TV on
Friday [1]

Write a line of code to output the number of minutes that Quinn watched TV on
Wednesday [1]

Answers

 print(minsWatched[1,1] or print(minsWatched[1][1]

 print(minsWatched[2,4] or print(minsWatched[2][4]

 print(minsWatched[0,2] or print(minsWatched[0][2]

File Handling

What is file handling?


 File handling is the use of programming techniques to work with
information stored in text files
 Examples of file handing techniques are:
o opening text files
o reading text files
o writing text files
o closing text files
Concept OCR exam reference Python
OPENFILE "fruit.txt" file =
Open FOR READ open("fruit.txt","r")
Close CLOSEFILE "fruit.txt" file.close()
READFILE "fruit.txt",
Read line LineOfText file.readline()
OPENFILE "fruit.txt"
FOR WRITE
Write line WRITEFILE file.write("Oranges")
"fruit.txt",
"Oranges"
Append a OPENFILE "fruit.txt" file =
file FOR APPEND open("shopping.txt","a")
Python example (reading data)
Employees Text file
file = open("employees.txt", "r") # open file Greg
in read mode Sales

27 | P a g e
Chapter 8 Programming

endOfFile = False # set end of file to false


while not endOfFile: # while not end of file
name = file.readline() # read line 1 39000
department = file.readline() # read line 2 43
salary = file.readline() # read line 3 Lucy
age = file.readline() # read line 4 Human
print("Name: ", name) # print name resources
print("Department: ", department) # print 26750
department 28
print("Salaray: ", salary) # print salary Jordan
print("age: ", age) # print age Payroll
45000
if name == "": # if name is empty 31
endOfFile = True # set end of file to true
file.close() # close file
Python example (writing new data)
Employees
Greg
Sales
39000
43
Lucy
file = open("employees.txt", "a") # open file
Human
in append mode
resources
file.write("Polly\n") # write line (\n for new
line) 26750
file.write("Sales\n") 28
file.write("26000\n") Jordan
file.write("32\n") Payroll
file.close() # close file 45000
31
Polly
Sales
26000
32
Examiner Tip
When opening files it is really important to make sure you use the correct letter
in the open command

 "r" is for reading from a file only

 "w" is for writing to a new file, if the file does not exist it will be created.
If a file with the same name exists the contents will be overwritten

 "a" is for writing to the end of an existing file only

Always make a backup of text files you are working with, one mistake and you
can lose the contents!

Worked Example
Use pseudocode to write an algorithm that does the following:

28 | P a g e
Chapter 8 Programming

 Inputs the title and year of a book from the user.


 Permanently stores the book title and year to the existing text file books.txt [4]
How to answer this question
 Write two input statements (title and year of book)
 Open the file
 Write inputs to file
 Close the file
Example answer
title = input("Enter title")
year = input("Enter year")
file = open("books.txt")
file.writeline(title)
file.writeline(year)
file.close()
Guidance
 title = input("Enter title") 1 mark for both
year = input("Enter year")
 file = open("books.txt") 1 mark
 file.writeline(title) 1 mark for both
 file.writeline(year)
 file.close() 1 mark

29 | P a g e

You might also like