<<

Teach yourself Programming with pseudocode and Python

for AQA GCSE Science (8520)

Students Workbook

By Nichola Lacey

Contents Introduction ...... 5

How to use this book ...... 5

Who should use this book? ...... 5

Installing Python ...... 5

Data types ...... 6

Using data types ...... 7

Integer ...... 7

Real...... 7

Boolean ...... 8

Character ...... 8

String ...... 8

End of chapter recap ...... 11

Programming Concepts ...... 12

Variables ...... 12

Constants ...... 13

Defining variables and constants ...... 14

Rules of naming variables and constants ...... 14

Assignment...... 15

Iteration ...... 17

Condition-controlled iteration ...... 17

Count-controlled iteration ...... 19

Indenting lines of code ...... 19

Selection ...... 21

Nested selection and nested iteration ...... 23

Nested iteration ...... 24

Nested selection ...... 25

Subroutines (procedures and functions) ...... 30

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 1 Advantages of using subroutines in programs...... 31

Passing data within programs ...... 32

Returning single vales ...... 32

Returning multiple values ...... 33

Global and local variables ...... 34

Why use local variables? ...... 34

Functions and Procedures...... 35

End of chapter recap ...... 40

Operators ...... 41

Arithmetic operations in a ...... 41

Relational operators in a programming language ...... 43

Boolean operations in a programming language ...... 45

Using operators in iteration and selection structures ...... 46

End of chapter recap ...... 48

Data Structures ...... 49

Arrays ...... 49

One-dimensional arrays ...... 49

Creating and using a 1D array ...... 50

Two-dimensional arrays ...... 53

Creating and using a 2D array ...... 54

Complex data types ...... 56

End of chapter recap ...... 58

Input/Output and file handling ...... 59

User input from the keyboard ...... 59

Displaying output ...... 59

Reading from and writing to a text file ...... 60

File location ...... 60

Writing to a text file ...... 60

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 2 Reading from a text file ...... 63

End of chapter review ...... 64

String handling operations ...... 65

Length ...... 65

Position ...... 65

Substring ...... 66

Concatenation ...... 67

Character codes ...... 67

String conversions ...... 68

Converting string to integer ...... 68

Converting string to real (floating-point) ...... 68

Converting integer to string ...... 68

Converting real (floating-point) to string ...... 68

End of chapter recap ...... 69

Random number generation ...... 70

End of chapter recap ...... 70

Structuring programming ...... 71

Step 1: Analyse the problem ...... 71

Step 2: Interpret the problem as a sequence of sub-problems ...... 73

Step 3: Design the solution ...... 74

Step 4: Creating a program ...... 75

White space ...... 75

Relevant and descriptive names ...... 76

Comments ...... 76

The advantages of using a structured approach ...... 77

End of chapter recap ...... 77

Robust and secure programming ...... 78

Data Validation ...... 78

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 3 Using a loop to force the user to try again ...... 78

Creating menus ...... 80

Try and catch ...... 81

Creating a simple authentication routine ...... 82

Testing your programs ...... 83

Test table...... 84

What sort of data should you test? ...... 85

End of chapter recap ...... 87

Classification of programming languages ...... 88

Low-level languages ...... 88

High-level languages ...... 89

Translators ...... 91

Interpreter ...... 91

Compiler ...... 91

Assembler...... 91

End of chapter recap ...... 92

Answers ...... 93

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 4 Introduction

"Whether you want to uncover secrets of the universe, or you want to pursue a career

in the 21st century, is an essential skill to learn."

Stephen Hawking, Theoretical physicist

Computers surround us and this book has been written to give you a practical hands-on approach to help you learn about how to program using the programming language Python. Instead of chapters of technical jargon and mind-numbing tedium the theory is broken down into smaller, manageable chunks with practical tasks for you to perform as you go along. This helps to ensure you understand the theory and remember it as you apply it to practical problems.

How to use this book

It is recommended that you start at the beginning and work through the chapters in order as each chapter builds on the knowledge you have gained from the previous one.

You are not expected to be a passive passenger on this journey. If you want to learn programming, you will need to do a bit of work yourself to achieve this. It is highly recommended that you do perform the tasks as instructed, even if some of them seem a little bizarre. They are all included for a reason and will help you learn the skills as you progress through the workbook. If you get stuck the answers, where there is a definite answer, to all the tasks are given at the back (page 93) of this book but try not to cheat and give the tasks a go.

Who should use this book?

This book was specifically written to assist students preparing for their AQA GCSE Computer Science examination (8520) and the objectives have been written specifically to match the syllabus, as of April 2018. However, the theory and methods would be beneficial to anybody who wants to learn how to program with Python.

Downloading Python

You can download Python for free from https://www.python.org/downloads/.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 5 Data types

Objective: Understand the concept of a

Data type = tells the computer program how you want that data to be treated

A data type tells the programming language how the data should be treated. For instance with the data “100318” this could be a telephone number (where you would not want to perform any calculations with it as there is no reason to add two telephone numbers together) or it could be a date (the 10th March 2018 in which case to add a day it would become 110318 rather than 100319) or it could be a numeric value (£100,318.00, in which case you may want to perform calculations with it such as addition, subtraction, multiplication or division).

As you can imagine it is very important to make sure the program knows how you want the data to work so you must specify the data types that you are using.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 6 Using data types

Objective: Understand and use the following appropriately: integer, real, Boolean, character and string.

Integer Integer = whole An integer is a whole number which can be either positive (0 or above) or negative (under 0). Lets look at how this can be used in number pseudocode and Python.

Pseudocode Python num1  integer(USERINPUT) num2  integer(USERINPUT) total  num1 + num2 OUTPUT total

In both examples num1 and num2 are values that the user will enter but it is specifying that they also have to be integers. In Python the word int is used to define the data type as an integer.

Real Real (floating- A real number is any number (positive or negative) including point) = number decimal places. In Python a real number is called a floating-point number or float for short. with decimal point

Pseudocode Python price  real(USERINPUT) discount  price * 0.20 total  price - discount OUTPUT total

Here the price is inputted by the user and treated as a real or floating-point number (notice the word float in the Python program). The discount is multiplied by 0.20 (20%) and subtracted from the original price to show the new total. This total is then displayed. In Python if an integer is inputted and then used as part of a division it will automatically change the data type of that variable to a floating-point data type.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 7 Boolean Boolean = Boolean values can have one of two values, usually True or False and cannot be left empty. True / False

Pseudocode Python member  true IF member = true THEN discount  0.20 ELSE discount  0 ENDIF

In this example the data type itself is not defined as the word true or false makes it obvious that the data type is a Boolean value. In python the word True and False need to have a capital letter at the beginning for Python to understand it is a Boolean value.

Character Character = A character is a single symbol such as a letter. Take the word “hello” single letter this could be defined as 5 single characters “h”, ”e”, “l”, “l”, and “o”.

Pseudocode Python myText = “Computer Science” OUTPUT LEN(name)

The output for the above examples will be 16 as it counts each letter and the space as separate items. LEN finds the number of characters in a string and we will be looking at strings next.

String A string is a series of characters that are combined to make a single piece String = of data. They are defined by adding speech marks around the value. However, in Python anything that the user inputs is treated as a string text unless otherwise specified.

Pseudocode Python name = USERINPUT OUTPUT POSITION(name.“a”)

In the above example the user would input their name and as it is not defined otherwise it is assumed this is treated as a string. It will then output the position of the letter “a” in the name. for

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 8 instance if they entered “Sam” the position would be 1 ( start counting from 0 so the first character is counted as 0 and the second character is 1). If the name they entered was “Nichola” the output would be 6. However if they entered “Timothy” which does not have any “a” characters in it Python would display the output as -1.

Task 1: Write the pseudocode for the following scenarios

Scenario Pseudocode Ask the user to enter a whole number. Add 5 to that number and display the new total.

Ask the user to enter a number which allows decimal places and divide (/) that by 2. Display the answer.

Ask the user to enter their age. If they are over (>) 17 save a variable called adult to true, otherwise save the variable called adult to false.

Ask the user to input their first name and save this as a string. Display their name.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 9 Task 2: Write the Python code for the same scenarios. Type them into Python to test them out and save them with a suitable name

Scenario Python code Ask the user to enter a whole number. Add 5 to that number and display the new total.

Ask the user to enter a number which allows decimal places and divide (/) that by 2. Display the answer.

Ask the user to enter their age. If they are over (>) 17 save a variable called adult to true, otherwise save the variable called adult to false

Ask the user to input their first name and save this as a string. Display their name.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 10 End of chapter recap

Task 3: Find the hidden data types in the grid and when you have found them write a definition of that data type and give an example of data using that data type

Data Type Definition Example of this data type

Integer

Real

Boolean

Character

String

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 11 Programming Concepts

Objective: Use, understand and know how the following statement types can be combined in programs: variable declaration, constant declaration, assignment, iteration, selection and subroutine (procedure/function).

Variables

Variable = a value that can change while the programme is running

Variables are values that change during the running of the program. This could be because the user is required to input the value or because it altered because of another in the program. Each variable is given a name which is unique to that variable and must not include any keywords that will interfere with the programming language for instance “and”, “input” etc.

Task 4: Underline the variable names in the following pseudocode and Python code wherever they are used

Pseudocode Python num1  integer(USERINPUT) num2  integer(USERINPUT) total  num1 + num2 OUTPUT total

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 12 Constants

Constant = a value that can NOT change while the programme is running

Constants are values that cannot be altered by the program during the normal running of the program. For instant the value of Pi (π) could be set to 3.14159265 for a program and it will not alter from this.

Task 5: Underline the constant name in the following pseudocode and Python code wherever they are used

Pseudocode Python exchangeRate  0.87 euros  real(USERINPUT) pounds  euros * exchangeRate OUTPUT pounds

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 13 Defining variables and constants

Defining a variable or constant means giving it a name that it can be referred to in the program and the value that it will be using. If it is a variable, defining it will assign the first value that will be used although this will change, for instance num1, exchangeRate or even just x. These are all valid variable names.

Rules of naming variables and constants Objective: Use meaningful identifier names and know why it is important to use them.

You need to give your variables and constants a suitable name so that you can refer to it easily later and it will make sense to you. There is no point in naming a variable “x” and another “y” if they are both important variables which you will need to refer to a lot in your program. These short one- letter variable names are usually only used for counting or variables which have a short life-span over a couple of lines of code.

All variable and constant names must begin with a letter of the alphabet but after the first initial letter, names may also contain letters, the numbers 0 to 9 and some symbols such as the “_” symbol. You cannot use mathematical symbols such as +, -, * or / as this will cause confusion since you could use those variables as part of a calculation. You must not use spaces in the name and therefore if the most logical descriptive name for a variable or constant would include more than one word it is common to use something called “

Normally variable names are displayed all in lowercase (i.e. num) but if it contains more than one word these are pushed together to remove the space and a capital letter at the start of each word is capitalised. Some prefer to do this from the start of the first word (ExchangeRate) but other programmers prefer to only so this to the second word onwards (exchangeRate). It is a personal preference but you should be consistent through the program. Variable and constant names are case sensitive so make sure you remember the correct case for the names you decide on, so you can refer to them later in the program.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 14 Assignment

Once you have created the variable or constant by naming it you need to give it a value. In pseudocode this is done with the symbol  and in Python the = is symbol is used.

