Basics
Production
Computer systems
Advanced
Outcome 1 - Understanding how computers and software work
Read and explain code
Describe the purpose of programming constructs and how they work
Describe a range of standard algorithms and how they work
Describe how software relates to the way computers work
Outcome 2 - Develop modular programs
Apply contemporary design methodologies
Selecting and using appropriate constructs
Selecting and using appropriate simple (primitive) and structured data types such as 1-D arrays
Testing digital solutions systematically
Applying good programming technique such as meaningful variable names, internal commentary and indentation
Do these individually.
Whilst we all arrive at the same solution (i.e. we have a cup of tea), we can have different ways of doing it
Do these individually.
For this course we will be using the Python programming language and the PHP programming language.
def findMaximum(l):
i = 0
max = l[0]
while (i < len(l)):
if l[i] > max:
max = l[i]
i = i + 1
return max
scores = [53, 12, 95]
print(findMaximum(scores))
function findMaximum(l):
$i = 0
$max = l[0]
while ($i < count($l)):
if $l[$i] > $max:
$max = $l[$i]
$i = $i + 1
return $max
$scores = [53, 12, 95]
print(findMaximum($scores))
What did it ask you to do when you pressed run?
print("Hello world")
print("Hello world")
What did it ask you to do when you pressed run?
print("Hello world")
What did it ask you to do when you pressed run?
print
function:print("Hello world!")
print("Hello", "world")
echo
keyword:echo "Hello world!";
input
function:print("Please insert your name")
print(input())
readline
function to get the user input:echo 'Please insert a value';
echo readline();
<form method="post" action="process.php">
<input name="username">
<input type="submit">
</form>
echo $_POST['username'];
HTML
PHP
echo $_GET['username'];
PHP
https://www.example.com/?username=peter
Open Python IDLE:
Write a program to display "Hello" and the users name which you have asked for.
Do the same in PHP.
Maths symbol | Python symbol | Purpose |
---|---|---|
+ | + | Addition |
- | - | Subtraction |
× | * | Multiplication |
÷ | / | Divide |
What will this display?
print(5 + 5 * 2 / 4)
A variable is a letter which represents an unknown number. For example in the expression
5 = x + 2, x is a variable
A definition from maths
A variable is like a container with a name on it. Values are put into and taken out of this container as needed.
A computing way of thinking
x = 10
y = 2
z = x + y
$
sign in front of an identifier string:$x = 10;
$y = 2;
$z = $x + $y;
print("Please insert your name")
fullName = input()
echo "Please insert your name";
$fullName = readline();
A data type is the type of the data you are storing in a variable.
For instance, when we are storing a number using the int(input()) function we are getting an integer.
Python has 5 data types we need to know about.
Name | Description | Example |
---|---|---|
Integer | Whole numbers | 1, 200, -128, 5 |
Float | Numbers with decimal places, numbers with exponents (power of) | 6.23, 5.00, -3.14 |
Char | A single character from the keyboard (note the quotes) | "Y", "N", "O", "1", "@" |
String | Multiple characters (note the quotes) | "Hello world", "Mr Balfour", "Computing" |
Boolean | Either true or false | True, False |
Python also treats characters (or chars) as strings when finding the data type of a variable, but it doesn't treat them the same when using functions on characters.
Name | Description | Example |
---|---|---|
Integer | Whole numbers | 1, 200, -128, 5 |
Float | Numbers with decimal places, numbers with exponents (power of) | 6.23, 5.00, -3.14 |
Char | A single character from the keyboard (note the quotes) | "Y", "N", "O", "1", "@" |
String | Multiple characters (note the quotes) | "Hello world", "Mr Balfour", "Computing" |
Boolean | Either true or false | True, False |
print("Please a number")
x = input()
y = x + 5
print("Please a number")
x = int(input())
y = x + 5
echo "Please insert a number";
$x = readline();
$y = $x + 5
echo "Please insert a number";
$x = (int) readline();
$y = $x + 5;
bool
str
int
float
a = bool(int(input()))
b = str(input())
c = int(input())
d = float(input())
Note the bool
casting function will convert everything to True, except the number 0.
bool
string
int
float
array
object
unset
$a = (bool) readline();
$b = (string) readline();
$c = (int) readline();
$d = (float) readline();
$e = (array) readline();
$f = (object) readline();
$g = (unset) readline();
Note the bool
casting function will convert everything to True, except the number 0.
type
function can determine a type of a value or variable.a = bool(int(input()))
b = str(input())
c = int(input())
d = float(input())
print(type(a))
print(type(b))
print(type(c))
print(type(d))
type
function can determine a type of a value or variable.$a = (bool) readline();
$b = (string) readline();
$c = (int) readline();
$d = (float) readline();
echo get_type($a);
echo get_type($b);
echo get_type($c);
echo get_type($d);
Using Python and PHP on your computers, create a variable with each data type discussed in it by using casting to ensure that the value is converted to the correct data type.
Use the type
and get_type
functions to check the data type is correct.
Below is a program for checking if the user can drive or not Python
age = int(input())
if age > 16:
print("You are old enough to drive")
It does not, however, tell the user if they cannot drive...
Below is a program for checking if the user can drive or not Python
age = int(input())
if age > 16:
print("You are old enough to drive")
else:
print("You are too young to drive")
This version now tells if we cannot drive by using else
.
Don't forget the :
symbol at the end of the condition and after the else
keyword.
Below is a program for checking if the user can drive or not in PHP
$age = (int) readline();
if ($age > 16) {
echo "You are old enough to drive";
} else {
echo "You are too young to drive";
}
With PHP, note the importance of the brackets after the if as, unlike Python, PHP will not compile without them.
We also don't use a :
symbol at the end of the condition, instead we contain the code routes within the {
and }
symbols.
x > 10
, or it could be simply True
or similar.Comparator | Explanation | Example | Example explanation |
---|---|---|---|
== | Equal to | IF A == B | Checks if A is equal to B |
> | Greater than | IF A > B | Checks if A is greater than B |
< | Less than | IF A < B | Checks if A is less than B |
!= | Not equal to | IF A != B | Checks if A is not equal to B |
>= | Greater than or equal to | IF A >= B | Checks if A is greater than or equal to B |
<= | Less than or equal to | IF A <= B | Checks if A is less than or equal to B |
print("Please insert your username")
username = input()
print("Please insert your password")
password = input()
if username == "Hamish" and password == "pass":
print("Welcome!")
else:
print("Login incorrect")
echo "Please insert your username";
$username = readline();
echo "Please insert your password";
$password = readline();
if ($username == "Hamish" && $password == "pass") {
echo "Welcome!";
} else {
echo "Login incorrect";
}
Write a program that does each of the following:
n = 0
print(n)
n = n + 1
print(n)
n = n + 1
print(n)
n = n + 1
print(n)
n = n + 1
$n = 0;
echo $n;
$n = $n + 1
echo $n;
$n = $n + 1
echo $n;
$n = $n + 1
echo $n;
$n = $n + 1
n = 0
for i in range(0, 4):
print(n)
n = n + 3
$n = 0;
for ($i = 0; $i < 4; $i++){
echo $n;
$n = $n + 3;
}
for num1 in range(0, 5):
for num2 in range(0, 5):
print(num1, num2)
for ($num1 = 0; $num1 < 5; $num1++){
for ($num2 = 0; $num2 < 5; $num2++){
echo $num1 . ' ' . $num2;
}
}
99 Bottles of beer on the wall, 99 bottles of beer.
If one should happen to fall, 98 bottles of beer on the wall.
For each of the following, state whether it is true or false:
x = True
y = False
print(x and y)
x = 54
y = 24
print(x > y)
x = 54
y = 24
print(x < y or y > 5)
x = True
y = True
print(not(x or y))
while True:
print("This loop is never gonna end!")
n = 0
while n < 100:
print(n)
n = n + 1
while (true) {
echo "This loop is never gonna end!";
}
$n = 0;
while ($n < 100) {
echo $n;
$n = $n + 1;
}
print("Please insert your username")
username = input()
print("Please insert your password")
password = input()
attempts = 0
while username != "Hamish" and password != "pass":
print("Login incorrect")
print("Please insert your username")
username = input()
print("Please insert your password")
password = input()
attempts = attempts + 1
print("Welcome", "It took you", attempts, "to login")
echo "Please insert your username";
$username = readline();
echo "Please insert your password";
$password = readline();
$attempts = 0;
while ($username != "Hamish" && $password != "pass") {
echo "Login incorrect";
echo "Please insert your username";
$username = readline();
echo "Please insert your password";
$password = readline();
$attempts = $attempts + 1;
}
echo "Welcome", "It took you", attempts, "to login";
Complete the Conditional Loops worksheet
Write a quiz program that loops until the user types the correct answer. Count the number of times it takes before the user types in the correct answer.
Write a program where the user has to guess a number that has been defined within the code. If the user guesses too high, the program should suggest they should guess lower. If the user guesses too low, the program should suggest they should guess higher. The program should display a congratulations message when the user guesses the correct number.
Describe, use and exemplify several data types
Describe and use 1D arrays
An array is a data structure.
Arrays let programmers store ‘lists’ of related data in one data structure.
For example, we could use an array to store pupil marks.
Each value in a list is given its own position/index value so it can easily be referenced.
Arrays can be assigned to variables.
Often a program will have to store lots of information at the one time, for example, when a teacher is entering in the names of all their pupils. It is unrealistic to have a separate variable for each of the names (StudentName1, StudentName2….etc).
Arrays allow the programmer to store more than one piece of data within a single data structure.
The element data type can be integers, reals, Booleans, characters or string
strings = [""] * 5
integers = [0] * 5
reals = [0.0] * 5
booleans = [False] * 5
characters = [""] * 5
$items = array();
print("Please insert the number of pupils required.")
numberOfPupilsRequired = int(input())
pupils = [""] * numberOfPupilsRequired
for i in range(0, numberOfPupils):
print("Please insert the name of pupil", i, ".")
pupils[i] = input()
echo "Please insert the number of pupils required.";
$numberOfPupilsRequired = intval(readline());
$pupils = array();
for ($= 0; $i < $numberOfPupils; $i++) {
echo "Please insert the name of pupil " . $i . ".";
array_push($pupils, readline());
}
DECLARE playerNames AS ARRAY OF STRING INITIALLY [""]*7
You are required to create a program that manages and analyses student assessment scores. The program should allow users to input 10 scores, perform various operations on the scores using arrays, and provide basic statistical analysis.
Requirements:
Implement functions for the following array manipulation tasks:
Whitespace and indentation are both really useful for making a program more readable.
Python enforces indentation, and to some degree, will assist in the indenting a program. PHP does not, so ensure that you use indentation in your code.
Comments make code easier to read by describing what the code does.
Comments in Python are written with a #
sign in front of them. PHP uses the #
or //
in front of a line.
Multiline comments in Python are represented with a '''
in front of them and after them. In PHP a multiline comment is started with /*
and ended with */
.
If you don't already, get into the habit of putting your name, the date and what the program is meant to do at the top of the code in comments
#Asks the user for their name
print("Please insert your name")
forename = input()
//Asks the user for their name
echo "Please insert your name";
$forename = readline();
An identifier is how a compiler recognises a variable or subprogram.
An identifier must be unique; this means that a variable name cannot be the same as a subprogram name.
forename = input()
def doubleNumber(x):
return x * 2
$forename = readline();
function doubleNumber($x){
return $x * 2;
}
It's easy to start writing a program which has lots of repetition in it and not use loops.
Making a program more efficient involves using constructs such as loops, subprograms and subprogram calls, nested if statements
if mark > 80:
print("A")
else:
if mark > 60:
print("B")
else:
print("C")
if mark > 80:
print("A")
else if mark > 60:
print("B")
else:
print("C")
if ($mark > 80) {
echo "A";
} else {
if ($mark > 60) {
echo "B";
} else {
echo "C";
}
if ($mark > 80) {
echo "A";
} else if ($mark > 60) {
echo "B";
} else {
echo "C";
}
It's easy to start writing a program which has lots of repetition in it and not use loops.
Making a program more efficient involves using constructs such as loops, subprograms and subprogram calls, nested if statements
if mark > 80:
print("A")
else:
if mark > 60:
print("B")
else:
print("C")
if mark > 80:
print("A")
else if mark > 60:
print("B")
else:
print("C")
if ($mark > 80) {
echo "A";
} else if ($mark > 60) {
echo "B";
} else {
echo "C";
}
if ($mark > 80) {
echo "A";
} else {
if ($mark > 60) {
echo "B";
} else {
echo "C";
}
Look at your existing code from other assignment.
Rate your work in terms of how well you have used whitespace, commented it, used good naming conventions for identifiers and used efficient constructs.
At National 5 and Higher the SQA talk about predefined functions.
These are functions built-in to the programming language in the form of either a function which is provided through the runtime (like in Python) or compiled straight to the original code (like in C++)
from random import randint
x = randint(0, 10)
x = 10
printSquareNumber(x)
def printAverage(name, mark1, mark2):
average = (mark1 + mark2) / 2
print("Pupil", name, " got an average of", average)
printAverage(21, 34, "John")
You are about to go in to a world of work. You are responsible for understanding how to find a built-in function and understand the documentation about it.
This is an important skill for any good programmer.
Copy and complete this table by looking up the following Python functions
Function name | Description | Parameters and description |
---|---|---|
abs | ||
ord | ||
exec | ||
eval | ||
pow | ||
hex | ||
divmod | ||
oct |
An algorithm is a sequence of instructions that completes a specific task.
The order of these instructions is important
At National 5 you came across three standard algorithms:
Traversing an array
Input validation
Running total
The traversing an array algorithm works simply by looping through an entire array of values
It then does something with those names (for example, simply prints them)
total = 0
names = ["Cammy", "John", "Mike"]
for i in range(0, len(names)):
print(names[i])
The traversing an array algorithm works simply by looping through an entire array of values
It then does something with those names (for example, simply prints them)
$total = 0;
$names = array("Cammy", "John", "Mike");
for ($i = 0; $i < count($names); $i++){
echo $names[$i];
}
Input validation uses a conditional loop.
It loops while the user has not provided the correct username, asking them over and over to insert the correct username
print("Please insert your username")
username = input()
while username != "john117":
print("Please retype your username")
username = input()
Input validation uses a conditional loop.
It loops while the user has not provided the correct username, asking them over and over to insert the correct username
echo "Please insert your username";
$username = readline();
while $username != "john117"{
echo "Please retype your username";
$username = readline();
}
The running total algorithm works by setting a total
variable to 0
It then loops for a set number of times (for example a set number of the size of an array using the len
function)
Each time it loops, it adds a number to the total
variable (it either asks the user to insert a number or it takes the next number from the array)
total = 0
for i in range(0, 10):
print("Please insert a number")
total = total + int(input())
total = 0
numbers = [2, 5, 8, 10]
for i in range(0, len(numbers)):
total = total + numbers[i]
The running total algorithm works by setting a total
variable to 0
It then loops for a set number of times (for example a set number of the size of an array using the count
function)
Each time it loops, it adds a number to the $total
variable (it either asks the user to insert a number or it takes the next number from the array)
$total = 0;
for ($i = 0; $i < 10; $i++){
echo "Please insert a number";
$total = $total + intval(readline());
}
$total = 0;
$numbers = [2, 5, 8, 10];
for ($i = 0; $i < 10; $i++){
echo "Please insert a number";
$total = $total + $numbers[$i];
}
Write a program that loops until the user types -1 adding each number to a total and storing it in array.
Write an algorithm which produces the first 10 numbers in the Fibonacci Sequence [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
The linear search algorithm is used to search through an array one element by one.
It is an inefficient algorithm because of an array consists of 10,000,000 elements - even with the fastest computer - this will take some time to process.
With a linear search, the user provides what is needed and the result is the index of the value that was being searched for.
This algorithm works by stepping through an array of items
It then checks if the item found at that position is equal to what it is searching for.
If it is, it sets the value of the index variable to the current position (not value) in the array
people = ["Matthew", "Flynn", "Connor"]
term = "Connor"
i = 0
index = -1
while i < len(people):
if people[i] == term:
index = i
i = i + 1
print(index)
This algorithm works by stepping through an array of items
It then checks if the item found at that position is equal to what it is searching for.
If it is, it sets the value of the index variable to the current position (not value) in the array
$people = array("Matthew", "Flynn", "Connor");
$term = "Connor";
$i = 0;
$index = -1;
while ($i < count(people)) {
if ($people[$i] == $term) {
$index = $i;
}
$i = $i + 1;
}
echo $index;
A program is required to find a user from their user ID.
[23, 34, 40, 43, 10, 23, 34, 22, 23, 43]
Write a linear search to find the index of the user with user ID of 22
temperatures = [23, 34, 40, 43, 10, 23, 34, 22, 23, 43]
term = 23
total = 0
for i in range(0, len(temperatures)):
if temperatures[i] == term:
total = total + 1
print(total)
$temperatures = array(23, 34, 40, 43, 10, 23, 34, 22, 23, 43);
$term = 23;
$total = 0;
for($i = 0; $i < count($temperatures); $i++){
if ($temperatures[$i] == $term) {
$total = $total + 1;
}
}
print(total)
A program is required to find out how many times a country was a certain temperature. A list of temperatures was provided:
[23, 34, 40, 43, 10, 23, 34, 22, 23, 43]
Write a program to count how many times a temperature has occurred. Test it with 23 and 43.
Finding the maximum is really straightforward in Python
temperatures = [23, 34, 40, 43, 10, 23, 34, 22, 23, 43]
max = temperatures[0]
for i in range(0, len(temperatures)):
if temperatures[i] > max:
max = temperatures[i]
print(max)
Finding the maximum is really straightforward in Python
$temperatures = array(23, 34, 40, 43, 10, 23, 34, 22, 23, 43]);
$max = $temperatures[0];
for($i = 0; $i < count($temperatures); $i++){
if ($temperatures[$i] > $max) {
$max = $temperatures[i];
}
}
echo $max;
Find the minimum really only involves a few changes
temperatures = [23, 34, 40, 43, 10, 23, 34, 22, 23, 43]
min = temperatures[0]
for i in range(0, len(temperatures)):
if temperatures[i] < min:
min = temperatures[i]
print(min)
Find the minimum really only involves a few changes
$temperatures = array(23, 34, 40, 43, 10, 23, 34, 22, 23, 43]);
$min = $temperatures[0];
for($i = 0; $i < count($temperatures); $i++){
if ($temperatures[$i] < $min) {
$min = $temperatures[i];
}
}
echo $min;
List of 10 test scores is show below:
[53, 12, 95, 54, 23, 45, 60, 72, 87, 48]
Implement a program to find the highest test score and the lowest test score using Python.
Program code often gets very messy unless it is broken up. A program can be broken into chunks to make the program more modular.
Programs are often made up of chunks of code that performs different tasks that are repeated throughout the program.
These chunks of code are called subprograms.
Each subprogram is given a unique name so that it can be referenced later on without having to rewrite the code each time it is used.
Often called subroutines, procedures, methods and functions, a subprogram is a clear and independent piece of code that performs a certain task.
We have been looking at predefined functions which are in fact themselves subprograms built in to the programming language.
These predefined functions, such as round will perform a specific job and nothing more.
We too can define our own subprograms.
When we need to run the code within a subprogram, we call it.
The subprogram receives data from the program and performs an action on it (for example, you might expect the printDoubleNumber subprogram to print a number multiplied by 2)
To call it, we use its name followed by brackets and any parameters we need to pass to it, take for example a subprogram called doubleNumber, we could call it using the parameter 2 by using:
printDoubleNumber(2)
def printDoubleNumber(num):
print(num * 2)
printDoubleNumber(2)
A subprogram definition
A call to a subprogram
function printDoubleNumber($num){
echo $num * 2;
}
printDoubleNumber(2);
A subprogram definition
A call to a subprogram
A function is like a mathematical function, it takes in a value and then performs a process on it and gives it back as an output.
In general, a function is a subprogram that can give back a value. It uses the return keyword to instruct the program to send the data back:
def printDoubleNumber(num):
return num * 2
x = 10
y = printDoubleNumber(x)
print(y)
x = 10
printSquareNumber(x)
def printDoubleNumber(num):
print(num * 2)
function printDoubleNumber($num) {
echo $num * 2;
}
def printAverage(name, mark1, mark2):
average = (mark1 + mark2) / 2
print("Pupil", name, " got an average of", average)
printAverage(21, 34, "John")
function printAverage($name, $mark1, $mark2) {
$average = ($mark1 + $mark2) / 2;
echo "Pupil " . $name . " got an average of " . $average;
}
printAverage(21, 34, "John")
function printAverage($name, $mark1, $mark2) {
$average = ($mark1 + $mark2) / 2;
echo "Pupil " . $name . " got an average of " . $average;
}
printAverage(21, 34, "John")
def printAverage(name, mark1, mark2):
average = (mark1 + mark2) / 2
print("Pupil", name, " got an average of", average)
printAverage(21, 34, "John")
Identify which of the following programs have formal parameters and which have actual parameters:
def squareIt(num):
def displayOnScreen(num):
1.
2.
print($y)
3.
print($x * 2)
4.
def addNumber(n):
print(x + n)
def setX():
x = 10
setX()
addNumber(5)
function addNumber($n) {
echo $x + $n;
}
function setX() {
$x = 10;
}
setX();
addNumber(5);
def addNumber(n):
print(x + n)
def setX():
x = 10
setX()
addNumber(5)
function addNumber($n) {
echo $x + $n;
}
function setX() {
$x = 10;
}
setX();
addNumber(5);
&$x
).function changeX(&$x){
$x = 20;
}
$x = 10;
echo $x;
changeX($x);
echo $x;
def printIt(z):
x = 20
print(x, y, z)
y = 10
printIt(5)
Local variable
Global variable
This will not work! Python will be unable to find a variable called y!
def printIt(z):
global y
x = 20
print(x, y, z)
y = 10
printIt(5)
Local variable
Global variable
function printIt($z) {
global $y;
$x = 20;
echo $x . " " . $y . " " . $z;
}
y = 10;
printIt(5);
Local variable
Global variable
In your own words, explain the difference between passing by reference and passing by value.
Open Python IDLE, create a subprogram which returns a number multiplied by 3. Your program should include a global variable which contains the number 3 and some local variables.
For example, suppose you have a list of students, and you want to store their names, ages, and grades. You can use three parallel arrays:
An array for names: This array stores the names of the students.
An array for ages: This array stores the ages of the students.
An array for grades: This array stores the grades of the students.
forename = [""] * 3
surname = [""] * 3
mark = [0] * 3
forename[0] = "John"
forename[1] = "Peter"
forename[2] = "Hamish"
surname[0] = "Thompson"
surname[1] = "Skeldon"
surname[2] = "Barbour"
mark[0] = 14
mark[1] = 19
mark[2] = 13
Declare three empty arrays
Set all of John Thompson's details to the first position in each array
And then display everything
...
for i in range(0, 3):
print(forename[i], surname[i], "you got", mark[i], "out of 20.")
Using Python IDLE, produce programs that meet the following requirements using parallel arrays:
Understand how to implement file reading and writing in Python and PHP
def readFile(filename, lines):
with open(filename, 'r') as f:
for line in f.readlines():
#Add each line to the lines list
lines.append(line)
lines = []
readFile("countries.txt", lines)
print(lines)
Francis,Burnham,36
Peter,Roosevelt,94
Adam,Smith,41
def readFile(filename, list1,list2):
with open(filename, 'r') as csv_file:
for row in csv_file.readlines():
#Remove the \n line terminator character
row = row[0:-1]
#Split the row string by commas
row = row.split(",")
#Each index is a column
print(row[0])
print(row[1])
print(row[2])
def readFile(filename, list1,list2):
with open(filename, 'r') as csv_file:
for row in csv_file.readlines():
#Remove the \n line terminator character
row = row[0:-1]
#Split the row string by commas
row = row.split(",")
#Each index is a column
print(row[0])
print(row[1])
print(row[2])
nums = "1,2,3,4"
##Split the row string by commas
numbers = nums.split(",")
The numbers
variable will contain an array with the following:
[1, 2, 3, 4]
text_file = open("write.txt", "w")
text_file.write("Hello, this is a test to see if this will write")
text_file.close()
Using the provided CSV files
write a program to store each row from the file in either a parallel arrays (use the names in the square brackets above to help).
def writeFile(filename, text):
with open(filename, 'w') as text_file:
text_file.write(text)
text_file.close()
writeFile("test.txt", "Hello there world!")
Note the use of the 'w' instead of the 'r'
import csv
def writeFile(filename, forenames, surnames):
with open(filename, 'w') as text_file:
csv_file = csv.writer(text_file)
for i in range(0, len(forenames)):
#This bit is turning the values into an array
row = [forenames[i], surnames[i]]
csv_file.writerow(row)
text_file.close()
forenames = ["John", "James", "Gillian"]
surnames = ["Smith", "Blogs", "McGlashan"]
writeFile("test.csv", forenames, surnames)
Using the data provided in the CSV file flavours.csv, read all the data into parallel arrays. At the end of the parallel arrays, using the Python list.append function, add 'kiwi' as 'fruity'.
Understand the term class
Understand the term object
Understand the purpose of object-oriented programming
Object-oriented programming is a programming paradigm in which data is encapsulated in objects.
An object represents a real-world entity or thing such as a person or a car.
Classes are created as 'blueprints' for what an object will represent, providing properties and methods that can be used with the object.
A car might have some properties such as the maximum speed, colour, make and registration plate:
class Car:
make = ""
registration = ""
colour = ""
max_speed = 0.0
A car might have some properties such as the maximum speed, colour, make and registration plate:
class Car:
make = ""
registration = ""
colour = ""
max_speed = 0.0
c = Car()
c.make = "Volvo"
c.registration = "SL12 XPZ"
c.colour = "Red"
c.max_speed = 121.3
We can then use the car as shown on the left
Classes are one of the most design-friendly means of representing data about one discrete entity or object.
Classes allow us to organise data in a better way, having data about one thing in one place.
class Car:
make = ""
registration = ""
colour = ""
max_speed = 0.0
cars = []
print("Please enter ten cars")
for i in range(0, 10):
c = Car()
c.make = input("Please enter the make")
c.registration = input("Please enter the registration")
c.colour = input("Please enter the colour")
c.max_speed = float(input("Please enter the maximum speed"))
cars.append(c)
Write a program that stores 10 pupils details, including their forename, surname, SCN number and three marks.
Use classes to help organise the data and ensure you store the data in an appropriately named array.
total = 0
for counter in range (0, 10):
print("Please insert a number")
number = int(input())
while number < 0 or number > 10:
print("Try again")
number = int(input())
total = total + number
print(total)
for counter in range (1, 6):
print(counter)
OUT: length, width, depth
IN: length, width, depth OUT: volume
This is a very common coursework task
When it comes to the project unit, you’ll be asked to write a proposal document and project plan, which includes mentioning your testing strategy. You could write that you’ll be using white box testing, as you know how the code works, and that you will test individual units and the whole program (see below).
Assume that we are testing a single unit. To generate a test plan, make a list of all the inputs (parameters passed in, whether they come from user input or a file).
Assume we’re testing a function that takes two parameters - an integer between 0 and 100, and a string. The function returns true or false.
Test type | age | year_group | Expected result |
---|---|---|---|
Normal | 15 | S5 | Function returns true |
Normal | 82 | None | Function returns true |
Extreme | 100 | None | Function returns true |
Exceptional | -50 | S1 | Function returns false |
Exceptional | Donkey | 77 | Function returns false |
Type of test | Details of testing | Expected result | Evidence to be gathered |
---|---|---|---|
Keyboard input | Left arrow key pressed | Turns left | Screen recordings |
Keyboard input | Right arrow key pressed | Turns right | Screen recordings |
Collisions | Collide with wall/edge | Bounces off, turns 90° | Screen recordings |
Collisions | Collide with self | Lives reduced by 1 | Screenshot of before/after |
Lives | Collide with apple sprite | Lives incremented by 1 | Screenshot of before/after |
Game over | Game ends when no lives left | Game stops, message shown on screen | Screenshot of before/after |
Test plan for a snake game
Type of test | Details of testing | Expected result | Actual result | Errors found | How errors were fixed | Comments |
---|---|---|---|---|---|---|
Describe the concept of the fetch-execute cycle
Describe factors affecting computer performance
In this lesson, we will cover:
The fetch-execute cycle
Factors affecting computer system performance
From this diagram we should also know that the CPU is broken down into 3 main parts:
Control Unit
The control unit controls the order of execution and the timing of all instructions
Arithmetic and Logic Unit (ALU)
The ALU performs the calculations for the processor and evaluates logical decisions.
Registers
The registers are temporary storage spaces for data. They are found directly on the CPU and are often only a few bytes in size.
Control Line | Function |
---|---|
Clock | Generates a constant pulse (measured in MHz). One operation will be carried out per pulse |
Read | Signals that the processor wishes to read data from the memory |
Write | Signals that the processor wishes to write data to the memory |
Reset | Causes the processor to halt execution of current instruction. All registers cleared and machine reboots |
Interrupt (IRQ) | Notifies the processor that an external event has occurred such as I/O from a device. This type of interrupt can be ignored. |
Non-Maskable Interrupt (NMI) | This is an interrupt that CANNOT be ignored such as a low power failure notification |
Clock speed is the number of pulses that occur in a second. Which is measured in hertz
1 clock pulse = 1 hertz
1000 clock pulses = 1000 hertz = 1 kilohertz
1000 kilohertz = 1 megahertz
1000 megahertz = 1 gigahertz
1000 gigahertz = 1 terahertz
The primary role of the ALU is arithmetic calculations, including addition, subtraction, multiplication and division.
In relation to logic it will perform calculations such as AND/OR/NOT
(such as those used in programming or in a processor instruction)
One particular register used by the ALU is the accumulator which holds the results of calculations. (Intel calls this the EAX)
Registers are very small memory locations found on the CPU itself. Because they are found on the CPU die, they are incredibly quick to access.
Registers are used to store small amounts of data whilst a program is being executed. The data they tend to hold varies from program data, to instructions to memory locations.
Registers are very close to the processing units of the CPU (such as the ALU and control unit) to improve system performance, but they are also very small and limited to around 64 bits (8 bytes).
Below is a simple C program to add two numbers in x86 Assembly Code:
add(int, int):
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], edi
mov DWORD PTR [rbp-8], esi
mov eax, DWORD PTR [rbp-4]
add eax, DWORD PTR [rbp-8]
pop rbp
ret
Some specialist registers are shown below:
Register name | Description |
---|---|
Instruction Register | Holds the address in memory of the next instruction to be executed |
Memory Address Register (MAR) | This is used to hold a value representing the address in memory that the processor needs to access. This would be connected to the address bus |
Memory Data Register (MDR) | This is used to gold data read from or being written to memory. Connected to the data bus |
Program Counter | Stores the instruction number that the program is currently executing. On x86 machines this is called the instruction pointer. |
Buses are lines (wires) that connect different parts of a computer together.
If you flip a motherboard over, you can see all the lines (called traces) that show all the buses.
Data Bus – Used to carry data to and from the CPU and memory. It holds a binary word. The data bus is bidirectional.
Address Bus - Used to carry the address of the memory location that is being used. It is unidirectional.
Control Bus – This doesn’t carry data but has a number of status signals it can send (reset, interrupt etc.)
unidirectional = one way
bidirectional = two way
A binary word is the number of bits that can be transferred by the data bus in a single operation.
Most PCs just now have a word length of 32 or 64 bits. Meaning the data bus can carry 16 (WORD
), 32 (DWORD
) or 64 (QWORD
) bits in a single operation.
Changing the width of the data bus means that we can move more or less data in a single operation - this would lead to increased performance due to less operations required to move
Changing the width of the address bus means that we can address more memory - this wouldn’t necessarily lead to an increase in performance in all cases
0
1
0
1
1
0
0
1
0
0
1
1
1
0
0
1
1
1
1
1
1
0
1
1
1
1
0
0
0
0
0
0
16 bit address bus
Changing the width of the data bus means that we can move more or less data in a single operation - this would lead to increased performance due to less operations required to move
Changing the width of the address bus means that we can address more memory - this wouldn’t necessarily lead to an increase in performance in all cases
0
1
0
1
1
0
0
1
0
0
1
1
1
0
0
1
1
1
1
1
1
0
1
1
1
1
0
0
0
0
0
0
32 bit address bus
Explain why increasing the width of the data bus will improve the system performance.
2 marks
SQP Q11 b)
The wider the data bus, the more bits that can be transferred (1 mark) in a single operation (1 mark)
The memory address of the next instruction is placed on the Memory Address Register
The processor activates the read line on the control bus
The instruction is fetched from the memory location using the data bus and stored in the Instruction Register
The instruction in the Instruction Register is then interpreted by the decoder and executed
Stage
1
2
3
4
From what we just looked at, write down the four stages of the fetch-execute cycle and describe them.
A multi-core processor is a processor with two or more separate processing units (cores).
Each core contains an ALU, Control Unit and Registers.
The greater the number of cores on a processor, the greater the number of instructions that can be carried out simultaneously.
However, it’s not always possible to share tasks between cores.
An AMD EPYC chip is shown to the right. It consists of multiple smaller chiplets which themselves have multiple cores. EPYC processors can have up to 128 cores as of 2023.
It's also possible to get motherboards that can take multiple processors themselves.
The board pictured here is a dual AMD EPYC board that can take two 128 core EPYC CPUs and up to 1.2TB of main memory.
Parallelism is a big research area in computer science today.
We already know that the data bus is used to carry data to and from the processor.
Each cycle of the fetch-execute cycle requires data to be moved along the data bus.
Increasing the width of the data bus, increases the amount of data that can be transported in a single cycle.
Cache memory is a small amount of fast accessible memory usually on the same chip as the processor.
The processor will check cache for data before accessing the main memory.
If it finds data or an instruction, this is known as a cache ‘hit’, resulting in improved performance. If the instruction is not present, then a cache ‘miss’ occurs and a slower main memory is accessed.
Many computers use multiple levels of cache, with small caches backed up by larger, slower caches.
There are different levels of cache memory:
Level | Description |
---|---|
L1 | In the processor core, generally around about 64KB |
L2 | Generally attached to the core, around about 256KB per core |
L3 | Generally shared between all cores, between 4MB and 32MB |
The processor always checks the fastest cache first. If the hit is not found it goes to the next fastest level and so on.
Cache memory is used to store frequently used data and instructions.
Clock speed is the measure of how many instruction cycles the system can work through within one second.
Clock pulses are used to trigger components to take their next step.
The higher the clock speed, the faster the computer can complete a set of instructions.
It is possible with some CPUs (for example Intel K series CPUs and all AMD Ryzen CPUs) to push them passed their set clock speed.
This is called overclocking.
The stability of a system can suffer as the clock speed gets higher, and since power consumption is directly proportional to the frequency the power draw can increase. Often overclockers tend to overvolt the system as well as overclock it to improve stability.
Increasing clock speed is one method of improving processor performance.
a) State one other method of improving processor performance.
1 mark
b) Explain how your answer to part (a) improves performance
1 mark
2021 Q2 (a) & (b)
Understand the terms compiler, interpreter and runtime
Understand how these three different programs work
03 (IDENTIFIER) 12 (LBRA) 08 (STRING) 13 (RBRA)
print("Hello world")
time
and a variable called x
in Python. Why does PHP require dollar signs in front of variables whereas Python does not?
print(time())
print(x)
How does the compiler know, without looking ahead, that brackets follow the word time? If it doesn't check ahead, it might just assume at first, incorrectly of course, that time is a variable. It then reads the symbols after to discover a bracket, so it changes it's mind. That's a waste of time and resources.
PRINT
IDENTIFIER
LBRACKET
LBRACKET
RBRACKET
RBRACKET
PRINT
IDENTIFIER
LBRACKET
RBRACKET
time
and a variable called $x
in PHP.Why does PHP require dollar signs in front of variables whereas Python does not?
print(time())
print(x)
How does the compiler know, without looking ahead, that brackets follow the word time? If it doesn't check ahead, it might just assume at first, incorrectly of course, that time is a variable. It then reads the symbols after to discover a bracket, so it changes it's mind. That's a waste of time and resources.
PRINT
IDENTIFIER
LBRACKET
LBRACKET
RBRACKET
RBRACKET
PRINT
IDENTIFIER
LBRACKET
RBRACKET
print(time())
print($x)
Now the compile can figure out that $x is a variable with only the first symbol it reads because the first symbol it finds is the $ sign.
PRINT
IDENTIFIER
LBRACKET
LBRACKET
RBRACKET
RBRACKET
PRINT
IDENTIFIER
LBRACKET
RBRACKET
DOLLAR
The following are key shortcuts for using DragonSlides and reveal.js.
Key combination | Action |
---|---|
→, PAGE DOWN, SPACE | Next slide |
←, PAGE UP | Previous slide |
SHIFT + → | Last Slide |
SHIFT + ← | First slide |
B | Whiteboard |
W | Widget Board/White Screen |
C | Toggle Notes Canvas |
DEL | Clears Whiteboard/Notes Canvas |
S | Show Presenter Mode |
SHIFT + D | Toggle Dark Mode |
H | Goes to the Home Slide |
META + P | Show Print options window |
In order to use the 'Start Remote' feature, you'll need to download JB Slide Controls from the Apple App Store. Once you have this you'll be able to control the slides using the app from you Apple Watch.
DragonSlides and jamiebalfour.scot are copyright © Jamie B Balfour 2017 - 2024, 2010 - 2024. Content is copyright © Jamie B Balfour