80
better future – brighter hope PiXL ICT to Computer Science Handbook 2017

PiXL ICT to Computer Science Handbook 2017

  • Upload
    others

  • View
    13

  • Download
    0

Embed Size (px)

Citation preview

Page 1: PiXL ICT to Computer Science Handbook 2017

b e t t e r f u t u r e – b r i g h t e r h o p e

PiXL ICT to Computer Science

Handbook 2017

Page 2: PiXL ICT to Computer Science Handbook 2017

b e t t e r f u t u r e – b r i g h t e r h o p e2

Contents Chapter Workbookintroduction

IntroductingPython

1. Input and Outputs

2. Variables

3. StringHandling

4. Casting

5. Selection

6. Iteration:While/ConditionalLoops

7. Iteration:ForLoops/Definiteloops

8. Subroutines:ProceduresandFunctions

9. Arrays/Lists

10. Dictionaries

11. FileHandling

12. Random Number Generator

13. 2DArrays

Appendix:

• String handling

• Loops

• Python does sums

• Evil Dictator

• Simple Calculator

• Number Guessing

• FileHandling–extensionactivities

• ListHandlingFunctions–everythingyouneedtoknow

• Python Cheat Sheet

Page 3: PiXL ICT to Computer Science Handbook 2017

b e t t e r f u t u r e – b r i g h t e r h o p e 3

WelcomeWelcome to the PiXL Computer Science “conversion course”.

Under the reformed GCSE specification the Non-Exam Assessment (NEA) is worth 20% of the overall qualification, much less than the 60% weighting the controlled assessment enjoys in the legacy specification.

However all reformed exams require pupils to undergo a programming tech-niques exam paper (under various names) that broadly asks pupils to demon-strate the concepts and logical thinking that the course will be teaching you today. To access the exam paper students will have to show an understand-ing of pseudocode: a written English version of programmable code.

Consequently this course and workbook will aim to:

◦ Improve ability to program to at least GCSE standard

◦ Improve ability to read, write and interpret algorithms (pseudocode) to at least GCSE standard.

In doing this you will therefore be better placed to prepare and assess your pupils in their forthcoming NEA and exams.

Our hope is that this workbook will also be a valuable resource to support your teaching. The workbook and the course have both been designed so that it mimics the style, manner and approach that you may want to take when delivering some of this content to your students.

Page 4: PiXL ICT to Computer Science Handbook 2017

Before we start programming.... There are some recurring aspects of programming that are helpful to understand before you begin.

Algorithms

“Algorithm” is a word you will hear a lot as a computer science teacher. Creating an algorithm means creating a set of steps for someone to follow that, if followed correctly, will always yield the same result.

Therefore you could consider a recipe book as a big book of algorithms. Y our sat-nav system gave each bit of an algorithm to maybe get you here today.

Algorithms are used to help design computer programs. A computer program is essentially an algorithm that has been brought to life. When a programmer is given a problem to solve they will create an algorithm to help understand the problem. Creating the algorithm requires them to follow a number of steps.

1. Abstraction: This is the process of removing any detail that isn’t necessary when solving the problem

2. Decomposition: This is where the problem to be solved is broken down into sub problems. Each sub problem is easier to tackle on its own rather than trying to create the whole algorithm in one go

3. Algorithmic Thinking: Thinking about and creating the algorithm to solve the given problem

This is, in part, the process that you and your students will have to follow in order to complete the NEA. In practical terms an algorithm for a computer program will be either a flowchart or pseudocode. All papers from the previous syllabus contained at least one high value (10% of paper) question on algorithmic thinking. It is good practice to create an algorithm for any solution that is being coded. This workbook will aim to emphasise the above process and it is advisable to do the same with your students.

There is a pseudocode glossary at the end of the handbook. However each exam board follows slightly different guidelines for using pseudocode. Please make yourself aware of your own exam board’s guidelines.

Relational Operators

Computer programs often require relational operations to take place and it is almost inevitable that any NEA from any exam board will need an understanding of these operators. Relational operators, sometimes known as comparison operators, test the relationship between two numbers. This can include whether they are equal to each other, whether one number is greater or to control how many times an action is carried out.

b e t t e r f u t u r e – b r i g h t e r h o p e4

Page 5: PiXL ICT to Computer Science Handbook 2017

The operators can vary slightly between programming languages. This course will be based on Python. The operators used by this language are:

Operator Meaning Example Evaluates to

== equal to 7==7 True

!= not equal to 6!=7 True

> Greater than 7>6 True

< Less than 5<8 True

>= Greater than or equal to 6>=8 False

<= Less than or equal to 7<=7 True

Data Types

Data is a single “thing”; quantity, unit, piece of text, etc. that could be stored and used by the computer program. Data is usually stored in something called a variable or a list (more on these later). In many programming languages you will need to tell the computer program what data type will be stored in that variable when you create it.

You don’t always have to tell Python what the data type is. Python is very understanding and initially assigns every data item to be of data type string by default. Unless, told otherwise. When you do it is called “casting”. (More on this later too!)

There are different types of data that a computer program will use:

Data Type Description Example In Python Written As