Task 6: Look at the following pseudocode and then answer the questions below

num  USERINPUT multiplyer  5 total = num * multiplyer OUTPUT total

Question Your Answer

1. How is the variable num assigned?

2. What is the value of the constant that is used in this pseudocode?

3. Is total a variable or a constant?

4. How is the total calculated?

5. If the user inputted 10 when prompted to enter a number, what would the output of the program be?

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 15 Task 7: Look at the following Python code and then answer the questions below

Question Your Answer

1. How is the variable x assigned?

2. What is the value of the constant that is used in this Python code?

3. How is the value of the constant assigned?

4. If the user enters 50, what will the output be?

5. If the user enters 3, what will the output be?

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 16 Iteration

Objective: Use definite and indefinite iteration, including indefinite iteration with the condition(s) at the start or the end of the iterative structure.

Iteration is the act of repeating a process. These are Iteration = commonly called “loops”. There are two types of iteration: repeating a process • condition-controlled iteration • count-controlled iteration

Condition-controlled iteration This is where the program will keep looping until it either meets a condition (an until loop) or until the condition is no longer met (a while loop). These are also known as indefinite iteration as there is no set number of times the loop will be repeated.

Lets look at the statement “Wait at the pedestrian crossing UNTIL the green man shows”. Here the loop will keep repeating and the pedestrian will keep waiting until the condition “the green man shows” is met and then they can cross the road. Here is another repeat…until statement written in pseudocode.

Pseudocode Python num = integer(USERINPUT) REPEAT There is no repeat… until direct equivalent in num  num * 2 Python UNTIL num > 100 OUTPUT num

Here the user will input a number and it will keep multiplying that number by 2 until it is over 100 then output the number.

If they entered 30 it would change that to 60 and then 120 so it will have repeated the loop twice and output the message 120. If they inputted 1 it would double that to 2, 4, 8, 16, 32, 64, 128 to repeate it 7 times. A repeat until loop will perform a task and check the condition when it gets to the end of the loop to see if it needs to be repeated. Therefore, a repeat…until loop is known as an indefinite iteration with the condition at the end.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 17

Another loop is “WHILE it is raining use your umbrella”. This means that the person who is out in the rain will be constantly checking to see if it is still raining and if it is they will still use their umbrella. This is a condition which needs to be met to keep the loop repeating. The moment it is no longer raining they can put their umbrella away.

Lets look at another example in pseudocode and Python.

Pseudocode Python num  0 WHILE num < 100 newNum  integer(USERINPUT) num = num + newNum

ENDWHILE OUTPUT num

Here there is a Python equivalent to the pseudocode while loop. In both of these codes a variable called num is assigned the value 0 to start with. The while loop starts and checks the condition at the start of the loop to see if it is number 100. as long as num remains under 100 it will keep repeating the loop. It will ask the user to input an integer and assign this to the variable called newNum. It will then add newNum to the num counter and start the loop again, checking to see if num is still under 100. Once num is no longer under 100 it will stop the loop and display the total of num. If the user inputs 23, 54 and 38 the output will display 115 and the loop will have run 3 times. If the user inputs 1 each time the loop will have to repeat 100 times so that it is no longer under 100. Therefore, a while loop is known as an indefinite iteration with the condition at the start of the loop.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 18 Count-controlled iteration This is also known as definite iteration because the code will know how many times the loop will run and it will always run that many times. In other words, it is not dependent on a condition to make it work or stop it running. Here is a definite iteration written in pseudocode and Python.

Pseudocode Python

FOR x  1 to 5 OUTPUT x ENDFOR

In both of these pieces of code x is a variable that has been created just to count the loop. This is quite a common practice and often you will see i or another single letter name used in this way which is perfectly acceptable as it only has a short life-span in the program and is not something that will need to be remembered once the loop has finished.

The main difference in the example above between the pseudocode and the Python code is when it will stop the loop. In the pseudocode it will be read as the loop will run 5 times. However, in a quirk of the way in which Python runs, when it checks the condition it will stop the loop when it gets to 5 so will not display the number 5 in the sequence and will only display 1, 2, 3 and 4 as the outputs. In Python you would need to use the line for x in range (1,6): to see the numbers 1 to 5 in the output.

Indenting lines of code It is very important to indent your code properly as the indenting shows which code is inside other bits of code. For instance, look at the following pseudocode:

FOR x  1 to 5 OUTPUT x ENDFOR

The output line is part of the , in other words it is inside the for loop. Any lines of code that are inside a loop should be indented. In pseudocode this is done by using 5 space characters and in Python you can either use the space characters or the tab key to get the same effect. Python will help you out and automatically indent lines it thinks are inside other sections. If you want to stop it indenting, you can use the delete key to get rid of the indentation.

Later we will be looking at “nested selection and iteration” and being comfortable with indenting text is an important skill to understand by then.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 19 Task 8: Write the pseudocode which will perform the following tasks. Remember to indent lines that are within the loop

Task Pseudocode

1. Ask the user to input a number and keep adding 10 to that number until the number is over 50. Once it is over 50 display the total.

2. Ask the user to enter a start and an end number (use two prompts to do this). Display the numbers between those two values. For instance if they enter 5 and 10 it should show 5, 6, 7, 8, 9 and 10 in the output.

3. Ask the user to enter a number. While that number is under 50 keep asking them to enter the number again. When they successfully enter a number which is worth 50 or more stop asking them.

Task 9: Correctly the two pieces of Python code so that one is labelled “Definite iteration” and the other is named “Indefinite iteration”

This will keep asking the user to enter a number until This will count down from 10 to 1 and they enter a number under 5. It will then display that then display the message “Blast off!” number.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 20 Selection “Selection” decides In a selection structure, a question is asked and depending on the answer the program takes one of two courses of which route to take action, after which the program moves on to the next through the program . These are commonly known as if statements. It is easier to envision this with a flow diagram.

In this example the user is asked to input a number. If the number they enter is over 100 it will display the message “This is a high number”, otherwise it will display the message “This is a low number”. Lets look at this in pseudocode and Python.

Pseudocode Python num  integer(USERINPUT) IF num > 100 THEN OUTPUT “This is a high number” ELSE OUTPUT “This is a low number” ENDIF

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 21 Task 10: Write pseudocode and Python code which will ask the use to enter two numbers. If the first number is larger than the second number display the first number, otherwise display the second number

Pseudocode Python code

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 22 Nested selection and nested iteration = Objective: Use nested selection and nested iteration structures. putting one Nesting means putting one structure inside another structure. An example of this would be putting an iteration inside a selection structure inside structure as this pseudocode shows. another

num  integer(USERINPUT) IF num > 1 AND num < 10 THEN FOR x  1 TO num OUTPUT x ENDFOR ELSE FOR x  1 TO 10 OUTPUT x ENDFOR ENDIF

Here you will see there is a main IF statement and inside each section of the IF statement is a FOR loop. The user will enter a number. If that number is between 1 and 10 it will count from 1 to the number they have entered, otherwise it will count from 1 to 10 regardless of the number they have entered.

The two FOR loops in this example are known as nested statements as they are inside the IF statement.

Look carefully at the indenting. The FOR loop is indented 5 spaces as it is inside the IF statement and the OUTPUT lines are indented a further 5 spaces as they are inside the FOR loops.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 23 Nested iteration Here is an example of a nested iteration inside another iteration.

Pseudocode Python num  integer(USERINPUT) total  0 WHILE total < 100 FOR i  1 TO 3 total  total + num ENDFOR OUTPUT total ENDWHILE

Here the user will enter a number and it will create a variable called total which is worth 0 at the start of the program. As long as the total is under 100 it will perform a FOR loop which will run 3 times adding the number they entered to the total. After it has done this three times it will display the total and repeat the WHILE loop if the total is still less than 100. Once the total is 100 or more it will stop running the WHILE loop. If the user enters the value 5 the outputs will be: 15, 30, 45, 60, 75, 90 and 105. Don’t forget the Python For loop needs to be from 1 to 4 to make it run three times.

Task 11: Write pseudocode and Python code which will ask the user to enter their name and a number. It should display their name that number of times and then ask them if they want to play again. As long as they answer “y” then repeat the

whole program

Pseudocode Python code

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 24 Nested selection IF statements can also be nested together and there are several variations of selection structures in place to allow this to happen.

Basic selection statement

This has a single condition and a single possible output, depending if that condition has been met. If the condition has not been met there is no output and the program will continue to the next event.

Pseudocode Python num  integer(USERINPUT) IF num > 10 THEN OUTPUT “Too high”

ENDIF

Task 12: Use the space below to write some pseudocode which will ask the user to enter a number. If that number is equal to 7 display the message “Thank you”

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 25 Standard selection statement

This has a single condition and two possible outputs, depending if that condition has been met. If the condition has been met it will take one branch, otherwise it will take the other branch.

Pseudocode Python num  integer(USERINPUT) IF num > 10 THEN OUTPUT “Too high” ELSE OUTPUT “Thank you” ENDIF

Task 13: Use the space below to write the correct Python code which will ask the user to enter a number. If that number is less than 7 display the message “Thank you”, otherwise display the message “Wrong”

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 26 Additional condition selection statement

This has a first condition which, if met, will perform that branch of the selection statement and then skip the rest of the selection statement. If, however, the first condition is not met, it will test the next condition. If this condition has been met it will perform the second branch of the selection statement otherwise it will perform the final section of the selection statement. Additional else If sections can be added before it finally meets the final else statement. The last branch should always be a simple else (without a condition) as this will allow any other possibility to be accounted for.

Pseudocode Python num  integer(USERINPUT) IF num > 10 THEN OUTPUT “Too high” ELSE IF num < 5 THEN OUTPUT “Too low” ELSE OUTPUT “Thank you”

ENDIF

Task 14: Use the space below to write pseudocode which will ask the user to enter a colour. If they enter “red” display the message “Thank you”, if they enter “blue” display “Well done” for anything else display “Incorrect”

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 27 Nested selection statements

Nested selection statements are when you have a selection statement inside another selection statement. In this example, if the answer to the first question is true it will ask the second “nested” selection statement.

Pseudocode Python num2  integer(USERINPUT) num3  integer(USERINPUT) IF num1 > 10 THEN IF num2 > 10 THEN OUTPUT “Thank you” ELSE OUTPUT “Invalid Input” ENDIF ELSE OUTPUT “Too low” ENDIF

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 28 Task 15: Use the space below to write the correct Python code which asks the user to enter two numbers. Add them together to make a third number. Follow the flow diagram to help you write the rest of the Python code

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 29 Subroutines (procedures and functions)

Objective: Understand the concept of subroutines.

Subroutine = a sequence of instructions that perform a specific task

It may be easier to think of them as mini-programs within a large program.

Look at the following example.

Here the main program (shown in the flowchart on the left, beginning with the word “Start”) asks the user to input two numbers. It then asks them to select an option from a menu (not shown here to simplify things for you). If they enter the word “add” it will run a subroutine called addNum (shown in the smaller flowchart on the top right of the example starting with the word addNum), if they enter anything else it will run the subtractNum subroutine (bottom right).

We will look at the subroutine box in the main flowchart first:

addNum(num1,

num2)

We can see the name of the subroutine has been defined along with the variables num1 and num2 in brackets. This means that the addNum subroutine is going to use the values of num1 and num2

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 30 and so has been “passed” these values. Sending variables to a subroutine is known as “passing” the variables.

Now, read the addNum subroutine flowchart (also shown on the previous page but we have isolated it here to make it easier for you).

It will add together the num1 and num2 variables and store these in a new variable called answer. It will then return the variable answer back to the main menu. Going back to the main menu, once the addNum subroutine has been completed it will be able to display the answer variable. If we had not returned the answer variable back to the main menu it would not be able to display the answer in the output as the main program on its own has not defined the answer variable and it does not know what it is.

Advantages of using subroutines in programs Objective: Explain the advantages of using subroutines in programs.

The advantages of breaking a program into subroutines include: • Decomposing a complex programming task into smaller chunks which helps you focus on one section at a time. • It saves the programmer time as it reduces the amount of code that needs to be written or amended by allowing you to reuse code without having to write it again (you can simply direct the program to go back to that section and run it again). • If you are working as part of a programming team you can divide a large program into smaller sections and allow individuals to simultaneously work on those sections. • It makes the code easier to read if you use sensible subroutine labels as the headings tell the reader what that section of code is doing. • By reducing the amount of repeating tasks you also reduce the risk of introducing errors in a program and it makes the errors easier to find.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 31 Passing data within programs Objective: Describe the use of parameters to pass data Parameter = a variable within programs. that is “passed” to a A parameter is a variable used in a subroutine to refer to subroutine data that is inputted into the subroutine.

If a subroutine requires a value that has been used in another part of the program then this variable has to be “passed” to the subroutine. You can have more than one parameter passing into a subroutine at a time.

SUBROUTINE addNumbers(num1, num2) total  num1 + num2 OUTPUT total ENDSUBROUTINE

num1  integer(USERINPUT) num2  integer(USERINPUT) addNumbers(num1,num2)

In this example we have overcomplicated the program as there is no real reason to use a subroutine for such a simple task but we have done this to show you how more than one parameter can be passed into a subroutine. In this case num1 and num2 are variables inputted by the user in the main program. Once the variables have been inputted, the addNumber subroutine is called and the two parameters (num1 and num2) are passed to that subroutine so they can be used.

Returning single vales Objective: Use subroutines that return values to the calling routine.

If we alter the above example slightly and instead of outputting the total as part of the subroutine we wanted to use that variable in the main program or even in another subroutine we would need to pass that value back into the main (calling) program.

SUBROUTINE addNumbers(num1, num2) total  num1 + num2 RETURN total ENDSUBROUTINE

num1  integer(USERINPUT) num2  integer(USERINPUT) addNumbers(num1,num2) OUTPUT total

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 32 This has the additional line in the subroutine to return the value which means it has been passed back to the main (calling) program.

Returning multiple values It is possible to return more than one value back to the main (calling) program, however you need to create something called a tuple. A tuple is a short list that holds values temporarily.

Take this example: we want to return the numbers and the total back to the main program. SUBROUTINE addition() num1  integer(USERINPUT) num2  integer(USERINPUT) total  num1 + num2 returningValues = (num1,num2,total) RETURN returningValues ENDSUBROUTINE

name  USERINPUT num1,num2,total  addition() OUTPUT “Hello” + name OUTPUT “You entered” + num1 + “and” + num2 OUTPUT “The total is”+ total

Here num1, num2 and total have been combined in the subroutine into a tuple called returningValue and this is retuned to the program using the line num1, num2, total  addition(). This will only work as long as the data is presented in the same order as it appears in the tuple.

Lets have a look at that in Python:

Don’t worry too much at this time about the str() sections as we will be looking at these a little later, but do take note of how the parameters are being passed around the system. The values that are being returned are grouped in a tuple and then used in the main program once they have been returned in the same order as the tuple.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 33 Global and local variables Objective: Know that subroutines may declare their own variables, called local variables, and that local variables usually only exist while in the subroutine executing and are only accessible within the subroutine.

Global Variable = a variable = a variable that is declared in the main that is declared and only program used in one subroutine

Global variables are declared outside any function and they can be accessed (used) on any function in the program. Local variables are declared inside a function and can be used only inside that function. It is therefore possible to have local variables with the same name in different functions.

Why use local variables? Objective: Use local variables and explain why it is good practice to do so. SUBROUTINE changeNumbers(num1, num2) userNum  integer(USERINPUT) total  (num1 + num2)/userNum RETURN total ENDSUBROUTINE

num1  integer(USERINPUT) num2  integer(USERINPUT) addNumbers(num1,num2) OUTPUT total

In the example above num1 and num2 are global variables as they can be used anywhere in the program or subroutines (as long as they have been passed to the subroutines as parameters). However, userNum is only used within the changeNumbers subroutines so is classed as a local variable as it is not used anywhere else. As soon as the changeNumbers subroutine has finished running the data stored in userNum would be deleted.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 34 Functions and Procedures There are two type of subroutine you need to be aware of:

• Functions • Procedures

Functions return values back to the main program and procedures don’t return a value back to the main program. Therefore, addNum and subtractNum in our example are functions and not procedures as they both return values back to the main menu.

Lets look at the subroutine written in pseudocode and Python.

Pseudocode Python SUBROUTINE addNum(num1,num2) answer  num1 + num2 RETURN answer ENDSUBROUTINE

SUBROUTINE subtractNum(num1,num2) answer  num1 - num2 RETURN answer ENDSUBROUTINE num1  integer(USERINPUT) num2  integer(USERINPUT) menuOption  USERINPUT IF menuOption = “add” THEN addNum(num1,num2) ELSE subtractNum(num1,num2) ENDIF OUTPUT answer

In both the pseudocode and the Python code the subroutines are defined BEFORE the main program.

When you follow a route through a main program and then need to start following a subroutine this is known as “calling” a subroutine. The main difference between calling the subroutines in pseudocode and Python is how you call them if you need to get a value back from them (you are using them as a function and not a procedure).

In pseudocode the following code is sufficient: addNum(num1,num2)

But in Python you need to use the following code: answer = addNum(num1,num2)

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 35 Task 16: Explain in your own words what this flow diagram is showing you

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 36 Task 17: For the flow diagram you saw in task 16, write the pseudocode for it in the space below

Task 18: Write the same code in Python, save it and test it out to make sure it is working

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 37 Here is another example where we are just using procedures and not functions. In other words we don’t need to return any values back to the main menu.

As you can see no values are being returned to the main program. Here is what these look like in pseudocode and Python.

Pseudocode Python SUBROUTINE hello(name) OUTPUT “Hello” + name ENDSUBROUTINE

SUBROUTINE goodbye(name) OUTPUT “Goodbye” + name ENDSUBROUTINE name  USERINPUT menuOption  USERINPUT IF menuOption = “greeting” THEN hello(name) ELSE goodbye(name) ENDIF

As no values are being returned the lines RETURN variableName does not need to be included and in Python you only need the line procedureName(variables) rather than variable = procedureName(variables)

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 38 Task 19: Use the space below to write the Python code for the following flow diagram. Once you have planned your Python code on paper, try it out in Python to make sure it works. Remember to save your file with a sensible name

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 39 End of chapter recap

Task 20: Answer these questions

Question Your answer

1. What is the difference between a constant and a variable?

2. What is meant by the term “iteration”? 3. When naming constants and variables what is meant by the phrase “camel case”? 4. What shape is used in a flow diagram to show a decision needs to be made about which route to take? 5. How many inputs can a selection shape have? 6. How many outputs can a selection shape have?

7. What is a subroutine?

8. What is the difference between a procedure and a function?

9. When writing pseudocode or Python code, where should the subroutines be put: above or below the main program? 10. If you are creating a function called “repeatName” in Python and want a variable called “name” passed back to the main program, what is the correct code in the main program you would enter to do this? 11. Using the above example, what line of code will you use in the subroutine to pass the variable back to the main program?

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 40 Operators

Arithmetic operations in a programming language

Objective: Be familiar and be able to use: addition, subtraction, multiplication, real division, integer division including remainders.

Having read the previous chapter and performed the tasks within it you will already be familiar with many of these arithmetic operations.

Arithmetic Pseudocode Python Description Output operation example example Addition Adds two values together 5 + 2 5 + 2 7 Takes the second value from the first Subtraction 3 – 5 3 – 5 -2 value Multiplication Multiples two values together 4 * 3 4 * 3 12 More commonly simply referred to as Real division just “division”, it divides the first value 15 / 2 15 / 2 7.5 by the second value Also known as “whole number division”, where the first value is Integer divided by the second value but only 16 DIV 3 16 // 3 5 division shows only the digits to the left of the decimal point (the integers) This finds the remainder from an integer division. After an integer division has been performed (16 // 3) = 5 a multiplication is carried out by Remainders 16 MOD 3 16 % 3 1 multiplying that answer by the second value (5 * 3) = 15. The difference between these two values is the remainder (16 – 15 = 1)