Integer A whole number (no decimal places

7 int

Float (sometimes called Real or Double)

A number that allows for decimal places

7.45 float

String A string of text stored together Hello str

Char A single text based character M chr

Boolean One of 2 values where only 2 values would be expected E.g. Yes/No; True/False; On/Off

True

b e t t e r f u t u r e – b r i g h t e r h o p e 5

Page 6: PiXL ICT to Computer Science Handbook 2017

Errors

A benefit of designing an algorithm before you create your codes is that it reduces the chance of making mistakes. However, as any programmer will tell you, they still happen! As programming is a logical procedure most errors can be fixed by understanding where the logic has “gone wrong”.

There are 2 main types of errors that can occur when writing code:

• Syntax Error • Logical Error

Syntax Error

Syntax error is an error in the rules or grammar of the programming language e.g. no colon at the end of an If statement. Another example could be where you have misspelled one of the key words that the program needs to understand in order to operate. In the next chapter you will learn that the command “print” is used to output a message. If the word is misspelled e.g “pirnt” then the program will not be able to run.

Python uses something called “white space” to understand when some commands start and stop. This means that some commands need to be indented to be understood properly. These will be referenced in the handbook where appropriate.

Logical Error

This is an error in the actual design of the program and may also be known as a run time error. A program could still function with a logical error but may not produce the expected results. A logical error could also cause the program to crash e.g. a division by zero.

For example you may be creating a program that converts £ to $. Instead of multiplying the amount of £ by the conversion rate you instead, by accident, programmed it to divide. This wouldn’t stop the program from working but would produce the wrong result.

b e t t e r f u t u r e – b r i g h t e r h o p e6

Page 7: PiXL ICT to Computer Science Handbook 2017

Introducing Python

Python Basics

Using the Shell The ‘Python Shell’ works like a calculator: type an expression at the prompt >>> You Get the answer as soon as you hit return. It is enough to type an expression; the value is echoed. The Shell is good for trying out small bits of program.

Writing Scripts A program or script is a document. The text of the program is in a file, with a name. To see what the program does, you must tell IDLE to ‘run’ the program. A program must have a ‘print’ In it; otherwise nothing happens. Large programs are always written in files.

b e t t e r f u t u r e – b r i g h t e r h o p e 7

Page 8: PiXL ICT to Computer Science Handbook 2017

Script colours:

Functions Keywords Strings Comments – must be preceded with a # and do not affect the running of your program and are either written above the code they are referring to or to the right of the code. Never preceding the code itself.

Everything else is in black!

b e t t e r f u t u r e – b r i g h t e r h o p e8

Page 9: PiXL ICT to Computer Science Handbook 2017

Saving Python Programs A program is a document that is held in a file (just like a word processor or spread heet file). We will assume that a Python program is a single file, with extension ‘.py’.

As you complete each exercise, create a new file for each stage. That way you can look back at the programs you have written. You can create a new program as follows:

1. Menu: File/New window 2. Edit text in the new window 3. Menu: Run/Run Module or Run/Check module. You will be prompted to save the file.

Give it extension .py

It is important to ensure that you click “libraries”, followed by “documents” before saving – otherwise Python saves the program locally to the C drive which can cause problems on networked machines. It is also advisable to create a Python folder in your user area to store your programs.

b e t t e r f u t u r e – b r i g h t e r h o p e 9

Page 10: PiXL ICT to Computer Science Handbook 2017

The rest of this work book is a series of explanations and challenges designed to teach you the basic programming techniques that you and your students will be required to know.

Each section begins with a definition and explanation. This is followed by a simple snippet of code that demonstrates the skill being implemented. This snippet of code is complemented by its pseudocode equivalent.

There is one immediate pseudocode challenge followed by a series of coding challenges to help embed the skill.

As the chapters get more advanced you will need to increasingly refer back to the pervious skills that you have learnt. Feel free to ask for help with how to implement previous skills as this is often the hardest part of learning to program.

Good Luck!

b e t t e r f u t u r e – b r i g h t e r h o p e1 0

Page 11: PiXL ICT to Computer Science Handbook 2017

1. Input and Output Definition: Input is when the user inputs some data into the program; for example types their name. Output is where the program gives data to the user.

When would you use Input and Output?

This is fairly self-explanatory. Whenever the user is required to engage and give data to a program an input will be required. For example name or age. If a program needs to make a decision there is often an input so that the user can influence what decision is made. You would use an output when you want to inform the user of what the program is doing. Any commands, questions, menus would all need to be presented to the user so they understand how they have to interact with the program. These, therefore are outputs.

Algorithm and sample code:

Pseudocode PRINT “Hello User, how are you?” USER INPUT

Python

Or

Algorithm Challenge Write an algorithm that outputs the message “Hello World” and allows the user to respond.

NOW CODE IT!

b e t t e r f u t u r e – b r i g h t e r h o p e 1 1

Page 12: PiXL ICT to Computer Science Handbook 2017

Challenges: 1. Think of 5 questions you’d like the program to ask the user. Can you make it ask each

question and allow the user to answer after each one?

b e t t e r f u t u r e – b r i g h t e r h o p e1 2

Page 13: PiXL ICT to Computer Science Handbook 2017

2. Variables Definition: A variable is a method of storing data in memory that can change while the programme is running.

When would you use a variable?

You would use a variable whenever you needed to store and reuse data in your program.

Imagine a computer game that required you to enter your name at the start of it. When you input your name the program would store it inside a variable. Each time the game needed to reuse your name the program would reuse the variable with the name in it. When the programmer creates a variable they decide on the name to give it. It is good practice to give the variable a meaningful name that refers to what is stored in it and is easy to understand. A popular analogy is to think of a variable as a box with a label on it (the name of the variable). The label should describe what is placed in the box. In Python there are rules: Variables cannot start with a number e.g. either 5mike or have spaces mike 5. They cannot be called after reserved words e.g. ‘print’

Algorithm and sample code:

Pseudocode PRINT(“What is your name?”) firstname=USERINPUT PRINT “hello” + firstname

Python

b e t t e r f u t u r e – b r i g h t e r h o p e 1 3

Page 14: PiXL ICT to Computer Science Handbook 2017

Algorithm Challenge Write an algorithm that asks a user to enter their name and age and stores them both in their own variable. The algorithm will then output a message saying “hello” followed by the name and “your age is...” followed by their age. Note that in Python the rule is the message in brackets are joined to the variable by the use of a comma.

NOW CODE IT!

b e t t e r f u t u r e – b r i g h t e r h o p e1 4

Page 15: PiXL ICT to Computer Science Handbook 2017

Challenges: 1. Create a variable called age and ask the user to store their answer in it. Print out

their age. 2. Create a variable called favFood and ask the user to input what their favourite

food is. Print out the answer. 3. Ask the user to enter their top 5 favourite bands and store each answer in a separate

variable. Print out the answers. 4. Input first name and surname as separate variables. Output “Hello “, firstname,

surname a. Create a new variable called fullName by joining together firstname

and surname variables b. Output “hello”, firstname, “nice to meet you” c. The code print(firstname[0]) will print out the first letter of the text

stored in the variable firstname. Use this to output “your first initial is.” Followed by the users’ initials

d. Add to your code so that it prints the message “your initials are” followed by the user’s initials.

b e t t e r f u t u r e – b r i g h t e r h o p e 1 5

Page 16: PiXL ICT to Computer Science Handbook 2017

3. String handling Definition: The ability to manipulate strings (letters, numbers, and symbols)

When would you use String handling? String handling is an essential tool required to solve many coding problems. Whenever you need to do something with a variable that contains text, you will need to use a string handling function.

Algorithm and sample code that inputs text to a variable and prints it in upper case:

Pseudocode name = USERINPUT PRINT name.upper

Python

b e t t e r f u t u r e – b r i g h t e r h o p e1 6

Page 17: PiXL ICT to Computer Science Handbook 2017

Algorithm Challenge Write an algorithm that will ask the user to enter the name of their pet, and will print it out in upper case

NOW CODE IT!

For many of the string handling operations, you can instruct Python to carry out a function by writing the variable name followed by .function() For example fullName.upper()will convert the string in the variable fullName to uppercase. Sometimes extra detail will be required, this should be placed in the brackets. This detail is technically referred to as parameters or parameter values

b e t t e r f u t u r e – b r i g h t e r h o p e 1 7

Page 18: PiXL ICT to Computer Science Handbook 2017

Challenges: 1. Assuming you have a variable called Courier New, type and run the following code:

print(fullName.upper()). What does it do? a. Below this type print(fullName). Is it still in uppercase? It shouldn’t be.

Why is this? b. To store the string as uppercase it needs to be stored in a variable. Can you

amend the code so that the uppercase version is stored in a new variable? c. The code print(firstname[0]) will print out the first letter of the text

stored in the variable firstname. Use this to output “your initials are.” Followed by the user’s initials

d. How would you print out the second letter in the variable firstname? e. What do you notice about the numbers you use to identify the position of a

character? f. What does the following code produce print(surname[0:3])? g. This is called a substring. Output a substring that contains the 2nd to 4thletters

of the full name.

2. Create a variable called town that a user can input their town’s name into.

a. The code len(town) would return the number of letters in the variable called town (if that’s what you called it). Write some code that would tell the user how many letters were in their town.

3. Write some code that would create a new variable to hold a username for a login system. The username must be created from the first three letters of the user’s surname, followed by their first initial, followed by the length of their surname. E.g. Jack Smith would have the username smij5. Hint: Use str(len(surname)) for this exercise.

4. Create a variable called river that allows a user to enter the text into.

a. The function river.count(“s”) will count the amount of times the letter s occurs in that string. Can you output the amount of times the letter “s” occurs in the user’s answer?

There are more string handling activities in the appendix

b e t t e r f u t u r e – b r i g h t e r h o p e1 8

Page 19: PiXL ICT to Computer Science Handbook 2017

4. Casting Definition: When you convert a variable’s default datatype (e.g. string) to a different datatype (e.g. integer)

When would you use casting? Casting would be used when the data type of the variable is no longer appropriate for the task it is completing. Python’s default data type that inputs into a variable is string (e.g. letters, numbers and symbols). So far you have only used the string datatype. If you wanted to use a variable as a number the datatype would need to be changed to integer (whole numbers) or float (numbers that allow decimal places). The following python code will demonstrate the problem with not using the appropriate data type: hour_night = input(“how many hours a night do you sleep?”) hour_week = hour_night*7 print(“You sleep”,hour_week,”hours per week”) This program generates a logical error. The program works but not as we expect it to. Can you see why without running the code? In pseudocode you will not need to declare the different datatypes that each variable may contain. It is up to the person programming the algorithm to recognise when each datatype is necessary based on the design of the pseudocode.

Algorithm and sample code:

Pseudocode PRINT “How many hours a night do you sleep?” hour_night = USER INPUT hour_week = hour_night * 7 PRINT “You sleep “ + hour_week + “per week”

Python

b e t t e r f u t u r e – b r i g h t e r h o p e 1 9

Page 20: PiXL ICT to Computer Science Handbook 2017

Algorithm Challenge Write an algorithm that extends this code so that it finds the total amount of hours spent sleeping in a month. Assume that there are 4 weeks per month.

NOW CODE IT!

b e t t e r f u t u r e – b r i g h t e r h o p e2 0

Page 21: PiXL ICT to Computer Science Handbook 2017

Challenges: 1. Amend the program so that the program assumes there are 4.35 weeks per month. You will

need to change the data type so that it will allow decimal places (integer only allows whole numbers). The datatype you need is called float.

o Extend the program so that it will find how many days the user sleeps for each month.

2. In a new program called “Fun Calculator” ask the user to enter two numbers (stored in separate variables). The program should then output 4 answers:

o number1 + number2 o number1 - number2 o number1 * number2 o number1 / number2

Next, update the program so that it will allow the user to take the average of 5 numbers that are entered by the user. Think about what datatype this will need!

When developing a solution it is easy to get so “lost” in the logical problem you are trying to overcome that you forget the importance of getting data types correct. It’s best to test your code as often as you can to make sure that these problems are spotted as early as possible. This, in fact, is considered to be good practice and when completing the NEA would expected to be evidenced in a test plan. (At last, some ICT!)

b e t t e r f u t u r e – b r i g h t e r h o p e 2 1

Page 22: PiXL ICT to Computer Science Handbook 2017

5. Selection Definition: When a particular section of code is executed only if a condition is met. The most well-known method of selection is known as an If Statement.

When would you use selection? When a decision needs to be made in your program the concept of selection is often employed. The decision is based on a condition. As human beings we use this aspect of computational thinking all the time. IF it is cold, I will wear a coat to work. The condition here is the temperature, the selection is whether to wear a coat or not. If you were very particular about your clothing you could say:

• If the temperature is below 15 degrees I will wear a coat and gloves • If the temperature is below 20 degrees I will wear a coat • Otherwise (or in programming terms, “ELSE”) I won’t wear a coat or gloves.

This is the same logic you and your students will learn to apply when programming.

Algorithm and sample code:

Pseudocode USER INPUT num1, num2 IF num1 > num 2 THEN

PRINT num1 “ is larger” ELSE IF num2>num1 THEN

PRINT num2 “is larger” ELSE

PRINT “Numbers are equal”

ENDIF

Python

b e t t e r f u t u r e – b r i g h t e r h o p e2 2

Page 23: PiXL ICT to Computer Science Handbook 2017

Algorithm Challenge Write an algorithm that asks the user what sort of calculation they would like to do (+, -, *, /) then asks for the two numbers they would like to use in the calculation. The program will perform and output the result depending on what the user chooses.

NOW CODE IT!

b e t t e r f u t u r e – b r i g h t e r h o p e 2 3

Page 24: PiXL ICT to Computer Science Handbook 2017

Challenges: 1. Ask the user the question “what is the capital of France?” If the user gives the correct

answer the program will output “correct, well done!” else it will output “incorrect” 2. Ask the user to enter their age. Based on their input have the program output whether they

have: a. left education (equal to or older than 19), b. are at college (equal to or older than 16), c. are in secondary school (equal to or older than 11), d. are in primary school (equal to or older than 4) e. else they aren’t at school yet. f. If you tried to complete the above task in any other order than the one above it may

not have worked. Can you see why?

3. Ask the user to enter a word in either lowercase or uppercase. If the word is in uppercase ( code needed: variable == variable.upper(): ) it will output “that was uppercase, otherwise it will output “that was lowercase”.

4. Ask the user to enter a number, perform a modulus (MOD) calculation on it to see if there is a remainder when it is divided by 2. If there is no remainder output “This number is even” otherwise output “this number is odd”.

Mod divides one number by another and shows you the remainder

Mod uses the ‘%’ sign in Python. Eg 4%2

This example divides 2 by 4 and delivers a remainder of 0

The following code – print(4%2) would print the number 0

This is a great way to allow a program to determine if a number is odd or even

as dividing an even number by 2 will always produce a remainder of 0

You can of course use variables to interact with the Mod operation

5. Create a temperature convertor. Ask the user if they would like to convert Celsius to Fahrenheit. The conversion for each is:

a. F = C * 1.8 +32 b. C = (F-32)/1.8

6. You can have more than one condition in a single statement. For example: If it is cold and raining I will wear a waterproof coat. Ask the user to enter 2 names into separate variables. If name 1 = “dave” AND name 2 = “ben” then output “hello Dave and Ben!”

b e t t e r f u t u r e – b r i g h t e r h o p e2 4

Page 25: PiXL ICT to Computer Science Handbook 2017

7. This is an excellent way to validate a user’s input to a program. Create another If statement that says “hello Dave” if the user enters “Dave” OR “dave”

OR Syntax: if variable1 == x or variable2 == y:

Have you noticed how each statement and condition ends with a colon? There’s a high chance you’ve missed one out by accident and have received a message saying “invalid syntax”. The colon has two purposes:

1. Used by Python to identify that the condition for the IF statement is complete

2. Anything that is indented after the colon will operate as part of the IF statement. Python is very block orientated. Indentation is crucial.

This is the first example of Python using white space to help it run.

b e t t e r f u t u r e – b r i g h t e r h o p e 2 5

Page 26: PiXL ICT to Computer Science Handbook 2017

6. Iteration: While/Conditional Loops Definition: A section of code that will repeat itself until a condition is met.

When would you use While Loops? You would use a while loop if you need a section of code to repeat itself but are uncertain how many times this will be. For example guessing games that keep repeating until someone gets the correct answer. You don’t know at the start of the game how many guesses there will be. This would therefore need a while loop. It is vital to give a method of exiting the loop otherwise you will create an infinite loop that the program can’t escape. Some user input will be required inside the loop in order to change the condition that the loop is checking. This will create a method of escape. In Python you may need to initialise the variable before it is used in the while loop. If the variable hasn’t been created before the while loop, the while loop won’t be able to use it. You can do this by simply writing: variable = “” Or variable = 0 Although you don’t always have to show this in your pseudocode you will need to remember this for writing many of the programs below! If you do want to show this in your pseudocode use the code: INITIALISE variable

Algorithm and sample code:

Pseudocode INITIALISE num WHILE guess != num

PRINT “Guess Again” num = USER INPUT

ENDWHILE

Python

Mini challenge! Can you work out why the input on line 2 had to be cast as an integer?

b e t t e r f u t u r e – b r i g h t e r h o p e2 6

Page 27: PiXL ICT to Computer Science Handbook 2017

Algorithm Challenge Write an algorithm that sets a variable name to the value “Hal” (but don’t use a user input to do this). Ask the user to guess the name correctly. While the user gets the answer wrong the question should keep repeating itself. When the user gets the answer correct it says “correct answer, well done!”

NOW CODE IT!

b e t t e r f u t u r e – b r i g h t e r h o p e 2 7

Page 28: PiXL ICT to Computer Science Handbook 2017

Challenges: 1. Create a program that checks a pre-set password entered by the user. (This is very similar to

the algorithm/code challenge above). 2. Ask the user to tell the program facts about themselves (don’t need to store these) until the

user enters the word exit. a. Can you convert the user’s input and while loop condition so that it doesn’t matter

what version of the word exit is used (exit, EXIT, Exit) b. Amend the loop so that it will end if the user enters “Exit” or “End”

3. Repeatedly ask the user to enter a number between 1 and 10. While the user doesn’t enter a number between these parameters the code will repeat. Like the IF statement you will need to use the OR condition in your syntax.

4. You can use variables to keep count of things during your program. For example, x = x + 1 repeated 10 times would increase the value of x by 10. This is a very handy trick to master! See what the following sets of code produces: x = 0 while x <= 5: print(“Hello”) x = x + 1 counter = 5 while counter > 0:

print(“12345”) counter = counter -1

5. Using this method, create a program that asks a user to enter a number. The program will then output the squares of that number that are below 200:

a. Make sure you get your data type correct! b. You actually need two variables for this. Can you spot why? Getting it wrong is often

the easiest way to finding the answer!

b e t t e r f u t u r e – b r i g h t e r h o p e2 8

Page 29: PiXL ICT to Computer Science Handbook 2017

7. Iteration: For Loops/Definite loops Definition: A for loop is a loop of code that will iterate for a predefined number of cycles.

When would you use For Loops? When the program you are writing requires some code to be repeated an exact amount of times which is known when the program is being designed. For example if you wanted a program to print our 6 random lottery numbers you could run the same code 6 times instead of writing it out 6 times. It is important to understand the structure of the for loop as this will help you understand how other programming techniques such as arrays (referred to as lists in Python) can work in conjunction with a for loop. Regardless of which language is being used, it is common to see the following expression at the start of a for loop: “FOR counter =” This is creating a variable which in this instance is called “counter”. It could be called anything the programmer wants but the word “counter” as it literally keeps count The variable “counter" effectively keeps count of how many times the for loop has been repeated. In the example below when counter = 10, the for loop has met the condition it needs in order to stop and move on to the next line of code. This is useful because while the for loop is being executed you can use the contents of the variable “counter" in the same way you would any other variable. As you progress through this pack you will also see other methods of constructing a for loop, but we’ll stick with the “for counter =” for the moment.

Algorithm and sample code:

Pseudocode FOR counter = 1 to 10

PRINT “Hello”

NEXT i

Python

As you can see, the python code differs from the pseudocode. In Python the “range(10)” is the same as saying “1 to 10”. No “NEXT” is required as the correct use of indentation is what Python needs to understand when to repeat/break the loop.

b e t t e r f u t u r e – b r i g h t e r h o p e 2 9

Page 30: PiXL ICT to Computer Science Handbook 2017

Algorithm Challenge Write an algorithm that asks the user to input a number. A for loop should then display that number 7 times.

NOW CODE IT!

b e t t e r f u t u r e – b r i g h t e r h o p e3 0

Page 31: PiXL ICT to Computer Science Handbook 2017

Challenges: 1. Write a program that uses a for loop to output all of the even numbers from 0 to 100 (you

could use the Mod operation here). 2. Write a program that uses a for loop to output all of the odd numbers from 0 to 100 (you

could use the Mod operation here). 3. Write a program that will print the 5 times table.

I bet you got caught out by the old index starting from zero trick! If so, update your code with this

• for counter in range(1,13) • This will tell the loop where to start from and where to stop.

a. Amend the above program so that the user can decide on which times table is

printed out. 4. Create a program that will allow the user to enter a monthly payment amount. The program

will then show the accumulative payment for a year. 5. Create a program that will loop 10 times and output the contents of “counter” during each

loop.

6. Copy the following program outline, then check that it runs without errors: pocketMoney = 0.01

for week in range(10):

print("\nIt is week ",week)

print("You will get £ ",pocketMoney)

input("\nPress ENTER to exit program")

The code /n is new to us.

Can you see what it does?

7. Change the for() loop so that it counts the weeks from 1 to 26. Check that it works as expected.

8. Add one line of code inside the loop to double the amount of pocket money. Hint: pocketMoney = ……. Check that it works as expected.

9. Finally, add a line of code at the start to create a variable called totalMoney. totalMoney = 0 Inside the loop, keep a running total of the total pocket money you will have collected so far. Only print this value at the END of the program (after exiting the loop).

b e t t e r f u t u r e – b r i g h t e r h o p e 3 1

Page 32: PiXL ICT to Computer Science Handbook 2017

8. Subroutines: Procedures and Functions Definition: A subroutine is a section/block of code that is separate to your main code and completes a specific task. It can be called from the main code when it is required.

When would you use a subroutine? There are two types of subroutines the exam and NEA will require your students to know: procedures and functions. A procedure is a self-contained block of code that performs a task. For example you could use a procedure to print out a menu that the user needs to make a selection from. A function is also a self-contained block of code that performs a task but it also returns at least value back to the main code. Here some data will be passed from the function back into the main code. That data can then be used in the main code. Think of a function or a procedure as a program in itself (sometimes called a subprogram). This aids testing and debugging. The sooner your students can work with these programming structures the better. Your pupils will be expected to use these successfully in their NEA programming solution. You call the subroutine by using its name in your main block of code. For example if there was a subroutine called exit you would use the code: exit() Example function structure with output screen If you need a variable from your main code to be used in the subroutine you can pass this data into it using the parameters at the end of the subroutine name. For example Age = 10 exit(Age)

b e t t e r f u t u r e – b r i g h t e r h o p e3 2

Page 33: PiXL ICT to Computer Science Handbook 2017

Each piece of data in the parameters is called an argument. You can pass more than one argument into another block of code.

Algorithm and sample code for calling and a executing a procedure

Pseudocode //procedure being executed PROCEDURE greeting(name)

PRINT(“Hello “+ name) END PROCEDURE //setting name variable name = USER INPUT //calling the procedure greeting(name)

Python

b e t t e r f u t u r e – b r i g h t e r h o p e 3 3

Page 34: PiXL ICT to Computer Science Handbook 2017

Algorithm and sample code for calling an executing a function and returning a value from it to the main code

Pseudocode //executing the function FUNCTION triple_age(age) old_age = age * 3 RETURN old_age END FUNCTION //setting age variable age = USER INPUT //calling the function and printing the results PRINT = triple_age(age)

Python

Note the code “return old_age”. This passes back the multiplication of the variable age to the main routine.

b e t t e r f u t u r e – b r i g h t e r h o p e3 4

Page 35: PiXL ICT to Computer Science Handbook 2017

Algorithm Challenge Write an algorithm that asks the user to enter two numbers. They should then be asked to choose what sort of calculation they would like to make on those two numbers (+,-,*, /). Each calculation will take place in its own function. Remember each function should return its resulting value back to the main routine.

Please note that while the examples we’ve used so far demonstrate how to apply the techniques of functions and procedures the same results could easily have been achieved without using them. The aim here is to embed the syntax in a simple manner so that it can be applied to the more complex scenarios below.

NOW CODE IT!

b e t t e r f u t u r e – b r i g h t e r h o p e 3 5

Page 36: PiXL ICT to Computer Science Handbook 2017

Challenges: 1. Ask the user to enter an age they want to convert. Next give them 3 options: convert

the age to dog years (7 * human years), cat years (10* human years) or horse years (6* human years). Each calculation should take place in its own procedure.

2. Create a function that will return the perimeter of a rectangle. The two side lengths should be passed into the function.

3. Create a function that will return three values: the area of the circle, the diameter of the circle and the circumference of the circle. This calculation should be based on the user input of the radius in the main code.

a. Diameter = r*2 b. Area = Pi*r2 c. Circumference = 2*Pi*r

4. Write a function to greet a user, development could be to greet user with their name.

5. Write a function for times tables. When calling the function the number and how many you would like to display e.g. 5 times tables up to 12

6. Write a function for favourite book that accepts one parameter, title. The function should print a message including the title, such as, “My favourite book is Alice in Wonderland”. When calling the function, include a book title as an argument in the function call

7. Write a function called pets() which outputs information about a pet this should include parameters pet_name and pet_type. Call this function three times with the details of different pets.

8. Write a function called describe_city() that accepts the name of a city and its country. The function should print a simple sentence, such as Reykjavik is in Iceland. Give the parameter for the country a default value. Call this function for three different cities, at least one of which is not in the default country.

b e t t e r f u t u r e – b r i g h t e r h o p e3 6

Page 37: PiXL ICT to Computer Science Handbook 2017

9. Arrays/Lists: Definition: An Array (known as a list in Python) is a data structure that (unlike a variable) will contain more than one piece of data, e.g. a list of data. In Python the list can contain items of different data types.

When would you use an Array? You would use an array when storing data that is linked. For example if you were storing a shopping list or a list of names it would be better to store this in one array instead of multiple variables. Each piece of data in an array has a position in the array. This is called the index. Confusingly the index begins at 0 (not 1). This is because in computer science we start counting from zero and not one. So the first item in the list will be in position/index 0, the second piece of data will be in position/index 1 and so on. An illustration of an array that has 5 positions would be:

Index 0 Index 1 Index 2 Index 3 Index 4 Stored data Stored data Stored data Stored data Stored data

Algorithm and sample code:

Pseudocode //Initialising an array with data names[] = “David”,”Emma”, “Mark” //using a for loop to output data in an array FOR EACH name IN names[]

PRINT(name) NEXT

Python

b e t t e r f u t u r e – b r i g h t e r h o p e 3 7

Page 38: PiXL ICT to Computer Science Handbook 2017

Algorithm Challenge Write an algorithm that stores a shopping list of 10 items and prints out the contents of that list.

NOW CODE IT!

b e t t e r f u t u r e – b r i g h t e r h o p e3 8

Page 39: PiXL ICT to Computer Science Handbook 2017

Challenges: Much like string handling, there are different ways of interacting with arrays/lists. Working through the below challenges will show you many of the different ways in which lists can be

used in Python. There are two main challenges here in this section. Lists Part 1 Scenario

The Superhero Alliance has just been formed, and they need you to keep their computer files up to date.

1. Create a new list of superheroes

heroes = ["Batman","Wonder Woman","Superman","Spiderman"]

2. Whoever is the first in the list (heroes[0]) gets to fly the HeroJet. Print out the following message:

print("Current pilot: ",heroes[0])

3. The next person in the list is the co-pilot. Print out a similar message specifying who this will be.

4. Superman has had to take some time off (his Kryptonite allergy has flared up). Change heroes[2] to "Hit Girl".

5. The Alliance has found enough funding for two more superheroes. Luckily in Python you can extend the number of items in a list. This type of list is said to be dynamic as it can grow and shrink when required to. The function used to add an item to a list is the append() function.

Use the append() function to add two more superheroes of your choice. You will need to use the append() function twice, once to add each new member.

6. Print out the full list of superheroes currently in the Alliance.

7. Extension task:

After the full list of members has been printed:

• Ask the user which member they want to replace (a number from 0 to 5) • Ask the user for the name of the new superhero • Print out the updated list of superheroes

b e t t e r f u t u r e – b r i g h t e r h o p e 3 9

Page 40: PiXL ICT to Computer Science Handbook 2017

Lists Part 2 Scenario

The Evil League of Super Villains has recently formed to help fight back against the superhero Alliance. They’ve hired you to help them keep track of who is who within the League.

1. Create a list of Super villains:

villains = ["The Joker","Magneto","Red Mist","Doc Ock"]

2. Use the following code to step through each villain and print their name:

for badGuys in villains:

3. Create another list called wages, this time to show the wages (in millions of pounds) of each villain. The list needs to be just four numbers (in the right order). The Joker: 21 Magento: 17 Red Mist: 3 Doc Ock: 5

4. Create a loop that will print out the name AND wage for each villain. The code below might help you.

print(villains[counter],": £",wages[counter]," million") Extra challenge – can you use the len() function to control the loop?

5. Create a variable called totalWage and set it to 0. Use a for loop to step through the wages list and add each value to totalWage. At the end, print out the total wage bill for the League.

b e t t e r f u t u r e – b r i g h t e r h o p e4 0

Page 41: PiXL ICT to Computer Science Handbook 2017

Using lists Task 1

1. DO NOT RUN THIS PROGRAM YET! Predict the output you would see if you were to run this program.

friends = ["Gunther","Monica","Phoebe",”Joey",”Ross”,”Chandler”] print("One of my friends is called ",friends[1])

Prediction:

Now type up the program and test if you were correct.

2. Alter the program so that it will print out “Ross” instead. (Note: You must use the list to do this, don’t cheat and just write in “Ross”!)

3. The first name in the list is wrong. Add a new line to the program that will change the first name from “Gunther” to “Rachel”. Add this line to the very end of the program so that you can see if it has worked.

print(friends)

4. DO NOT RUN THIS PROGRAM YET! Predict the output you will see if you were to run this program.

takeThat = [“Gary”,“Mark”,“Howard”,“Jason”] takeThat[4] = “Robbie” print(takeThat)

Prediction:

Now type up the program and test if you were correct.

5. Alter the program so that it adds Robbie to the list correctly

b e t t e r f u t u r e – b r i g h t e r h o p e 4 1

Page 42: PiXL ICT to Computer Science Handbook 2017

6. The following code will create an empty list of 4 names, then ask the user for a name to place in the list. The last line is just there so we can see what the list looks like at the end.

friends = [None] * 4 name = input("Enter the name of a friend: ") friends[0] = name print(friends)

Add more code that will ask the user for more names to complete the list. The last line should still print out the completed list.

7. If you want to add an item to the end of a list and not specify where it goes, use the append() function: syntax ~ list.append(data)

Create a list of 4 items. Use the append() function to add two more items via user input in a loop. Print the final list

8. If you want to add an item to a list and specify where it goes, use the insert() function: syntax ~ list.insert(position,data)

Using your list from 7 above, apply the insert() function to add two more items at index points 2 and 4. Print the list.

9. If you want to remove an item from a list, use the pop() function: syntax ~ list.pop(position)

Using your list from 8 above, apply the pop() function to remove two items at different index point. Print the list.

There is a comprehensive list (by the standards of the NEA anyway) of other list functions in the appendix. If you don’t know how to handle a list to achieve a certain outcome, the answer may be there.

b e t t e r f u t u r e – b r i g h t e r h o p e4 2

Page 43: PiXL ICT to Computer Science Handbook 2017

Extension:

Write a program for cinema to keep a list of the latest films being screened. The program should start by presenting the user with a menu:

1. Reset list 2. View entire list 3. View one item 4. Edit list 5. Quit

Option 1 should create a blank list of 6 films.

Option 2 should print the entire list in one go.

Option 3 should ask which item the user wants to see (by number) and display that film.

Option 4 should ask the user which item the user wants to change and what film they want to replace it with. The program should then replace that item.

Option 5 should exit the program.

The program should repeat (using a WHILE loop) until the user chooses option 5.

It is worth noting that a menu system is a common feature that students are expected to successfully implement within the NEA. Therefore this is

definitely something worth practising with your classes.

b e t t e r f u t u r e – b r i g h t e r h o p e 4 3

Page 44: PiXL ICT to Computer Science Handbook 2017

10. Dictionaries Definition: Think of dictionaries as fancy lists. These allow a multi-dimensional approach to list creation and manipulation.

How to use Dictionaries:

The syntax of a dictionary is familiar ~ nameOfDictionary = {item, item, item}. We use braces { } rather than square brackets [ ]. A simple dictionary might be bands = {“Led Zepplin”, Nine Inch Nails”, “Slipknot”} This would be created and output as:

The output is messy. Try adding an asterisk ‘*’ immediately before ‘bands’ in the print statement. If this were all there were to dictionaries there would be no real reason to use them. The real benefit of dictionaries is the multi-dimensional aspect. Consider this code:

And the output

A dictionary has the structure of Key and Value. The left item is the key and the right item is the value.

b e t t e r f u t u r e – b r i g h t e r h o p e4 4

Page 45: PiXL ICT to Computer Science Handbook 2017

Challenges: 1. Create a dictionary with a key value pair (see bands example above for the syntax) 2. When working with data in dictionaries, Python has a range of functions that allows

the user to identify and manipulate:

.key()

.values()

.items()

Bring it all together, we can produce output with meaning (note the use of ‘{}’ to format the output):

b e t t e r f u t u r e – b r i g h t e r h o p e 4 5

Page 46: PiXL ICT to Computer Science Handbook 2017

3. Develop your dictionary from 1 above so that the user can input new items to the dictionary.

You may have noticed that things are starting to get reasonably complicated. As such please be aware that some of the concepts and skills

that have been explained in this section have been presented and explained in what is hopefully the most understandable way.

Consequently there are some aspects here that are technically incorrect (for example a dictionary is not a “fancy list”) but to fully explain these technicalities would just be too much! However, please feel free to ask

for the technical details if you’d like

b e t t e r f u t u r e – b r i g h t e r h o p e4 6

Page 47: PiXL ICT to Computer Science Handbook 2017

11. File Handling Definition: Using a programming language to work with (e.g. read, write and append to) an external file. For example a text file

When would you use file handling? While a programming language uses data structures like variables and arrays (known as lists in Python) to store data while the program is running, this data will often be lost when the program is exited. Therefore it is beneficial to be able to read from and write to an external file that can hold data regardless of whether the program is running. For example, if you were a new user of a program you may have to sign in the first time you use it. This would require you to maybe create a username and password. When the program is terminated so are the username and password you have created. However, if upon creation, they were saved in an external file, when you came to log in again your details could be checked. Thus allowing you to skip the “sign up” stage. The explanations given below work on the assumption that the text file is in the same folder as the Python program you are running. If it isn’t you would have to declare a path to where the text file is.

Algorithm and sample codes: Read from a file

Pseudocode

//to read text from a file and output it file = openRead(“samplefile.txt”) text = file.readLine() PRINT text //it is important to close the file to prevent it //from accidently being corrupted file.close

Python

Algorithm and sample codes: Write to a file

Pseudocode //to write user input text to a file

file = openWrite(“samplefile.txt”)

file.writelines(USER INPUT())

file.close

Python

b e t t e r f u t u r e – b r i g h t e r h o p e 4 7

Page 48: PiXL ICT to Computer Science Handbook 2017

Algorithm and sample codes: append to a file (write will always overwrite the contents of the file)

Pseudocode

//to append user input text to a file

file = openWrite(“samplefile.txt”)

file.writelines(USER INPUT())

file.close

Python

Note that writing to a file will OVERWRITE all data in it. If you want to add data to a file change the ‘w’ to ‘a’

b e t t e r f u t u r e – b r i g h t e r h o p e4 8

Page 49: PiXL ICT to Computer Science Handbook 2017

Algorithm Challenge Write an algorithm that allows someone to write their name in a text document called “sample.txt” before outputting the contents of the text document.

NOW CODE IT!

*You will need to create a sample.txt file and make sure it is saved in the same folder as the Python program.

b e t t e r f u t u r e – b r i g h t e r h o p e 4 9

Page 50: PiXL ICT to Computer Science Handbook 2017

Challenges: 1. Create a text file called “scores”. Using python, ask a user to enter the score they have

received in a test. Write their input to the text file “scores”. 2. Update the code so that the user is asked if they would like to update their most recent

score or read their most recent score. Use an IF statement and the file handling code we’ve learnt to allow the user to select an option.

a. The code you need to read the score is: file = open(filename, “r”) 3. So far we have been using the following code:

a. file = open(filename, "w") 4. This has resulted in all data in the text file being overwritten. However the file can be

accessed in a way that allows data to be appended to it rather than overwriting it. The code you will need is:

a. file = open(filename, "a") 5. Update your code so that you can now choose one of three options:

a. Read Scores: file = open(filename, “r”) b. Overwrite Scores with a new score c. Add a Score

Python can also handle other types of files including databases and csv files. There are details about these in the appendix for you to explore further.

b e t t e r f u t u r e – b r i g h t e r h o p e5 0

Page 51: PiXL ICT to Computer Science Handbook 2017

12. Random Number Generator Definition: A function in a programming language that simulates a random number that can be used in the program.

When would you use a Random Number Generator? When you need a random number... For example if you were looking to simulate the roll of a dice you could program the generator to randomly pick a number from 1-6. For many programming languages, including Python, this requires a line of code that “imports the module” to do with the random number generator. In simple terms this means python accesses a predefined set of code that is used to generate random numbers.

Algorithm and sample code

Pseudocode

//identifies the number range for the generator to use. //Note that no import is required r1 = getRandomInt(0,9) PRINT r1 r1 = getRandomInt(0,9) PRINT r1

Python

Mini challenge! How would you generate a random number in the range 1 to 10?

b e t t e r f u t u r e – b r i g h t e r h o p e 5 1

Page 52: PiXL ICT to Computer Science Handbook 2017

Algorithm Challenge Ask the user if they would like to roll the dice. If the answer is yes a random number between 1 and 6 will be generated. Else the program will say “thank you” and close

NOW CODE IT!

b e t t e r f u t u r e – b r i g h t e r h o p e5 2

Page 53: PiXL ICT to Computer Science Handbook 2017

Challenges: 1. Create a lottery number generator. It should create and output 6 different random

numbers. 2. Create a guessing game. The program generates a number between 1 and 100. The

user has to keep guessing the number until they get the correct number.

Extension:

• If they guess too high the program outputs “Too high, guess again” • If they guess too low the program outputs “Too low, guess again” • When the user gets the answer correct the program will also output the amount of

guesses it took 3. Create a list. The list should be 10 items long and each index should contain the

letter “O”. Use a RNG to randomly place the letter “X” in one of the positions in the list. The user should guess where the “X” is placed by entering a guess of 1-10. Note that the user should guess from 1 – 10, as this is more natural for the user. However, the list indexes will be different. You need to decide how to solve this problem!

Create a 4 digit number that is randomly generated. Do not allow a number to be repeated. For example:

4592 = acceptable

4431 = unacceptable.

b e t t e r f u t u r e – b r i g h t e r h o p e 5 3

Page 54: PiXL ICT to Computer Science Handbook 2017

13. 2D Arrays Definition: A Data Structure that allows linked data to be stored. Unlike the 1 dimensional array which stores data in a single list, the 2D array stores data in a matrix of rows and columns.

When would you use a 2 Dimensional Array? You would use a 2D array when you have linked data that needs to be stored and reused and that data exceeds just one list. Any scenario when data would be best represented by a table would most likely require a 2D array to store it. For example if you were storing a list of names and 5 test results for each name a 2D array would be suitable. If you imagine the 2D array as a table or grid, each cell will have a 2 digit reference number (that starts from 0.... obviously!) So the top left cell would always have a reference of (0, 0). You can populate and print the 2D array based on the cell reference. Confusingly, Python does not use 2 dimensional arrays in the sense that other programming languages do. Instead it allows the user to place a series of lists next to one another. Each new list effectively creates a new row. Sometimes referred to in Python as a list of lists This therefore creates the same outcome as a conventional 2D array providing that you are aware of how to handle the list to get the same outcome.

Algorithm and sample code:

Pseudocode

// creates an array that is 4 x 4 cells in size myArray[3,3] //stores data in cell 1,0 myArray[1,0] = “David”

Python

b e t t e r f u t u r e – b r i g h t e r h o p e5 4

Page 55: PiXL ICT to Computer Science Handbook 2017

Algorithm Challenge Create a 2D array that will have a list of 5 names and the age of each person next to the name. The data should be “hard coded”, i.e. there is no user input, the data is all in the coding itself.

NOW CODE IT!

b e t t e r f u t u r e – b r i g h t e r h o p e 5 5

Page 56: PiXL ICT to Computer Science Handbook 2017

Challenges: 1. Adapt your multi-dimensional lists so that data is added and removed using:

Append()

Insert()

Pop()

If you’re unsure of the syntax, refer back to the first Lists chapter for help or the appendix which has a more comprehensive account.

2. Create a 2D list that holds the name, mark, percentage and grade for a computer science exam (assume the maximum mark is 80)

a) Update the above code so that the data can be added using user input b) Update once more so that once the mark is input the percentage and grade are

automatically calculated. Assume 40 = 50% c) Edit your code so that the data is written to a file.

3) Initialise a 2D array called seven_times

a) Create a for loop that will populate the array with the seven times table and the power of each multiplication. Print the output.

Note: you can add a new list using the following syntax:

myArray = myArray + [[]]

If done correctly, the output for the 7 times table would look like this:

[[7, 49], [14, 196], [21, 441], [28, 784], [35, 1225], [42, 1764], [49, 2401], [56, 3136], [63, 3969], [70, 4900], [77, 5929], [84, 7056]]

b e t t e r f u t u r e – b r i g h t e r h o p e5 6

Page 57: PiXL ICT to Computer Science Handbook 2017

Appendix Congratulations! If you’re reading this you may well have made it through the entire workbook.

The following appendix includes further challenges, tasks and skills that you can use to further hone your understanding of Python.

The appendix includes challenges that will develop your skills with:

• String handling • Iteration/Loops • Casting • Selection • File Handling • List Functions

STRING HANDLING

Python has a range of string operations that students will benefit from working with.

Example 1 What is the value of the keystroke?

All keystrokes have an unique ASCII value associated with them e.g. print(ord(“R”)) will return the value 82.

Task, create a program that will take user input of one character and output its ASCII value.

Example 2 What is the keyboard equivalent of an integer?