Notice how the first four symbols are the same for pseudocode and Python, it is only the last two options which change from the words (“DIV” and “MOD”) using in pseudocode to the symbols (“//” and “%”) used in Python.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 41 Task 21: Work out the answers to these calculations

Calculation Your answer

35 + 40

82 – 4

6*11

80/2

11/2

(4+8)*2

10*(3-1)

(14+12) – (8+2)

((3-5)*2)+2

9//2

9%2

100 DIV 3

95 MOD 10

(23 // 3) *2

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 42 Relational operators in a programming language

Objective: Be familiar with and be able to use: equal to, not equal to, less than, greater than, less than or equal to, greater than or equal to.

Like before, you have already used some of these operators in previous programs:

Example Arithmetic Pseudocode Python Description (Using operation example example Python) This is used between two values to see if they are the same value. If they are Equal to = == num == 5 the same the result will be TRUE, otherwise it will be classed as FALSE This is used between two values to see Not equal to ≠ != num != 5 if they are worth different amounts This is used between two values to see Less than if the first value is less than the second < < 4 < 5 value This is used between two values to see Greater than if the first value is greater than the > > 10 > 5 second value This is used between two values to see Less than or if the first value is less than the second ≤ <= 4 <=5 equal to value or if it is equal to the second value This is used between two values to see Greater than if the first value is greater than the ≥ >= 6>=5 or equal to second value or if it is equal to the second value

One of the main differences is with the first symbol and this is one that people often get wrong. In programming there is a huge difference between the phrase “is num equal to 5” and “make num equal 5”. To help with this, programmers often use the word “assign” when they mean something equals a particular value. For instance, “num equals 5” would be referred to as “num is assigned the value of 5”. Also to help differentiate the difference they often use the phrase “equal to” for instance “Is num equal to 5?”

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 43 Task 22: Work out if these statements are true or false and place a tick in the correct column

Statement True False

5 > 3

2 < 10

10 == 14

8> 10

10 != 14

(400 / 2) != 200

12 < 10

(20 / 10) <= 3

45 >= (3 * 7)

((99 + 1) % 10) == 10

(23 DIV 10) ≤ 2

(37 MOD 5) ≠ 2

(372 DIV 50) ≥ (155 MOD 50)

(99 // 10) != (99 % 9)

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 44 Boolean operations in a programming language

Objective: Be familiar with and be able to use: NOT, AND, OR.

So far, when we have looked at selection structures (if statements) and iterative structures (loops) we have used a single condition at a time but it may be necessary to use more than one condition. The most common reason for doing this is in “between” statements. For instance, a number must be greater than or equal to 10 AND less than or equal to 20 at the same time. This can be done using an AND statement to specify that both conditions must be met. (num ≥ 10 AND num ≤ 20). Please note that the variable name (num) needs to be specified for both of the conditions as it is used in both the conditions. You could not, for example, use the phrase “num ≥ 10 AND ≤ 20” as this is not specific enough.

Arithmetic Pseudocode Python Example (Using Description operation example example Python) Both of the conditions num ≥ 10 and And need to be met for this to AND and num ≤ 20 be classed as true. Only one of the conditions num1 ≥ 10 or Or needs to be met for this to OR or num2 ≥ 100 be classed as true.

The only difference between pseudocode and Python is that pseudocode uses uppercase and in Python it is in lowercase.

There is another Boolean operator you need to be aware of and that is “not”. Not is only used to check that the condition has not been met. The condition you are testing goes inside a set of round brackets ( ) and the word not is placed in front of these brackets as shown below.

Arithmetic Pseudocode Python Example (Using Description operation example example Python) The condition must not be Not NOT not not(num == 5) met for this to be true.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 45

Task 23: Read the description and then write the correct pseudocode and Python code for that condition. Please note: “num” and “colour” are variable names

Description Pseudocode Python

“num” must be equal to 10 or equal to 20 “num” must be over 10 but also less than 100 The “colour” must not be “red” or “blue”

Using operators in iteration and selection structures

We have looked at programming concepts and now we have seen how operators can be used so now it is time for you to look at how to combine all this knowledge together.

Here is some pseudocode we have looked at before.

num  integer(USERINPUT) total  0 WHILE total < 100 FOR i  1 TO 3 total  total + num ENDFOR OUTPUT total ENDWHILE

You can see the condition “total < 100” in the while line. We can change that to any condition we want now we have looked at them.

You could change that so that it says “WHILE total ≤ 100 AND total ≥ 400” for instance, you may want to say “WHILE total != 100 OR num < 100”. Now is the time to be brave and put all that knowledge you have been gathering into practice.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 46 Task 24: Write the pseudocode for the following challenges

Challenges Pseudocode

1. Ask the user to enter two numbers. Add those two numbers together. If the total is between 20 and 50 (inclusive) display num1, otherwise display num2.

2. Ask the user to enter three different numbers and display the highest of those three numbers.

3. Set a variable called total to 0. Use a loop to ask the user to enter 5 numbers and after each input ask them if they want that number included. If they enter a “y” or a “Y” then add the number to the total. If they do not want it included, don’t add onto the total. After they have entered all 5 numbers display the total. 4. Keep asking the user to enter numbers and adding them to a total. When they enter a 7 or a number over 10, stop the loop after the new number has been added to the total. Once the loop stops display the total.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 47

End of chapter recap

Task 25: Using the challenges you have just completed create these Python programs. Test them out and save them with a sensible name. The challenges have been written again below for your convenience

Challenges 1. Ask the user to enter two numbers. Add those two numbers together. If the total is between 20 and 50 (inclusive) display num1, otherwise display num2. 2. Ask the user to enter three different numbers and display the highest of those three numbers. 3. Set a variable called total to 0. Use a loop to ask the user to enter 5 numbers and after each input ask them if they want that number included. If they enter a “y” or a “Y” then add the number to the total. If they do not want it included, don’t add onto the total. After they have entered all 5 numbers display the total. 4. Keep asking the user to enter numbers and adding them to a total. When they enter a 7 or a number over 10, stop the loop after the new number has been added to the total. Once the loop stops display the total.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 48 Data Structures

Objective: Understand the concept of data structures

A is a way of storing data in an organised way. If you were to do this manually with paper and pen most people would either write a list with items written neatly one under the other down the page. However, for more complex data structure people may use a table to help them organise the data. It is similar in pseudocode and Python. There are simple data structures which we will look at first and more complicated “2D” data structures which we will look at later in this workbook. Arrays Array = a collection

Objective: Use arrays (or equivalent) in the design of solutions of values to simple problems.

“Array” is a common term in programming but in Python “arrays” are called “lists”. To make matters worse there is a data structure called an array in Python which only allows you to store numeric data so is not used as much as lists which can store any type of data. When you hear the term “array” think of it as a “list” in Python.

One-dimensional arrays These are the simplest array structures to use. Think back to the variables we have been using, they have all been allowing a single value to be stored in a single name. That is great for small single items of data but arrays (or lists) allow you to store lots of data under a single name. Imagine a list of students in a tutor group. That tutor group may be saved under the single name “R7” but inside the tutor group “R7” are lots of individual pupils.

R7 James Anne Connor Timothy Sarah Keith

Each position in that array is numbered starting from 0 so James would be R7[0], Anne would be R7[1] , Connor would be R7[2] etc.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 49 Creating and using a 1D array To set up an array you can define it with or without the contents straight away.

Description Pseudocode Python

Creating an R7  [] empty array called “R7” Creating an R7  [“James”,“Anne”,“Connor”] array called “R7” that contains data

Once the array has been created you can print out the whole list or you can choose to print a specific item from that array. Don’t forget that it always starts counting from 0.

Description Pseudocode Python OUTPUT R7 Displays the whole array

OUTPUT R7[1] Displays item 1 from the array (in this case “Anne”)

If you wanted to overwrite an existing item (i.e. change one item to another) you can easily do that. In this example we are changing Connor to Harry so that Connor will no longer be in the list and Harry will have taken his place.

Description Pseudocode Python

Change item [2] R7[2]  “Harry” to “Harry”

You may want to see the length of the array (i.e. how many items are in the array) and this is easy to do so too.

Description Pseudocode Python OUTPUT LEN(R7) Display the length of the array/list

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 50 You may want to add a new item to the end of the array.

Description Pseudocode Python

Add an item to APPEND R7  “George” the array

You may also want to delete specific items from the list.

Description Pseudocode Python DELETE R7[1] Delete an item in the array

You may notice that when the whole array is being referred to it appears in round brackets. However, when a single item in the array is being referred to this is done using square brackets. Square brackets are always used to refer to an individual item in the array.

Task 26: Write some pseudocode which will allow the user to add to an array so that when they flip a coin and get heads they can type in the letter “h” and it will store “heads” in the array. Do the same for “t” and “tails”. If they enter an “n” they should stop adding to the array. If they enter anything apart from a “h”, a “t” or an

“n” it should display a suitable error message. Once they have stopped adding to the array, it should display the whole array

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 51 Task 27: Using the pseudocode you have planned in the previous task, write the

program in Python. Save it with a sensible name and test it out.

Task 28: Write some pseudocode which will use a loop to ask the user to enter 5 names and add these to an array called “names”. It should then display the names array in full and ask the user to enter a number. If that number is between 0 and 4 it should display the individual item and ask them if they want to delete or change that item. It should allow them to delete it or change it and then display the full

array again, showing the changes that have taken place. It may help you to break this code into subroutines. Once you have written this in pseudocode create it in python and test it out, saving it with a sensible name.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 52 Two-dimensional arrays So far we have looked at simple 1D arrays. Wow we will turn our attention to the slightly more complicated 2D arrays. In a 1D array the structure is quite flat and only allows one row of data.

R7 James Anne Connor Timothy Sarah Keith

However, in a tutor group the teacher is likely to have lots of different pieces of data for each pupil. They may need to store their maths grade, their English grade etc.

The table of data is more likely to look like this.

R7 Name Maths English James 56 72 Anne 73 78 Connor 79 48 Timothy 84 80 Sarah 37 43 Keith 50 23

Arrays are not interested in the titles of the columns, so these are ignored and instead you need to concentrate on the white section of the table where you will see that for each row there are several columns. The rows are for each individual pupil and the columns are for the score they have got in each subject.

When referring to a cell (individual piece of data) you need to identify the row and then the column. So, for instance, to get Timothy’s English score it would be R7[3][2], not forgetting everything starts counting from 0.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 53 Creating and using a 2D array Using a 2D array is very similar to using a 1D array you just need to remember to include the [row] and [column].

To create a 2D array in pseudocode you need to write:

R7  [[“James”,56,72],[“Anne”,73,78],[“Connor”,79,48]]

Notice each separate row has its own set of square brackets. Also note that data which needs to be treated as a string has speech marks but data that needs to be treated as a number (as an integer or floating point) does not have speech marks.

To create a 2D list in Python it follows the same rules:

Description Pseudocode Python OUTPUT R7 Displays the whole array

OUTPUT R7[1] Displays row 1 from the 2D array (in this case it will show [“Anne”, 73, 78]) OUTPUT R7[1][0] Displays the data in row 1 column 0 in a 2D array (in this case it will show [“Anne”]) Change item [2][1] to R7[2][1]  “Harry” “Harry”

OUTPUT LEN(R7) Find out how many rows are in the list

OUTPUT LEN(R7[1]) Find out how many columns are in one row

Add an item to the APPEND R7  [“George”,45,89] array

DELETE R7[1] Delete an entire row from the 2D array

Make a single item in a R7[0][0]  “” row blank in a 2D array. This will get rid of the name “James” and leave the row looking as ['””, 56, 72].

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 54 Task 29: Use the space below to write the pseudocode and then create the program in Python. Test it out and save it with a suitable name. This program should ask the user to enter two numbers. Add together the two numbers they have entered. Create a data structure which will store the data as [num1, num2, total] and add this to the end of a 2D array called “numbers”. It should then ask the user if they want to add another row of data and if they answer “y” it should allow

them to keep adding rows until they answer anything else. It should then ask them to enter a column number (0-2) and add up all those numbers in that column and display the answer. Try to use two subroutines in this program, one to allow the user to enter the numbers and one to add up the correct column

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 55 Traditionally arrays only allow one type of data (for instance integers, strings or Boolean etc.) but Python allows more than one type of data to be stored in a list as we have been doing with the pupils’ names (strings) and their maths and English scores (integers).

Complex data types

Objective: Use records (or equivalent) in the design of solutions to simple problems

As we mentioned earlier, traditional arrays should only allow a single type of data stored in them. This is known as a “homogeneous” data structure. Python and some other programming languages allow you to break this rule and create a list which can store different types of data structures. This is known as a “heterogeneous” data structure.

Ignoring Python, if you wanted to create a complex data structure that allows different data types you need to create a “record”. This is where the columns that a 2D array has are given titles as if they are separate variables and each of these can then be given a separate data type.

Lets look once more at our R7 tutor group 2D array.

R7 Name Maths English James 56 72 Anne 73 78 Connor 79 48 Timothy 84 80 Sarah 37 43 Keith 50 23

The column titles could be called Name, Maths and English.

In pseudocode this would be written as:

RECORD R7 Name string Maths integer English integer ENDRECORD

To refer to this in the programming you use the array name followed by a full stop “.” and then the column name for instance R7.Maths rather than using the numbers in square bracket.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 56 This is commonly used in loops so if we wanted to add up all the maths scores we could use a for loop:

total  0 FOR x in 0 TO (LEN(R7)-1) total  total + R7.Maths[x] ENDFOR OUTPUT total

This will go through each row in the array and add the maths score for each row to the total. At the end of the array it will display the total.

Please note that records are not something you need to create in Python as Python can already cope with a variety of data types in a single array.

Task 30: Write the pseudocode to create a complex 2D array that will include the name of a person and either True or False depending on if they are invited to a party. It should allow the user to add names and specify True or False. Once the array has been completed it should display how many people are coming to the party. Use subroutines to split this pseudocode into smaller sections.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 57 End of chapter recap

Task 31: Answer these questions

Question Your answer 1. What will artists  [] do?

2. In the following array, films  [“The Godfather”, “Casablanca”, “Sunset Boulevard”, “Monty Python's Life of Brian”] what would OUTPUT films[1] produce?

3. What is the difference between a simple array and a 2D array?

4. How can you add the name “King Kong” to the films array using pseudocode?

5. How would you do the same thing but in Python?

6. In the following 2D array called “ages”, how would you change “Mike” to “Andrew” in Python?

7. Why is it sometimes necessary to use “records” in pseudocode?

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 58 Input/Output and file handling

User input from the keyboard

Objective: Be able to obtain user input from the keyboard

Previously, in this workbook you have used an INPUT command in pseudocode and have expanded this slightly in Python to show the input message.

Pseudocode Python name  USERINPUT

The data type can be included to make the input command more specific.

Pseudocode Python num  integer(USERINPUT)

Displaying output

Objective: Be able to output data and information from a program to the computer display.

So far, we have only used a very simple OUTPUT command (known as a print command in Python).

Pseudocode Python

OUTPUT name

However, this is not very user friendly and it is necessary to sometimes combine the output in a suitable message.

Pseudocode Python

OUTPUT “Hello” + name

You may notice that the + symbol is used in the pseudocode. When part of a statement is a string (in this case “Hello”) the + symbol is known as concatenation (or joining) which allows values to be joined together rather than added together.

This can be altered so the variable appears anywhere in the output, rather than just joined onto the end. Just remember the strings appear with speech marks.

Pseudocode Python

OUTPUT num1+“-”+num2+“=”+ans

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 59 Reading from and writing to a text file

Objective: Be able to read/write from/to a text file.

So far in this workbook we have performed an action and then stopped. At that point any data that was stored would be lost including variables, constants and arrays. More commonly, people need to write a program that will save the data between the running of the program and this is known as a “persistent data storage” system. We will look at how this data can be stored outside of the program in a text file (.txt) which can be read by many different applications.

File location Normally text files are referred to by their name “countries.txt”. If the file is stored in the same location as the program the name of the file will usually suffice but if the file is stored in another folder on your computer or network you will need to use the full file name including the root of where the file is stored as follows:

/user/bgates/geography/countries.txt

Writing to a text file In order to write to a text file all the data needs to be converted to a string. We will be looking at how to do this with other data types later but for now you just need the following.

Data type Pseudocode Python

Integer INT_TO_STRING(num) Floating-point REAL_TO_STRING(num)

Please note the code is the same in both examples in Python as it does not matter if the original number is an integer or a floating-point number.

Lets look at some pseudocode:

country = “England” population = 53000000 file  open(“countries.txt”) newData  county + ”,” + INT_TO_STRING(population) WRITE(file,newData) CLOSE(file)

This code will set a variable called country to England and another called population to 53 million. It will then open a file called countries; if there is not one already in existence the file will be created. Then a new variable is created called newData which will join the country (England) to the

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 60 population (53 million) which is converted to a string. This data is then written to the countries text file and the file is closed. It works in a similar way in Python.

Again, the country is assigned the value “England” and the population is 53 million. The next line is different. Not only do you need to tell Python which file to open you also need to specify how that file will be used.

Code Description

Write mode, used to create a new file. Any existing files with w the same name will be erased and a new one created in its place. Read mode, used when an existing file is only being read and not being written to a Append mode, used to add new data to the end of the file

In the example we have shown, it is specifying “w” after the file name so the file will be created. The data is joined together and the population converted to a string and assigned to the variable newData and there is an additional element (+”/n). This is a line break so that if we were to add an additional line it would appear on the next line in the text file. This makes it easier later if we want to display the data on separate lines in Python. The data is written to the text file and the file is closed. It is very important the file is closed as this is when Python saves the changes to the file and if the file is not closed the new data will not be written to the file.

If you wanted to add additional rows of data to Python you would not use the “w” character at the end of the open line as this will overwrite the original data. Instead you would use the “a” character to add additional lines.

This is the same program but adapted slightly so that the user can enter the country and population and the data will be added to the existing file rather than overwriting the existing file.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 61 Task 32: Write the pseudocode which will ask the user to enter a name and then enter two numbers. Add the numbers together and work out the total. Save the name and the total in a text file called “numbers.txt”. After you have written the pseudocode create a Python file to do the same, test it out and save the file with a sensible name.

Task 33: Amend the original program you created for the previous task so that it will ask you to enter three names and three sets of numbers and will add the correct data to the numbers.txt file without overwriting the original

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 62 Reading from a text file Using the write method we looked at previously, we added a comma between each bit of data and put each record on a separate line.

To read the file we can use the following pseudocode: file  open(“countries.txt”) WHILE NOT file.ENDOFFILE() dataToRead  READ(file) OUTPUT dataToRead ENDWHILE CLOSE(file)

This will display the data stored in the countries.txt file. If you wanted each row to appear on a separate line you could use the line dataToRead  READLINE(file) instead of dataToRead  READ(file).

We can do a similar thing in Python:

As you can see, the Python program does not need to use the while loop. Python will stop automatically when it gets to the end of the file. The other difference is Python will automatically display each record on a separate row as the “/n” line break was used when the data was originally written.

Task 34: Write pseudocode which will display the data in the numbers.txt file you created earlier. Once you have written the pseudocode create a Python program to do the same, test it out and save it with a sensible name

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 63

End of chapter review

Task 35: Create a Python program which will ask the user to enter 10 numbers. If the number is an even number (i.e. when it is divided by 2 there is no remainder) add it to a text file called even.txt. If it is an odd number add it to the file called odd.txt. Once they have entered all 10 numbers it should ask them if they want to see the odd or the even numbers and display the numbers from the correct file. Use subroutines to split the code into manageable chunks. Use this page to make notes and scribbles that you think may help you with creating the program.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 64 String handling operations

Objective: Understand and be able to use: length, position, substring, concatenation, convert character to character code, convert character code to character, string conversion operations.

Strings are a useful way or storing any data that you do not need to perform calculations with. However, there are times when you need to be able to select a part of a string, manipulate a string or convert it to another data type. This is what we will be looking at in this chapter.

Length

To find the length of a string use the following:

Pseudocode Python

LEN(name)

For instance, using the Python code, we could ask for a name and then find out the length of the name as follows:

Position

Position will find out where in the string a character appears. Don’t forget it will start counting from 0. In this example it will find the letter “k” in the name and display the number of the position.

Pseudocode Python letterPos  POSITION(name,”k”) OUTPUT letterPos

In Python if the letter cannot be found it will return the value of -1.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 65 Substring

A substring is a group of two or more characters that appears inside another string. For instance, “the best of” is a substring of “It was the best of times”. The substring can be found as long as you know the start position and the end position of the string you are looking for.

Pseudocode Python message  “Chewie, we’re home.” OUTPUT SUBSTRING(8,12,message)

Don’t forget Python needs an extra position counted at the end otherwise it will stop when it reaches the last letter and not show it.

Task 36: Write some pseudocode so that the user types in a message and then they are asked for a letter in that sentence. It should then display from that letter to the end of the message. Once you have written it in pseudocode create it in Python,

save it with a sensible name and test it out

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 66 Concatenation

Concatenation means joining two strings together and this is done using the + symbol in both pseudocode and Python.

Please note, the “ ” has been added in the middle to join the names with a space between them.

Character codes

All characters are stored by a computer as binary numbers which can be shown as a number called ASCII. The Table below shows how each upper and lower-case letter is represented along with numbers and some symbols.

Character ASCII Character ASCII Character ASCII A 65 a 97 (space) 2 B 66 b 98 0 48 67 c 99 1 49 68 d 100 2 50 E 69 e 101 3 51 F 70 f 102 4 52 G 71 g 103 5 53 H 72 h 104 6 54 I 73 i 105 7 55 J 74 j 106 8 56 K 75 k 107 9 57 L 76 l 108 ! 33 M 77 m 109 " 34 N 78 n 110 # 35 O 79 o 111 $ 36 P 80 p 112 % 37 Q 81 q 113 & 38 R 82 r 114 ' 39 S 83 s 115 ( 40 T 84 t 116 ) 41 U 85 u 117 * 42 V 86 v 118 + 43 W 87 w 119 , 44 X 88 x 120 - 45 Y 89 y 121 . 46 Z 90 z 122 / 47

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 67 If you want to know the ASCII code for a character you can convert that character to the corresponding ASCII code very easily.

Pseudocode Python letter  USERINPUT OUTPUT CHAR_TO_CODE(letter)

If you knew the ASCII code and wanted to convert this to the character, you can easily do this too.

Pseudocode Python num  integer(USERINPUT) OUTPUT CODE_TO_CHAR(num)

String conversions

As you have seen, when we wrote to a text file, (see page 60) we had to convert an integer to a string. There may be other occasions when this is necessary. For instance, if you want to join a number to a string to make an identification number. This can easily be done in both pseudocode and Python.

Converting string to integer Pseudocode Python

STRING_TO_INT(stringName)

Converting string to real (floating-point) Pseudocode Python

STRING_TO_REAL(stringName)

Converting integer to string Pseudocode Python

INT_TO_STRING(num)

Converting real (floating-point) to string Pseudocode Python

REAL_TO_STRING(num)

You may notice that the Python is very simple. Python doesn’t really care about the current data type and only needs to know what you are converting it to (int, float or str) whereas the

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 68 pseudocode is much more specific and needs you to know the current data type and the required data type you are converting it to.

Lets look at some of these conversions in practice. Remember our tutor group called R7?

At present they are all in Year 7 and this is shown in their tutor group name “R7”. Next year they will be in year 8 and so here is a program which will change the current tutor group name from R7 to R8.

Here it split the tutor group name into a letter and a number and converts that number to an integer. This can then be altered with a calculation (in this case adding 1) and then converted back into a string so it can be once more joined to the letter to make the new tutor group name.

End of chapter recap

Task 37: Create a Python program which will ask the user to enter their date of birth in the format dd/mm/yyyy. It should also ask them to enter their first name and then enter their surname. The program should take the digits for the date of birth and add them together (for instance if the date was 13/02/2002 it should add together 1 + 3 + 0 + 2 + 2 + 0 + 0 + 2 = 10). It should join the first 3 digits of their surname to the last letter of their first name and join this to the number that was created. So, if their name is Jemima Puddle-Duck and their date of birth was the 13/02/2002 the program should display Puda10. Make sure you save the program with a sensible name and test it out

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 69 Random number generation

Objective: Be able to use random number generation.

For the AQA GCSE (9-1) Computer Science (8520) you do not need to know about random number generation in pseudocode, so we will concentrate our efforts on Python only for this section.

Random numbers are not part of the standard of commands in Python so in order to use them you need to import an additional library at the start of your program. You do this by entering the code “import random” as the first line in your program.

If you want a random number between 0 and 1 which includes lots of decimal places use the following code:

If, however, you only want a whole number between two numbers you specify (in this case 1 and 100) use this code:

End of chapter recap

Task 38: Create a Python program which will ask the user for a low number and a high number and will generate a random whole number between those two values, but do not display it. Ask the user to guess the number and if they have

not guessed correctly tell them if they are too high or too low. Keep asking them to guess until they guess correctly and then display a message “You took [guess] guesses” where [guess] is the number of guesses they took to guess correctly

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 70 Structuring programming

Objective: Describe the structured approach to programming.

Some people can sit down and write a program without much planning, their brains just seem to be work that way. But even those people need to take a more structured approach when they have a large complicated program or when they are working as part of a programming team. Ask any programmer how they tackled a problem and most of them will explain that they took the following steps, even if they didn’t formally write it down anywhere.

Step 1: Analyse the problem

Look at the problem and highlight what is important. This is known as Abstraction. Work out what is important and what is not important.

Take this problem.

“Hi, I’m Sandra and I love painting people’s houses. Sometimes they choose a really lovely colour and I think that would be nice in my home but other times they pick something really dodgy and I wonder if they are mad! Anyway, I want you to help me. I need you to write me a program that I can use to work out how much I should charge for each job. You know the type of thing, I go in there and measure up and work out how big each wall is. I only work in rectangles I’m afraid and if there is an odd shape I just assume it is a rectangle to make it easier. There is usually more than one wall and they are always different sizes, honestly why can’t builders make everything the same size, it would make my life a lot easier. The customer also tells me what colour paint they want and I go out and get it so I have to charge them for that but luckily I go to a special supplier that charges £5 for a pot of paint and each pot covers 25 m2 and I only want to get the correct number of pots of paint that I need, I don’t want to be getting too many. Usually I do two coats as it gets a better finish but obviously I need twice the paint to do that so it is up to the client if they want two coats or not. Most of them do. I also charge for my time at £50 for every 10m2 that I complete but if there is less than 10m2 I still charge £50. Can you do that for me?”

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 71 Task 39: Read through Sandra’s statement again and underline any areas you think are important for the program

Task 40: Use the space below to list the main objectives that the program needs to be able to perform

Now you need to look at the data that is involved.

Task 41: List the variables that you will need and identify the data types. You will come back to this list and add to it later as you plan the solution in more detail but for now all you need to do is start to consider the data that you will be using

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 72 Step 2: Interpret the problem as a sequence of sub-problems

When you are faced with a large problem it will seem impossible to sort out at first, so you have to break it down into much smaller problems. This is known as Decomposition. By breaking down the task into more manageable parts you can focus on just a small section at a time and get that part working before you move onto the next stage.

Lets break down Sandra’s decorating program into smaller chunks:

Look back at the main objectives you wrote for task 40. You have already started to break down the problem into smaller sections. By decomposing the problem, you have already highlighted the subroutines you need to include.

We could break down some of those tasks further:

Consider the parameters that need to be passed to it and values that need to be returned back to the main program.

Once you have broken down the project into small manageable chunks that you feel you can tackle you need to plan the interaction between the chunks. This involves planning the data that needs to be passed to each section.

We cannot, for instance, buy the paint until we have worked out the size of the walls that need to be painted. Therefore the first thing we need to do is find out the size of the walls.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 73 Now we are at the stage of designing the solution.

Step 3: Design the solution

It is easier to plan your program by thinking about the steps involved, putting them in a logical order. We are using a table to help us structure this. We are also specifying the inputs and outputs of each of these subroutines

Subroutine Input(s) Processes Return Value wallArea Prompt the user to enter the totalArea number of walls (numberOfWalls) and use a loop to ask for the width (widthOfWall ) and height (heightOfWall ) of each wall. Multiply width by height and add these for a total area. coatsOfPaint Prompt the user to enter the coats number of coats of paint (coats) buyPaint totalArea Whole number division of paintCoverage totalArea by 25 and if there is any coats remainder add 1 to find the total costPaint number of pots of paint. Multiply by coats to find the paint area (paintCoverage). Multiply by £5 to get cost of paint (costPaint) labourCosts paintCoverage Whole number division of paint labourCharge area (paintCoverage) by 10 then multiply by £50 to get the labour amount (labourCharge) totalCost costPaint Add together the cost of the totalCharge paint (costPaint) and the labour labourCharge amount (labourCharge). Display the total.

Task 42: Go back to task 41 and add to the list to include any variables that you had not considered and identify the data type for each. Your names will probably differ from those identified in the table above but it is up to you on the name that you

decide

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 74 Step 4: Creating a program

After you have planned your program you can create it. There are a few things to consider when writing your program which will make it much easier for others to make sense of what you have done later.

• Use white space to split up sections of your code • Use relevant and descriptive variable and subroutine names • Use comments to explain what you have done

White space Leaving blank lines in your code will not make any difference to how that code runs with one exception. You cannot leave a blank line in subroutines. Python reads these blank lines as being at the end of the subroutine (rather than having to use the ENDSUBROUTINE line that pseudocode requires).

Keep sub routines in Python as a continuous block but use blank lines at other areas to show where natural breaks will occur. In this example a blank line is used between each subroutine and further down between the inputting of the data and selecting the column number.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 75 Relevant and descriptive names Use descriptive names which tell the reader what that variable or subroutine will do. This makes the world of difference. Reserve using those 1 letter variable names for counting loops etc where the variable will not be used elsewhere.

Comments Comments can be used in two ways:

• To add description and explain what is happening • To block out bits of code while you test others.

If you are using a comment to add description this can be either for the whole line or added at the end of the line. Comments are created by using the # symbol.

As you can see comments can be above a section of code and take up a whole line or added to the end of a line. Python will ignore any text from the # to the end of the row.

Programmers often use comments to block out sections of code they do not want to test. For instance, if you have a long program and it went through lots of processes before it gets to the section you want to test you can add comments to block out all of these sections you don’t want to run so you can quickly check the part of the program you are currently working on. Many Python editors allow you to highlight sections of code and add comments automatically specifically for this purpose.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 76 The advantages of using a structured approach

Objective: Explain the advantages of the structured approach.

By following this three-step approach, you have planned your solution and there should be no surprises when you start to develop the solution. You know the variables you are using and you know about the processes that each subroutine needs to perform and how they link together. Often programmers work as part of a team and by following a structured approach they can all work on different subroutines simultaneously, knowing how they will fit together later. This saves time rather than waiting for each subroutine to be finished before the next is started. It also allows you to document how you approached the problem so if another programmer needs to make sense of it later, they are aware of why you made particular decisions and can update the program accordingly as they are aware of how it works together as a whole.

Task 42: Pick one of the subroutines listed in step 3 and write it in pseudocode

End of chapter recap

Task 43: Create the program for Sandra, save it with a sensible name and test it out. Use blank lines and comments to make your program easier for others to read

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 77 Robust and secure programming

Objective: Be able to write simple data validation routines.

Data Validation

Data Validation = when the program checks that the data the user has inputted is suitable

This has been done to some extent with specifying the data type however we could go much further.

You can:

• Check if a string is a minimum or maximum length • Check if a string is empty • Check that a string has been inputted in the correct case • Check if a number lies between a given range

Some of these things can be automatically corrected by the computer (for instance if a string has been inputted in lower case you can add code to change it to uppercase if that is what you are expecting.) Alternatively, if they enter a string that is too long you can trim down the string to the correct length rather than asking the user to input it again.

However, some cannot be automatically altered and you need to make a decision as to whether you ask the user to keep entering the data until they enter something that falls within the rules or to stop the program.

Using a loop to force the user to try again

Pseudocode Python accepted  false WHILE accepted = false num  integer(USERINPUT) IF num ≥ 5 AND num ≤ 10 THEN OUTPUT “Thank you” accepted  true ENDIF ENDWHILE

Here we are using a while loop that will keep repeating until the number that has been entered is valid (i.e. between 5 and 10).

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 78 Task 44: Write some pseudocode that will ask the user to input a word. If they enter a word that has fewer than 3 characters, ask them to try again until they do enter a word that has 3 characters or more. Once you have planned the pseudocode create the program in Python, test it out and save it with a sensible name

Task 45: Create a Python program which will ask the user to enter their name. If they leave it blank three times, display an error message and stop the program

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 79 Creating menus

One easy way for users to enter the commands and options they want is to display a menu for them and they can then enter a letter or a number to select the option they want.

Have a look at this program.

It shows another way of validating data. By giving them a menu and set options to choose from you can use an if statement to give the correct response, depending on how they answer.

Below is the same program but uses letters for the options and whatever letter they type in is converted to lowercase before the if statement starts.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 80 Task 46: Create a Python program that will ask the user to input two numbers between 1 and 100. Use a subroutine to find out if the data is valid or not. After valid numbers have been inputted the program should show them a menu giving them the option to either add or multiply the numbers together and keep asking for their menu selection until they enter a valid option. Use subroutines to perform the correct calculation and display the final answer in a user-friendly format (i.e. display a message such as “The answer is…”)

Try and catch

Sometimes the user can make a mistake and crash the program which can be very frustrating. Instead of letting the program crash it is much more user friendly to show them an error message so they can try again. This is where the “Try and catch” can help you.

Pseudocode Python num  USERINPUT TRY num  STRING_TO_INT(num) OUTPUT “This is a number” CATCH OUTPUT “This is not a number”

It works in a similar way to an if statement but instead of crashing the program it will run the catch (or except) block.

This is particularly useful when writing to a text file. If you are not sure if the file already exists, you do not want to overwrite an existing file with a new one so you could try to see if you can write to the existing file and if it is not already there it could create it.

As you can see from the Python program above it will try to append the data to an existing file but if that file is not there it will create the file first and then write the data to the file.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 81 Creating a simple authentication routine

Often a computer system will require a user to log in to make sure they are authorised to use the system. You are going to create a simple authentication system.

Task 47: Create a Python program which will ask the user to input a new user ID and password. The user ID must be saved in lowercase (no matter how they type it in) and have at least 4 characters. The password must have at least 8 characters. Don’t worry about making the password more secure by forcing them to have upper and lowercase letters, numbers and symbols, that is not a necessary level of detail you need for the GCSE. Once the user has entered a valid user ID and password you must save the data to a text file called “passwords.txt”. Save your Python program and test it out a few times to add several valid user IDs and passwords to the file

You can now use that file for the next challenge.

Task 48: Create another program that will use the password.txt file you created in the last program. You need to ask the user to input a user ID and a password. If they are in the password.txt file display a suitable message i.e. “Access granted” or if they are not in the file, it displays another message i.e. “Incorrect User ID or

password”. If they fail to log in three times it should say a suitable message i.e. “Access Denied” and stop the program

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 82 Testing your programs

Objective: Be able to select suitable test data that covers normal (typical), boundary (extreme) and erroneous data. Be able to justify the choice of test data.

Once you have created a program you can’t sit back with a smug look thinking that you have finished. You haven’t. You still need to test the program works. You may well have been testing small parts of your program as you go to make sure it mechanically works and are satisfied you have got rid of the syntax (typo) errors. You have added all the brackets where needed and changed the odd = to a == where necessary but you still haven’t finished. Now you need to think about the users of the system and how they may enter incorrect data.

Think about this program:

It will generate a random number between 1 and 10 and ask the user to guess. It will test if that number can be converted to an integer and if it can it will convert it to an integer and test to see if it is the same as the computer’s random number. If it is, the program will display the message “Well done” otherwise it will display “Wrong”. If they entered something that is not an integer, it will give them an error message telling them “It has to be an integer” and gives an example.

To find out if this program is really working correctly we would have to run it several times to test lots of eventualities. We record these in a test table and most of the test table should be filled in before the test is run.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 83 Test table Test Result Description Input data Expected outcome number (Pass/ fail) Test if they enter the 1 Same as compNum Output “Well done” correct number Test if they enter the Integer but different 2 Output “Wrong” wrong number to compNum Test if they enter a Output “It has to be 3 number with decimal 4.5 an integer e.g. 5” point Test if they enter a Output “It has to be 4 Five string an integer e.g. 5”

Obviously, it would be difficult to test if they are entering the same value or a different value to the compNum unless you can see what the number is so often the tester will add a temporary print line to their program so they can see the number the computer is working with while they test the program as shown below:

Now we can test the program and fill in the last column:

Test Result Description Input data Expected outcome number (Pass/ fail) Test if they enter the 1 Same as compNum Output “Well done” Pass correct number Test if they enter the Integer but different 2 Output “Wrong” Pass wrong number to compNum Test if they enter a Output “It has to be 3 number with decimal 4.5 Pass an integer e.g. 5” point Test if they enter a Output “It has to be 4 Five Pass string an integer e.g. 5”

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 84 What sort of data should you test? There are three types of data you should consider.:

• Normal (typical) data • Boundary (extreme) data • Erroneous data

Normal data is data you are expecting, for instance if you are asking for an integer between 1 and 10 you should test some data that is an integer between 1 and 10, for instance 4.

Boundary data is data that is on the boundaries. If you are asking for a number between 1 and 10 inclusive, then test 1 and 10 as well as 0 and 11 to check that the boundaries of the range are working as you expect.

Erroneous data is data that is just wrong. If you are asking for an integer test what happens when you enter a number with a decimal point or a string?

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 85

Task 49: Look at the program above. There are several errors with the program and you will use the following test table to test it out and identify where the errors are. If you prefer, you can type in the program EXACTLY as it is shown in Python to run the tests. The program should ask the user to enter two letters which should be

saved as uppercase and a single digit integer (0-9) that the user also enters. It should then display the complete code as a single string to the user

Test Result Description Input data Expected outcome number (Pass/ fail) Enter two letters in uppercase and a 1 AB & 5 AB5 number in range (normal data test) Enter two letters in lowercase and a 2 cd & 5 CD5 number in range (normal data test) Enter three letters in Output “Incorrect uppercase and a 3 A letter choice” before number in range number is entered (boundary test) Enter two letters in uppercase and a 4 AB & 0 AB0 number in range (boundary test) Enter two letters in uppercase and a 5 AB & 9 AB9 number in range (boundary test) Enter two letters in uppercase and a Output “Incorrect 6 AB &10 number out of range number choice” (boundary test) Enter two letters in uppercase and a Output “Incorrect 7 AB & “One” string as the number number choice” (erroneous test)

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 86 End of chapter recap

Task 50: Match the test type and test data with the correct description

Test type or Test data Description

Type check Correct, typical data

Test the program responds appropriately if the Presence check wrong type of data is inputted

Values at the extremes of what should and Normal data shouldn’t be accepted

Boundary data Data that is incorrect

Test the program responds appropriately if the Erroneous data input is left blank or empty

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 87 Classification of programming languages

Objective: Know that there are different levels of programming language: low-level language, high- level language. Explain the main differences between low-level languages and high-level languages.

Most computer programming languages are written in a high-level programming language. This means that the use common English words to make it more understandable and to speed up the process of writing and debugging programs. Computers, however, use their own language written using binary called Machine code. This is known as a low-level language.

Low-level languages

Objective: Know that machine code and are considered to be low-level languages and explain the difference between them. Understand that machine code is expressed in binary and is specific to a processor or family of processors.

The processor inside a computer uses machine code which is represented by binary numbers. Every different type of processor has its own machine code storing the way in which instructions are processed by the logic gates that are on the CPU chip.

Douglas Hofstadter, an American professor of cognitive science, said "Looking at a program written in machine language is vaguely comparable to looking at a DNA molecule atom by atom”

To use machine code to add two numbers involves knowing where in the memory each of the numbers you want to add are presently stored, where in the memory the addition process is stored and where in the memory the answer is to be stored. Each of these instructions are broken down into the operation (for instance retrieve, add, store) and the memory address that contains the data or the instruction (for instance add).

Machine code is stored in binary and looks a little like this:

00100010 10110101 01001101 01011101 00100010 00010101 11010100 10111001

As you can image this is not very user friendly.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 88 Assembly language is slightly more user friendly but is still too technical for most people to understand and only specialist programmers can work using it. Assembly language is also made up from two sections. The instruction and the address of where the data or operator is stored.

The machine code we looked at previously could be converted to assembly language as follows:

LOAD 181 ADD 93 LOAD 21 STORE 185

It is still not very user friendly, but it is better than working directly with machine code.

However, a CPU can only understand machine code so anything written in assembly language still needs to be translated into machine code for this to work. This is quite a fast process as there is a direct translation that can occur between the instruction and the address number.

Assembly language is often used to develop simple programs such as those used in embedded systems like washing machines or traffic lights where the program is unlikely to change and it only needs to control specific hardware components.

It is also used by people in cases of computer forensics or brute-force cyber-attacks and is sometimes used in extreme cases of debugging code to determine exactly what’s going on but can only generally be done by people with very specialist knowledge.

High-level languages

Objective: Understand that ultimately all programming code written in high-level or assembly language must be translated into machine code.

Programming languages such as Python, Java, SQL and C++ are all classed as high-level languages as they have been developed to be a little like a human language. They use English words to make the programming a lot easier and a single command can perform what would take up several lines of machine code.

As there is a greater difference between what is created by a programmer using a high-level language and the machine code, the computer needs the instructions to be stored in and needs to be translated to make it work.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 89 Task 51: Write the advantages and disadvantages of low-level programming languages and high-level programming languages

Language Advantages Disadvantages

Low-level

High-level

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 90 Translators

Objective: Understand that there are three common types of program translator: interpreter, and assembler. Explain the main differences between these three types of translator. Understand when it would be appropriate to use each type of translator.

Interpreter Once the program has been created it will be saved and then can be run. At this point the programming language translates every line one at a time and executes them straight away. Every time the program runs it has to be translated again as there is no secondary file that is created to store the machine code and therefore must be translated afresh each time the program is run. This makes interpreted code slower to run than compiled code but it shows any errors as soon as it finds a problem, so it is easier to debug than compiled code. Python, Basic and Pascal are all interpreter-based programming languages.

Compiler A compiler translates the whole program into machine code before the program is run. The machine code is saved and stored in a separate file to the high-level programming language. Once the programmer has created the program they need to request it to be compiled before they can run and test the file which can take a while. This can make testing small sections of the program slower as the whole program needs to be compiled before any of it can be run. However, as the whole file will be compiled the running of the program is much quicker and unless changes are made it will not need to be compiled again each time it runs. Overall, once the program is finished programs created in compiler languages are faster to run. Java and C++ are compiler programming languages.

Assembler An assembler translates assembly language into machine code and is effectively a compiler for the assembly language but can also be used interactively like an interpreter.

Task 52: Without looking at the descriptions above, label the three types of translator

Translates one line at a time Translates the whole program Translates assembly language into machine code and runs into machine code before it into machine code them straight away runs any of it

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 91 End of chapter recap

Task 53: Answer these questions

Question Your Answer 1. What is machine code?

2. What is assembly language?

3. Give an example of a high-level language.

4. What is the difference between a low-level language and a high-level language?

5. Why would somebody program using a low-level language?

6. Why would somebody program in a high-level language?

7. What does a translator do?

8. What is the difference between an interpreter and a compiler?

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 92 Answers

Task 1 Scenario Pseudocode Ask the user to enter a num  integer(USERINPUT) whole number. Add 5 to total  num + 5 that number and display OUTPUT total the new total. Ask the user to enter a number which allows num  real(USERINPUT) decimal places and divide answer  num / 2 (/) that by 2. Display the OUTPUT answer answer. Ask the user to enter their age  integer(USERINPUT) age. If they are over (>) IF age > 17 THEN 17 save a variable called adult  true adult to true, otherwise ELSE save the variable called adult  false adult to false. ENDIF Ask the user to input their first name and save this as name  USERINPUT a string. Display their OUTPUT name name. Task 2 Scenario Python Ask the user to enter a whole number. Add 5 to that number and display

the new total. Ask the user to enter a number which allows decimal places and divide (/) that by 2. Display the answer. Ask the user to enter their age. If they are over (>) 17 save a variable called adult to true, otherwise save the variable called

adult to false. Ask the user to input their first name and save this as a string. Display their name.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 93 Task 3

Data Type Definition Example of this data type Integer A whole number 45 Real A number that allows decimal places 2.5 Boolean Only allows one of two possible values True Character A single symbol, letter, number etc “a” A series of characters grouped into one String “Computers” piece of data Task 4

Task 5

Task 6 Question Your Answer How is the variable num assigned? The user will input the number they want What is the value of the constant that is 5 used in this pseudocode? Variable as it will change depending on Is total a variable or a constant? what the user inputs for the num variable How is the total calculated? num * multiplyer If the user inputted 10 when prompted to enter a number, what would the output 50 of the program be?

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 94 Task 7 Question Your Answer How is the variable x assigned? The user will input the number they want What is the value of the constant that is 10 used in this Python code? How is the value of the constant The equal symbol assigns the value of 10 assigned? to the z constant If the user enters 50, what will the output “Too high” be? If the user enters 3, what will the output 13 be? Task 8 Task Pseudocode Ask the user to input a number num  integer(USERINPUT) and keep adding 10 to that REPEAT number until the number is num  num + 10 over 50. Once it is over 50 UNTIL num > 50 display the total. OUTPUT num Ask the user to enter a start startNum  integer(USERINPUT) and an end number (use two startNum  integer(USERINPUT) prompts to do this). Display FOR x  startNum to endNum the numbers between those OUTPUT x two values. For instance if ENDFOR they enter 5 and 10 it should show 5, 6, 7, 8, 9 and 10 in the output. Ask the user to enter a num  integer(USERINPUT) number. While that number is WHILE num < 50 under 50 keep asking them to num  integer(USERINPUT) enter the number again. ENDWHILE When they successfully enter a number which is worth 50 or more stop asking them. Task 9

This will keep asking the user to enter a This will count down from 10 to 1 number until they enter a number under 5. It then display the message “Blast off!” will then display that number. Indefinite iteration Definite iteration Task 10 Pseudocode Python code num1  integer(USERINPUT) num1  integer(USERINPUT) IF num1 > num2 THEN OUTPUT num1 ELSE OUTPUT num2 ENDIF

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 95 Task 11 Pseudocode Python code again  “y” WHILE again = “y” name  USERINPUT num  integer(USERINPUT) FOR x  1 TO num OUTPUT name ENDFOR again  USERINPUT ENDWHILE Task 12 num  integer(USERINPUT) IF num = 7 THEN OUTPUT “Thank you” ENDIF Task 13

Task 14 colour  USERINPUT IF colour = “red” THEN OUTPUT “Thank you” ELSE IF colour = “blue” THEN OUTPUT “Well done” ELSE OUTPUT “Incorrect” ENDIF Task 15

Task 16 It will ask the user to input two numbers. It will add these together and find out the total. If that total is over 50 it will run the largeNum function which will multiply num1 by 2 and then add on num2 to get the answer. This will then be returned to the main program. If the total is not over 50 it will run a different subroutine called smallNum which will multiply the total by 2 and store that as the answer. It will also return the answer back to the main program. In the main program the answer will be displayed, and the program will stop.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 96 Task 17 SUBROUTINE largeNum(num1,num2) answer  (num1 * 2) + num2 RETURN answer ENDSUBROUTINE

SUBROUTINE smallNum(total) answer  total * 2 RETURN answer ENDSUBROUTINE

num1  integer(USERINPUT) num2  integer(USERINPUT) total  num1 + num2 IF total > 50 THEN largeNum(num1,num2) ELSE smallNum(total) ENDIF OUTPUT answer Task 18

Task 19

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 97 Task 20 Question Your answer A constant value is one that does not 1. What is the difference between a change throughout the running of the constant and a variable? program and a variable does change it’s value. 2. What is meant by the term Iteration is when code repeats itself. “iteration”? This is when a variable or constant has 3. When naming constants and variables been given a name that is made up of two what is meant by the phrase “camel or more words. Each word starts with an case”? uppercase letter and the spaces between the words are removed. 4. What shape is used in a flow diagram to show a decision needs to be made A diamond shape about which route to take? 5. How many inputs can a selection One shape have? 6. How many outputs can a selection Two shape have? A subroutine is a small block of 7. What is a subroutine? code(outside the main program) that performs a specific task. A function returns a value back to the 8. What is the difference between a main program but a procedure doesn’t procedure and a function? pass a value back to the main program. 9. When writing pseudocode or Python code, where should the subroutines Above the main program be put: above or below the main program? 10. If you are creating a function called “repeatName” in Python and want a variable called “name” passed back to name = repeatName() the main program, what is the correct code in the main program you would enter to do this? 11. Using the above example, what line of code will you use in the subroutine to return name pass the variable back to the main program?

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 98 Task 21 Calculation Your answer 35 + 40 75 82 – 4 78 6*11 66 80/2 40 11/2 5.5 (4+8)*2 24 10*(3-1) 20 (14+12) – (8+2) 16 ((3-5)*2)+2 6 9//2 4 9%2 1 100 DIV 3 33 95 MOD 10 5 (23 // 3) *2 8 Task 22 Statement True False 5 > 3 ✓ 2 < 10 ✓ 10 == 14 ✓ 8> 10 ✓ 10 != 14 ✓ (400 / 2) != 200 ✓ 12 < 10 ✓ (20 / 10) <= 3 ✓ 45 >= (3 * 7) ✓ ((99 + 1) % 10) == 10 ✓ (23 DIV 10) ≤ 2 ✓ (37 MOD 5) ≠ 2 ✓ (372 DIV 50) ≥ (155 MOD 50) ✓ (99 // 10) != (99 % 9) ✓ Task 23 Description Pseudocode Python num == 10 or num == “num” must be equal to 10 num = 10 OR num = 20 or equal to 20 20 “num” must be over 10 but num > 10 AND num < num > 10 and num < also less than 100 100 100 The “colour” must not NOT(colour = “red” not(colour == “red” “red” or “blue” OR colour = “blue”) or colour == “blue”)

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 99 Task 24 Challenge Pseudocode 1. Ask the user to enter two num1  integer(USERINPUT) numbers. Add those two num2  integer(USERINPUT) numbers together. If the total  num1 + num2 IF total ≥ 20 AND total ≤ 50 THEN total is between 20 and OUTPUT num1 50 (inclusive) display ELSE num1, otherwise display OUTPUT num2 num2. ENDIF 2. Ask the user to enter num1  integer(USERINPUT) three different numbers num2  integer(USERINPUT) and display the highest of num2  integer(USERINPUT) IF num1 > num2 AND num1 > num3 THEN those three numbers. OUTPUT num1 ELSE IF num2 > num1 AND num2 > num3 OUTPUT num2 ELSE OUTPUT num3 ENDIF 3. Set a variable called total total  0 to 0. Use a loop to ask FOR x  1 to 5 the user to enter 5 num  integer(USERINPUT) included  USERINPUT numbers and after each IF included = “y” OR included = “Y” input ask them if they THEN want that number total  total + num included. If they enter a OUTPUT total “y” or a “Y” then add the number to the total. If they do not want it included, don’t add onto the total. After they have entered all 5 numbers display the total. 4. Keep asking the user to total  0 enter numbers and REPEAT adding them to a total. num  integer(USERINPUT) total = total + num When they enter a 7 or a UNTIL num == 7 OR num > 10 number over 10, stop the OUTPUT total loop after the new number has been added to the total. Once the loop stops display the total.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 100 Task 25 Challenge Python 1.

2.

3.

4.

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 101 Task 26 coinToss  [] again  true WHILE again = true ans  USERINPUT IF ans = “h” THEN APPEND coinToll  “heads” ELSE IF ans = “t” THEN APPEND coinToss  “tails” ELSE IF and = “n” THEN again = false ELSE OUTPUT “Invalid option” ENDIF ENDWHILE OUTPUT coinToss Task 27

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 102 Task 28 SUBROUTINE addNames(names) FOR x  1 – 5 newName  USERINPUT APPEND names  newname ENDFOR RETURN names ENDSUBROUTINE

names  [] names  addNames(names) OUTPUT names position  integer(USERINPUT) IF position ≥ 0 AND position ≤4 THEN option  USERINPUT IF option = “d” THEN DELETE names[position] ELSE names[position]  USERINPUT ENDIF OUTPUT names ENDIF

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 103 Task 29 SUBROUTINE enterNumbers(numbers) again = “y” WHILE again = “y” num1  integer(USERINPUT) num2  integer(USERINPUT) total  num1 + num2 newRow = [num1,num2,total] APPEND numbers  newRow again  USERINPUT ENDWHILE RETURN numbers ENDSUBROUTINE

SUBROUTINE addNumbers(numbers, col) colTotal  0 FOR x  0 TO (len(numbers)-1) colTotal  colTotal+ numbers[x][col] ENDFOR RETURN colTotal ENDSUBROUTINE

numbers  [] numbers  enterNumbers(numbers) col  integer(USERINPUT) IF col ≥ 0 AND col ≤ 2 THEN colTotal  addNumbers(numbers, col) OUTPUT colTotal ENDIF

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 104 Task 31 Question Your answer What will artists  [] do? It will create a blank array called artists In the following array, films  Casablanca [“The Godfather”, “Casablanca”, “Sunset Boulevard”, “Monty Python's Life of Brian”] what would OUTPUT films[1] produce? What is the difference between a A simple array only allows a single set of data simple array and a 2D array? but a 2D array contains multiple rows and multiple columns How can you add the name “King APPEND films  [“King Kong”] Kong” to the films array using pseudocode? How would you do the same thing but in Python? 9. In the following 2D array called “ages”, how would you change “Mike” to “Andrew” in Python?

Why is it sometimes necessary to use Arrays would only traditionally allow a single “records” in pseudocode? type of data throughout the whole array but by using records it allows each field to specify its own individual data type. This is not necessary in Python lists Task 32 name  USERINPUT num1  integer(USERINPUT) num2  integer(USERINPUT) total  num1 + num2 file  OPEN(“numbers.txt”) newData  name + “,” + INT_TO_STRING(total) WRITE(file,newData) CLOSE(file)

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 105 Task 33

Task 34 file  open(“numbers.txt”) WHILE NOT file.ENDOFFILE() dataToRead  READ(file) OUTPUT dataToRead ENDWHILE CLOSE(file)

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 106 Task 35

Task 36 message  USERINPUT letter  USERINPUT letterPos  POSITION(message,letter) end  LEN(message)-1 OUTPUT SUBSTRING(letterPos,end,message)

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 107 Task 37

Task 38

Task 39

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 108 Task 40 • Must be able to input multiple walls of different sizes • Work out the total size of the job • Work out the number of pots of paint that are needed (whole pots only no part pots) • Must be able to select the number of coats that are needed (labour and paint costs will increase if two coats required) • Work out the cost for labour • Client needs to be able to see the total cost for the job Task 41 numberOfWalls = integer widthOfWall = real heightOfWall = real totalArea = real coats = integer pots = integer paintCoverage = real costPaint = real blocks = integer labourCharge = real totalCharge = real Task 43

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 109 Task 44 accepted  false WHILE accepted = false word  USERINPUT lengthOfWord  LEN(word) IF lengthOfWord ≥ 3 THEN OUTPUT “Thank you” accepted  true ENDIF ENDWHILE

Task 45

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 110 Task 46

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 111 Task 47

Task 48

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 112 Task 49 Test Expected Result (Pass/ Description Input data number outcome fail) Enter two letters in uppercase and a number 1 AB & 5 AB5 Pass in range (normal data test) Enter two letters in lowercase and a number 2 cd & 5 CD5 Fail in range (normal data test) Output Enter three letters in “Incorrect uppercase and a number letter choice” 3 A Pass in range before (boundary test) number entered Enter two letters in uppercase and a number 4 AB & 0 AB0 Fail in range (boundary test) Enter two letters in uppercase and a number 5 AB & 9 AB9 Fail in range (boundary test) Enter two letters in Output uppercase and a number “Incorrect 6 AB &10 Pass out of range number (boundary test) choice” Enter two letters in Output uppercase and a string as “Incorrect 7 AB & “One” Fail the number number (erroneous test) choice” Task 50

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 113 Task 51 Language Advantages Disadvantages • Fast to run • Machine dependent so • Provides direct manipulation cannot be used on another of computer registers and machine storage and can manage • It is difficult to develop, debug memory more efficiently and maintain programs Low-level • Allows for direct written in machine code or communication with assembly language hardware devices • As it is harder to program in, which usually results in poor programming • Programmer-friendly so are • Slower than low level easy to write programs as needs to be • It is not dependent on one translated into machine code High-level single make or model of • Less memory efficient processor to work • Cannot communicate directly • Less error prone and easier to with the hardware find and debug errors Task 52 Translated one line at a Translates the whole Translated assembly time into machine code program into machine language into machine and runs them straight code before it runs any of code away it Assembler Interpreter Compiler

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 114 Task 53 Question Your Answer 1. What is machine code? Instructions executed by the processor and it is written in binary 2. What is assembly A direct translation of machine code using words for the language? instructions to make it a little easier for the programmers. It still needs to be translated into machine code 3. Give an example of a Python, C++, Java, Pascal, COBOL, BASIC (there are many high-level language. of them) 4. What is the difference Most computers are written in a high-level language as between a low-level it is much easier and one line of high-level code can take language and a high- the place of many lines of machine code (a low-level level language? language). The processor can only understand machine code so any program created by assembly code or a high-level language still needs to be translated before it can be run. 5. Why would somebody It communicates directly with the hardware and program using a low- memory in embedded systems so is faster to be level language? translated and it can also be used for forensics and cyber-attacks 6. Why would somebody It is much easier to create and debug programs in high- program in a high-level level languages. It is also not dependent on that one language? processor so can be used on other computers 7. What does a translator Translates the code into machine code do? 8. What is the difference An interpreter translates one line at a time before it is between an interpreter run but a compiler translates the whole program before and a compiler? it can be run

Teach yourself programming with pseudocode and Python for AQA GCSE Computer Science by Nichola Lacey Page 115