Just as every letter has an ASCII value, you can find the alphanumeric value of a number through using the chr function: print(chr(65)) will output “’A’.

Task, edit your program form Task 1 to return the keyboard value of an input number. Why does the value 3 not produce anything?

Example 3 Hex value?

Within data representation the ASCII system also represents keyboard input as the hexadecimal value e.g. hex(ord(E)) will return 0x45. Why is 0x appended to the front of the output?

Task, create a short program that will convert a single keystroke into its hex value.

b e t t e r f u t u r e – b r i g h t e r h o p e 5 7

Page 58: PiXL ICT to Computer Science Handbook 2017

Example 4 Space used?

Calculation of the length of a sting, including spaces can be achieved using the len() function

e.g .print(len(This is Python)) will return the value 14.

Task, create a simple program that will accept user input and return the length of the input.

Example 5 Concatenate

Joining text can be relatively straightforward in Python. The example below shows the simplest form:

However, the text prints with no spaces making it unreadable for human eyes.

A more Pythonic/programmer approach is to use inbuilt formatting tools.

Example 6 Using braces

Try the code below. Extend this to work with user input over several input strings

Example 7 Using join

When working lists, it is often necessary to output the contents as a string.

Using the text from our examples above we use the join function in this way

The process is to convert/transfer the variables into a list (myText) and then use the join function. Be sure to leave a space between the quotation marks!

Task: create a list from 3 different user inputs, convert these into a list and output as a string.

b e t t e r f u t u r e – b r i g h t e r h o p e5 8

Page 59: PiXL ICT to Computer Science Handbook 2017

Loops Exercise Program What Is Printed? x = 0 whi l e x <= 5 :

pri nt(" Hel l o") x = x + 1

count er = 5 whi l e count er > 0 :

pri nt(" 12345") count er = count er - 1

count er = 1 whi l e 8 < count er :

pri nt(" Davi d") count er = count er + 1

Complete the following programs to give the pattern shown: Program Outline Output Expected cnt r = 0 whi l e ... :

pri nt(...) cnt r = cnt r + 1

Hel l o worl d! Hel l o worl d! Hel l o worl d! Hel l o worl d!

count er = 6 whi l e ... :

pri nt(...) count er = count er ...

Loops repeat Loops repeat Loops repeat Loops repeat Loops repeat

... whi l e ... :

...

... = ... + 1

On and on On and on On and on On and on On and on On and on On and on

b e t t e r f u t u r e – b r i g h t e r h o p e 5 9

Page 60: PiXL ICT to Computer Science Handbook 2017

Python Does Sums Knowledge required:

• Input and print • Conversion to integers

Write a program allowing the user to enter two numbers and output the product (one multiplied by the other). Here are two examples of the program running: ***** PYTHON CAN MULTI PLY ***** TEST ME !!! Ent er x? 193 Ent er y? 789 You asked me t o mul ti pl y 193 by 789 1 93 * 789 = 152277 ***** PYTHON CAN MULTI PLY ***** TEST ME !!! Ent er x? 77 Ent er y? 1293 You asked me t o mul ti pl y 77 by 1293 77 * 1293 = 99561

b e t t e r f u t u r e – b r i g h t e r h o p e6 0

Page 61: PiXL ICT to Computer Science Handbook 2017

Evil Dictator Knowledge required:

• Input and print • If statement • Loops can be used though there is a way to avoid them.

You are captured by an evil dictator who demands your name. Unknown to you, he cannot abide names containing an 'e' (or an 'E'). He has a program to check the names of his captives. Here is a transcript of his program running for you and your fellow captive Bill. The evi l di ct at or has capt ur ed you and de mands your na me. Obey at once! Ent er your na me, sl ave: Bi ll Wel co me Bi ll your na me i s accept abl e You can be my honour ed sl ave! The evi l di ct at or has capt ur ed you and de mands your na me. Obey at once! Ent er your na me, sl ave: Ben Oh no! A na me wi t h an ' e' Guar ds, send Ben t o t he dungeon To save yourself, offer to rewrite his program in Python, So far unknown in his evil kingdom.

b e t t e r f u t u r e – b r i g h t e r h o p e 6 1

Page 62: PiXL ICT to Computer Science Handbook 2017

Simple Calculator Knowledge required:

• Input and print • If statement • Loop

This program makes Python into a simple calculator, able to do ‘+’, ‘‐’, ‘*’ and ‘/’

Enter number> 9 Value= 9 Enter operator> + Value= 9 + ? Enter number> 11 Value= 20 Enter number> 17 Value= 17 Enter number> 23 Value= 23 Enter operator> * Value= 23 * ? Enter number> 17 Value= 391 Enter number> 35 Value= 35 Enter operator> / Value= 35 / ? Enter number> 8 Value= 4.375 Enter number>

Write out the code for this program

b e t t e r f u t u r e – b r i g h t e r h o p e6 2

Page 63: PiXL ICT to Computer Science Handbook 2017

Number Guessing Knowledge required:

• Input and print; • If statement • Loops • Function for random number.

In this game the computer chooses a secret number for the user to guess. Here is an example:

I have chosen a secr et nu mber of 3 di gi t s f or you t o guess Wh at ' s your guess>500 Too hi gh. Tr y l ower. Wh at ' s your guess>250 Too l ow. Tr y hi gher. Wh at ' s your guess>375 Too l ow. Tr y hi gher. Wh at ' s your guess>427 Too l ow. Tr y hi gher. Wh at ' s your guess>463 Too l ow. Tr y hi gher. Wh at ' s your guess>480 Too l ow. Tr y hi gher. Wh at ' s your guess>490 Too hi gh. Tr y l ower. Wh at ' s your guess>485 Too l ow. Tr y hi gher. Wh at ' s your guess>487 Good guess. Wel l done!

Write out the code that would run this program

b e t t e r f u t u r e – b r i g h t e r h o p e 6 3

Page 64: PiXL ICT to Computer Science Handbook 2017

File Handling – extension activities CSV files CSV (Comma Separated Values) is the most common import and export format for spreadsheets and databases. A csv file contains a number of rows, each containing a number of columns, values within separated by commas. Opening and reading CSV files

• Put some data into an Excel file:

Reading from a CSV file

• Try this:

Modes CSV files use the same modes as text files: “w” for Write – This overwrites the file, data previously in the file is lost. “a” for Append – This adds data at the end of the file, data previously in the file is retained. “r” for Read‐ This allows the content of the file to be read.

b e t t e r f u t u r e – b r i g h t e r h o p e6 4

Page 65: PiXL ICT to Computer Science Handbook 2017

csv.reader() The reader() function returns from a csv file a data item that can be read.

• Try this:

• What happens? csv.writer() The writer() function returns a data item that can be written to a row in a csv file. Note: As csv operates as though it contains a table consisting of rows and columns a row is written at a time.

• Try this:

• What happens? • Can you modify the code so that it prints “Hello” as a single word?

b e t t e r f u t u r e – b r i g h t e r h o p e 6 5

Page 66: PiXL ICT to Computer Science Handbook 2017

Appending data

• Try this:

CSV tasks Task 1 Create a program that asks the user their name and age each time it is run, and stores all the users’ responses in a csv file. Task 2 Add to the previous program to print all lines in the csv file.

b e t t e r f u t u r e – b r i g h t e r h o p e6 6

Page 67: PiXL ICT to Computer Science Handbook 2017

Databases SQL SQL is a standard language for creating manipulating databases. A comprehensive yet accessible guide to SQL is available here: http://www.w3schools.com/sql/ sqlite3 sqlite3 is library program, included in standard downloads of Python, which allows SQL commands to be used to manipulate a database in Python. Creating a database

• Try this:

Creating a table

• Try this:

• If you run this more than once, you will receive an error message.

b e t t e r f u t u r e – b r i g h t e r h o p e 6 7

Page 68: PiXL ICT to Computer Science Handbook 2017

• To avoid the error message whilst practising, try this:

Inserting data

• Try this:

Creating a cursor Note that the above example creates a “cursor”. This is a device to help navigate the database. In order to use the fetchall() and fetchone() functions, that respectively fetch all records to return a list or one record into a variable, it is necessary to introduce a cursor.

b e t t e r f u t u r e – b r i g h t e r h o p e6 8

Page 69: PiXL ICT to Computer Science Handbook 2017

Querying a database

• A query in SQL works as follows: SELECT required fields FROM name of table WHERE criteria is met

• In addition, the results can be sorted, as follows: SELECT required fields FROM name of table WHERE criteria is met ORDER BY name of field

• Try this:

Using fetchone()

b e t t e r f u t u r e – b r i g h t e r h o p e 6 9

Page 70: PiXL ICT to Computer Science Handbook 2017

Using fetchall()

Using indices Data is returned from sqlite3 as a virual row (in fact it’s a list or tuple). Indices can be used to pick a particular data item.

• Try this:

• Note that the first item in the “row” is at index[0].

b e t t e r f u t u r e – b r i g h t e r h o p e7 0

Page 71: PiXL ICT to Computer Science Handbook 2017

Database tasks: Task 1 Create a program that asks the user their name and age each time it is run, and stores all the users’ responses in a database in sqlite3. Task 2 Add to the previous program to allow the user to input a name, to receive the age of that person in return. Benefits of using sqlite3 The main benefit of using the database is that you can search the database directly using SQL and only read in the data you need. That way your variables in your program become much simpler to use. Compare this to using a text file. With a text file, you need to… • read in all the text • then split up the text • then search the list The SQL method is closer to how we think and therefore easier to use. It is computationally less complex.

b e t t e r f u t u r e – b r i g h t e r h o p e 7 1

Page 72: PiXL ICT to Computer Science Handbook 2017

List Handling Functions – everything you need to know Using methods with lists gives you the power to manipulate the data stored in the list quickly and effectively.

In Python the default format is: list.function apart from len()

Using the following list of planets, work out what the snippets of code below would do:

planetList = [“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”, “Uranus”, “Neptune”]

List Function Description

len() Find the number of items in a list.

len(planetList)

Hint: Remember lists start counting from zero.

append() Adds (appends) an item to the end of the list:

planetList.append(“Pluto”)

pop() A. If the parenthesis left empty then it will remove at item from the end of the list:

planetList.pop()

B. You can remove a specify item by giving the index of that item in the parenthesis:

planetList.pop(7)

insert() In order to place a new item into a list, you need to specify the index where you want to insert the new item and the item you want to insert:

planetList.inset(7, “Neptune”)

remove() With remove you give it the actual value of the item you want to remove. It will find and remove the first occurrence of that value in the list:

planetList.remove(“Pluto”)

extend() Adds two lists together. It adds the list in parenthesis to the list that is being called on:

b e t t e r f u t u r e – b r i g h t e r h o p e7 2

Page 73: PiXL ICT to Computer Science Handbook 2017

newPlanetList = [“Vulcan”, “Chronos”]

planetList = planetList.extend(newPlanetList)

index() Finds the index of an item in a list. It will be the first occurrence of an item, not every occurrence:

planetList.index(“Mars”)

sort() Sort a list into order, and will save it in the new order:

planetList.sort()

Beware: this will overwrite the previous list, so create a copy to sort, if you need to preserve the original list.

reverse() Reverses the order of items in a list in places and saves it. It just flips the list!

planetList.reverse()

Beware: this will overwrite the previous list, so create a copy to reverse, if you need to preserve the original list.

Hint: If you want to put a list into reverse alphabetical order, just call both sort() and reverse()

Multidimensional Lists and Functions

Anything that is true for single dimensional lists is also true for multidimensional lists, including methods.

b e t t e r f u t u r e – b r i g h t e r h o p e 7 3

Page 74: PiXL ICT to Computer Science Handbook 2017

Python Cheat Sheet

https://groklearning.com/resources/

b e t t e r f u t u r e – b r i g h t e r h o p e7 4

Page 75: PiXL ICT to Computer Science Handbook 2017

b e t t e r f u t u r e – b r i g h t e r h o p e 7 5

Notes

Page 76: PiXL ICT to Computer Science Handbook 2017

b e t t e r f u t u r e – b r i g h t e r h o p e7 6

Notes

Page 77: PiXL ICT to Computer Science Handbook 2017

BCSaccreditation

b e t t e r f u t u r e – b r i g h t e r h o p e 7 7

Teachers attending the PiXL Computer Science Course will be entitled to enrol on the ‘BCS Certificate in Computer Science’ with a 20% discount. The current pricing for enrolment including discount is £240 plus VAT.

The PiXL ICT to Computer Science provides 50% towards the requirement for Part One of the BCS Certificate.

Teachers will have 12 months from enrolment to complete the certificate.

The requirements to be certified as a BCS Certificate in Computer Science Teaching are:• Attend and reflect on CPD.• Complete a programming project.• Carry out a classroom investigation.

Sign up for the BCS Certificate in Computer Science Teaching and have your knowledge and skills in teaching Computer Science recognised. The Certificate is a professional qualification accredited by BCS, The Chartered Institute for IT.

Completion of the PiXL ICT into Computing course will have provided you with 50% of the CPD requirement to achieve Part One of the Certificate. It will also have equipped you with the skills you need to successfully achieve the standards required to complete Part Two of the Certificate.

Next stepsEmail [email protected] and provide evidence of your attendance at this the PiXL ICT into Computing course to receive your unique 20% discount code.

Register for the Certificate at www.bcs.uk/teachingcertificate. The 20% discount applies to September or November 2017 enrolment dates only.

TheBCSCertificateinComputerScienceTeaching

Page 78: PiXL ICT to Computer Science Handbook 2017

b e t t e r f u t u r e – b r i g h t e r h o p e7 8

GinnyRhodesGinny is Headteacher at St Crispin’s School in Wokingham, which is a successful large mixed comprehensive secondary school. Ginny also leads the national English team in the PiXL partnership, where she focuses on supporting schools improve standards via a mix of vibrant, purposeful conferences, complemented by online resources, training opportunities and development programmes.

MattHewlettMatt Hewlett is the subject lead for Computer Science at St Crispin’s School in Wokingham where he has also worked as an associate member of the senior leadership team. Matt enjoys running training sessions supporting the development of technology in teaching and co-ordinates inset sessions for computer science departments in his local federation of schools. He is also PiXL’s subject lead for Computer Science and ICT.

Nadine Vallient HillNadine is the product manager responsible for the Teaching Certificate at BCS. She has worked in education and education related sectors for over 20 years. She has taught children aged 5 to 14 in primary and middle schools, was a deputy head and ICT co-ordinator. She has been developing and delivering CPD for teachers in teaching and using technology since 2004. She is Chair of Governors for a Federation of three schools (a secondary and two primaries) and is passionate about ensuring all children have access to an excellent education delivered by teachers who have the skills,

knowledge and resources to make a difference.

MikeBlowerMike is currently Head of ICT and Computing at the North East Wolverhampton Academy. Mike has held this post for three years and overseen the move to Computing within the Academy. Mike has also undertaken work within PiXL, offering advice and guidance in the delivery of ECDL and worked as part of the Computer Science subject team to develop PiXL resources for the subject.

Mike JonesMichael is Director of Computing at Northfleet Technology College, Kent. The school is a lead school in the CAS Network of Excellence. Computer Science is delivered at GCSE and A level with numbers increasing from 22 to 125 in three years. Michael is directly involved in developing sustainability in computer science. He has designed and delivers the new PGCE in Computer Science at the University of Greenwich. Michael is currently developing an online portal, in partnership with Canterbury Christ Church University, with support and resources to address the primary CS curriculum

KayleighSmythKayleigh is currently an Assistant Curriculum Leader of Computer Science at Maricourt Catholic High School in Maghull, Liverpool. This is a mixed comprehensive school with 1,500 students on roll. She is also a senior team leader for OCR Computer Systems and Programming( A451). From the next academic year, Kayleigh will be the Principle Examiner for Computer Systems (J276/01).

DavidHowellsDavid is a Teacher of Computing at Key Stages 3, 4 and 5, as well as being the Key Stage 4 Co-ordinator in Computing and is currently a moderator for OCR. David has a degree in Business and in addition undertook a one year full-time subject knowledge enhancement course in Computing at the University of East London. He went on to complete his PGCE in Computing and was amongst the first cohort of PGCE graduates to do so.

DavidWoodsDavid is currently Head of IT and Computing at the Stonehenge School, Amesbury, Wiltshire. David has been in the post for ten years, so has experienced the transition from ICT to Computer Science. He has also successfully delivered GCSE OCR Computing for three cohorts, as well as delivering Eduqas Computer Science for the class of 2018 .

JacobLowreyJacob graduated with a BSc (Hons) in Computer Science from the University of Reading and completed a PGCE in Secondary ICT and Computing. He has been teaching at St Crispin’s School since September 2013, where he has lead A level Computer Science and implemented GCSE Computer Science. Jacob has held responsibility as an Associate Head of Department and whole school Gifted and Talented Co-ordinator. From 2017, Jacob will be taking on a new role as a Subject Leader of ICT and Computer Science.

Presenters

Page 79: PiXL ICT to Computer Science Handbook 2017

b e t t e r f u t u r e – b r i g h t e r h o p e 7 9

Contact details and feedback

Huddle

Lunch menu

The resources and presentations from today can be found on Huddle.

Select PiXL resources, Computer Science > 2017 ICT to Computer Science Conference.

If you do not have access to this workspace when you login (top left hand corner), then please contact huddle on [email protected] or email [email protected] you do not have access to this workspace when you login (top left hand corner), then please contact huddle on [email protected].

Homemade Lockey Farm pork sausage rolls (Branston pickle) Chicken skewers (spiced harissa) Prawn puri (garlic naan, coriander and yoghurt)Mini piglets pie (spinach and ricotta) Greek salad (baby gem and lemon oil) Spiced vegetable samosa (balti mayonnaise)

We would love to hear your feedback on today’s conference, please feel free to use the text feedback number: 078600 18804 or via the ‘PIXL events’ app.

If you have any queries and would like to contact a member of the Comput-er Science team directly, their details are below:

Matthew Hewlett – Computer Science Lead – [email protected]

Gurinder Badesha – PiXL Operations – [email protected]. Tel: 07527 888516

Page 80: PiXL ICT to Computer Science Handbook 2017

Agenda Time SessionDay1–23rdJune2017-IntroductionandInput(10.00to15.30)Registration09.00–09.4510.00 – 10.05 Welcome

10.05 -10.20 What is Computer Science? What are the course requirements for GCSE? What we will be covering within the course requirements.

10.20 – 11.15 Move into breakout groups – Fundamentals of Programming - Python as the programming language demonstrated and taught

11.15 – 11.30 Coffee

11.30 – 12.45 Fundamentals of Programming continued (breakouts)

12.45 – 13.30 Lunch

13.30 – 15.30 Fundamentals of Programming continued (breakouts)

15.30 - 15.45 Introducing BCS Partnership including ‘programming project’ and BCS Accreditation (Nadine Valliaent)

15.45 – 16.00 Queries and support (Introduction to learning environment and setting of homework selection) Matt Hewlett

Thefollowingroomswillbeusedforthebreakouts:PrincessSuite (Beginners)RoyalSuite (Intermediate)1871Suite (Advanced)

BLENDEDLEARNING(Onlinelearningandaccess)A Moodle account has been set up for all delegates to complete their blended learning part of the course. Each delegate will be required to complete at least two of the three mini challenges to further their learning, before attending Day 2.

You can access Moodle by visiting: http://cs.pixl.org.uk/course/view.php?id=8

Username: Initial of your first name followed by surname (lower case). Joe Blogs = jbloggsPassword: Password1@

All the resources and presentations from the two day course will be available on Moodle and Huddle.

Day2–12thJuly2017-(10amto16.00)–ApplyingLearning*AgendasubjecttochangedependentonoutcomesofDay1.10.00 - 10.10 A recap – where should you be by now? What should you be able to do?

10.10 - 11.30 Groups (as before on Day 1 and Blended Learning) Python next steps

11.30 – 11.45 Coffee

11.45 - 12.45 Continuation of group work focusing on Python

12.45 – 13.30 Lunch

13.30 – 15.45 Begin programming of BCS practical programming project

15.45 – 16.00 Key note speech from BCS – further accreditation opportunity

b e t t e r f u t u r e – b r i g h t e r h o p e