31150-Introduction To Python v2.1
31150-Introduction To Python v2.1
1, July 2012
PAGE 1 OF 1
DURATION: TWO CLASSROOM PERIODS
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
Thanks
Many thanks go to Peter Thompson for his invaluable help, particularly with the sections on lists and dictionaries, and
also to Brian Lockwood for proof reading and suggestions for improvements.
Copyright Notice
To share:
You may copy, distribute & transmit the work. You may provide digital or printed copies for students.
To remix:
You may adapt or improve the work.
Attribution:
You must attribute the work to Mark Clarkson by including my name on the front cover and in the footer.
Noncommercial:
You may not use this work for commercial purposes. If you are providing printed copies you may only charge a
fee to cover production costs, not profit. You must not charge for a digital version of the work.
Share alike:
If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or
similar licence to this one. Please let me know if you make significant changes so that I can include them in my
own copies.
Version History
PAGE 1 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
An Introduction to Python
Table Of Contents
PAGE 2 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
Go to the python.org website and download a standard installation of the latest version of Python
(currently 3.2). This will provide you with everything you need.
NB: Do NOT download Python 2.x as some of the programs in this course will NOT work! It
must be version 3 or higher!!!
The documentation for Python is very good, and you can find it at http://docs.python.org/py3k/
1.1b - IDLE
You can write Python code in notepad, or any other simple text editors - but it is easier if you use a program like IDLE
(which comes with the standard Python installation) because it helps with things like indentation and debugging
(things we will cover later). We will be using IDLE throughout most of the course.
When you run IDLE you will see a window like this:
NB: The (few) screenshots in this booklet are taken from Mac OS X. Windows users may see something slightly
different, but largely similar.
You can type simple commands at the prompt (>>>).
Try typing:
2+2
17-9
16/4
3*7
PAGE 3 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
print(“Hello, World”)
Save this file in your Python folder (call it “hello world.py”) and then press F5 to run it.
The main IDLE window should show you your output:
Main Python window
“Hello World”
program window
PAGE 4 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
1.3 Arithmetic
1.3a - Addition
Create a new file and type in the following code:
firstNumber = int(input(“Enter a number between 1 and 100: “))
secondNumber = int(input(“Enter another number between 1 and 100: “))
print(“firstNumber + secondNumber =”,firstNumber+secondNumber)
Save this file as “addition.py” and press F5 to run it.
1.3b - Subtraction
Repeat the last program, but this time make it subtract the two numbers. Save it as “subtraction.py” and test it works.
1.3c - Multiplication
Repeat the last program, but this time make it multiply the two numbers. Save it as “multiplication.py” and test it works.
1.3d - Division
Repeat the last program, but this time make it divide the two numbers. Save it as “division.py” and test it works.
1.3e - Square
Repeat the last program, but this time make it calculate x2. Save it as “square.py” and test it works.
1.3f - Powers
Repeat the last program, but this time make it calculate xy. Save it as “powers.py” and test it works. (Hint: use x**y)
1.3g - Mod
Repeat the last program, but this time make it calculate the modulus (remainder) of a division. Save it as “mod.py” and
test it works. (Hint: use x%y)
Try writing a program that will take a number, add four and then multiply by three.
Put the number 7 into both programs and check that they work correctly.
PAGE 5 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
1.4 Comments
Comments make it MUCH easier to see what you have done when you come back to your code several months later
and you should use them regularly.
PAGE 6 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
2.1 Variables
NAME: It is REALLY important to choose a good name that shows what the variable is for. So in a computer game
you might use numberOfLives, score, bulletsRemaining and health. You probably wouldn’t want var1, var2, var3 and
var4.
TYPE: Python tries to hide the data type to make life easier for you, but read the rest of this chapter to see what the data
types are - it really is important.
VALUE: This is what you have saved into the variable at the minute - the whole point of using them!
When we create a variable we call it ‘declaring’ a variable. When we give the variable its first value we call it ‘initialising’ a
variable.
If we want to tell the computer to ‘Create a variable called “age” and give it the number 12’, we say:
age = 12
2.1b - Assignment
One of the most frequent things you will do in programming is to store values.
The following code will work out an answer and print it to the screen:
print(3+4)
But this code will work out an answer and store it in a variable called ‘answer’:
answer = 3 + 4
Assignment always works to the left, so work out the answer on the right and save it last.
You can use a variable in a calculation, and use the same variable to store the answer. Try the following code:
score = 112
score = score + 1
print(score)
PAGE 7 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
2.2 Strings
print(sentence)
If you add strings together, you end up with one long string.
print(firstLine + secondLine)
print(start,number)
2.3 Numbers
2.3a - Integers
There are two main types of numbers in Python. We’ll start with Integers (whole numbers).
We can force Python to make something a whole number by saying int(number). Like this:
number = 3.7
newNumber = int(number)
print(newNumber)
Note that this won’t round the number up, it just takes the whole number part.
2.3b - Floats
The second main type is a floating point, or just “float” for short (a decimal). We can force Python to make something a
float by saying float(number). Like this:
number = 3
print(number)
newNumber = float(number)
print(newNumber)
2.3c - Casting
Casting is the technical term for changing the type of data you are working with. You’ve already been casting by saying
int(), float() and str() to change the data type. But now you know what it’s called!
2.3e - Long
Another number type you might need occasionally is long, or a long integer. Integers in Python can only hold numbers
from -2billion to +2billion (actually from -2,147,483,646 to +2,147,483,647). If your number is going to be outside that
range then you will have to use a long to keep count.
PAGE 9 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
2.4 Boolean
2.4a - True or False?
A boolean (bool for short) can store one of only two possible values - True or False. (NB: Note the capital letters!)
This is useful for logical tests (e.g. is 22/7 bigger than 3?) or to check if something has been completed (this becomes
useful in section 3).
Here is an example:
bigger = False
print(bigger)
The main advantage of booleans is that they are very small and simple.
PAGE 10 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
2.5 Lists
2.5a - What’s a list?
NB: In some languages you would do this stuff with ARRAYS, which work in a very similar way
A list is a collection of something, like integers:
numbers = [3,5,9,6]
print(numbers)
print(numbers[0])
print(numbers[1])
print(numbers[2])
print(numbers[3])
You use square brackets to write the list and then square brackets again to say which LIST ELEMENT you want. We
start counting from 0 so the first number in our list is numbers[0] and the last one is numbers[3].
print(names[0],"is",ages[0])
print(names[1],"is",ages[1])
print(names[2],"is",ages[2])
print(names[3],"is",ages[3])
Although you can’t edit each list element as you can with ordinary lists.
PAGE 11 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
If you find your list is too short, you can add one more value at a time by using the APPEND procedure.
names = [“Rita”, “Sue”]
names.append(“Bob”]
print(names)
If you want to add more than one value at a time you can use EXTEND procedure.
names = [“Graham”,”Eric”,”Terry G.”]
extraNames = [“Terry J.”, “John”, “Michael”]
names.extend(extraNames)
print(names)
Try the code above with APPEND instead of EXTEND and see what happens.
If you want to know where in the list it is, you can use INDEX:
names = [“Graham”,”Eric”,”Terry”]
position = names.index(“John”)
print(position)
BUT be careful because if the thing you’re searching for isn’t there, you’ll get a nasty error. Perhaps try:
names = [“Graham”,”Eric”,”Terry”]
if “Eric” in names:
position = names.index(“John”)
print(“Eric in position”,position)
else:
print(“Eric not found”)
PAGE 12 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
3.1 Selection
Selection means selecting (or choosing) what to do next. Should I cycle to school, or ask for a lift? If
it’s a sunny day I might cycle. If it’s raining, I’ll ask for a lift.
Notice how the colon (:) is used to say what should happen in each case.
Also notice that the indentation is VERY important. Python only knows when your IF statement is finished by looking
at the indentation!
Try this program to see what I mean:
That last line will be printed no matter which option you chose.
PAGE 13 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
answer = int(input(menu))
if answer == 1:
print("You look lovely today!")
elif answer == 2:
print("You smell funny.")
elif answer == 3:
print("Two wrongs don't make a right. But three lefts do...")
elif answer == 4:
print("The pen is mightier than the sword.")
elif answer == 9:
print("Goodbye!!!")
• If you are testing for equality, use a double equals (is 3x2 == 6?)
3.1d - Inequalities
This seems a good point to mention some of the most important inequalities used in selection:
< Less Than e.g. 3 < 5
> Greater Than e.g. 5 > 3
<= Less Than Or Equal To e.g. 3 <= 5 5 <= 5
>= Greater Than Or Equal To e.g. 5 >= 3 5 >= 5
!= Not Equal To e.g. 5 != 3 3 != 5
PAGE 14 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
3.2 Iteration
Iteration is a posh way of saying “loop” (iteration literally means to do something again).
Loops are absolutely vital in programming in order to avoid having to write sequences of code out again and again. And
they come in several forms:
We use the TAB key to INDENT the code to show which bit of code we repeat.
How many times do you think this loop will repeat? Try it and find out:
number = 1
while number < 10:
print(“This is turn”,x)
number = number + 1
print(“The loop is now finished”)
Make sure you understand why the last line only prints out once, at the end of the loop.
A WHILE loop is ideal if you don’t know exactly how many times you will need to repeat the code.
This example will keep asking for a number until it gets the right one:
targetNumber = 7 # this is the correct number
guess = input(“Guess a number between 1 and 10”)# ask for a guess
while guess != targetNumber: # repeat if the answer is wrong
print(“Wrong, try again”)
guess = input(“Guess a number between 1 and 10”)
print(“Congratulations - that’s right!”) # do this after the loop
A motorbike costs £2000 and loses 10% of its value each year. Print the bike’s value each year until it falls below £1000
value = 2000
PAGE 15 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
You can be a bit more specific with your loop by setting a start and an end number:
for loopCounter in range(5,10):
print(loopCounter)
Remember that loops are closed (or finished) by removing the indentation:
for loopCounter in range(1,4):
print(loopCounter,"potato")
print("4")
for loopCounter in range(5,8):
print(loopCounter,"potato")
print("more")
1. Look closely at the three times table example on the last page. Write a similar program to calculate the four times
table.
2.Write a program that will calculate the 5 times table.
3.Try writing a program that will prompt for an integer (whole number) and print the correct times table (up to 12x).
Test with all of the tables up to 12.
PAGE 16 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
First, he (or she) cleans all the windows on the first floor:
for room in range(1,5):
print(“Room”,room,”cleaned”)
Then he (or she) does the 2nd floor and the 3rd, and so on:
floor = 1
for room in range(1,5):
print(“Room”,floor,room,”cleaned”)
floor = 2
for room in range(1,5):
print(“Room”,floor,room,”cleaned”)
floor = 3
for room in range(1,5):
print(“Room”,floor,room,”cleaned”)
Think about what this program will do. Decide what you think will happen. Then try it.
for x in range(1,11):
for y in range(1,11):
print(x,"x",y,"=",x*y)
Were you correct? Was it easy to follow the logic? How many lines of code would you need to write it with only 1 loop at
a time?
PAGE 17 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
Write a program that will start at 1 and end at 1,000,000. The program should print each number followed by its square
but break once this square is bigger than 4096.
Write a program that will prompt for an integer and then calculate the factorial of that number.
PAGE 18 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
3.3 Procedures
If the same piece of code needs to be used several times we can use a loop - but only if those times
are all together. If you need to run the same bit of code again later, you can use a procedure.
Here the top two lines are a procedure called output. The procedure expects to be given one variable (which it calls
number) and will happily do its thing when told to.
The main program is underneath, and the line that says output(x) will run the output procedure and give it the
variable x to work with.
You can pass as many parameters as you like to a procedure as long as you set it up correctly.
PAGE 19 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
output("C")
output("A",87)
output("E",12,"Rubbish!")
You can pass as many (or few) of the parameters as you like - as long as they’re in the right order. This means you have to
plan the procedure quite carefully.
3.3d - Functions
So far our procedures have just printed an answer to the console. Sometimes a procedure will have to send some data
back. This is called a return. Procedures that return something are called functions. In Python that isn’t a huge
distinction, but in some programming languages it is very important.
def calculate(number):
newnumber = number / 100
return (newnumber)
The line return(newnumber) passes the value of the newnumber variable back to the main program.
The line y = caluclate(x) shows that the main program expects a value to be returned and has somewhere to
store it.
3.3e - Modules
There are some procedures already built in to Python (print, for example). Modules (sometimes known as libraries in
other languages) are collections of extra procedures and functions that are pre-written.
Try this program first. It won’t work, but I’m trying to prove a point (sqrt is short for square root):
number = 49
answer = sqrt(49)
print(answer)
number = 49
answer = math.sqrt(49)
print(answer)
You can find a list of modules at http://docs.python.org/py3k/modindex.html
PAGE 20 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
4.1 Turtle
4.1a - Creating a Turtle
If you’ve ever used Logo, Roamer or BeeBots then you’ll be familiar with the concept of a Turtle program. If you’re not,
then try this code:
import turtle #import the turtle module
window = turtle.Screen() #create a window
timmy = turtle.Turtle() #create a turtle called timmy
timmy.forward(150)
timmy.right(90)
timmy.forward(100)
window.exitonclick() #close the window when clicked <-- VERY important
Remember that we use a FOR loop if we know how many times we want to repeat something. Check it works!
A square has 4 sides, of length 150, and with 900 turns. A hexagon has 6 sides, of length 150, and with 600 turns. Try to
draw a hexagon.
PAGE 21 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
4.1d - Procedures
It would be really helpful if, instead of writing:
for loopCounter in range(4): #repeat the next bit 4 times
timmy.forward(150)
timmy.right(90)
def drawASquare(whichTurtle):
for loopCounter in range(4):
whichTurtle.forward(150)
whichTurtle.right(90)
window = turtle.Screen()
timmy = turtle.Turtle()
drawASquare(timmy)
window.exitonclick()
It just draws a square, right? OK, now in the main program replace :
drawASquare(timmy)
with :
for loopCounter in range(72): #repeat 72 times
drawASquare(timmy)
timmy.left(5) #turn 50. Note that 3600 ÷ 5 = 720
If that took a bit too long, try inserting this line straight after you have created Timmy :
timmy.speed(0)
PAGE 22 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
4.1e - Spirograph
There used to be a toy called a Spirograph that let you draw lots of coloured patterns like this.
To make the pictures more interesting, we can try changing the colour:
timmy.color(‘blue’)
On its own, that might not look too amazing, but try this:
colourCounter = 1
for loopCounter in range(72):
drawASquare(timmy)
timmy.left(5)
if colourCounter == 1:
timmy.color(‘blue’)
elif colourCounter == 2:
timmy.color(‘red’)
elif colourCounter == 3:
timmy.color(‘yellow’)
elif colourCounter == 4:
timmy.color(‘green’)
colourCounter = 0
colourCounter += 1
Try using pentagons instead of squares, or triangles, or octagons . Try turning amounts other than 50.
drawASquare(timmy)
drawAHexagon(tina)
window.exitonclick()
See what other patterns you can come up with using 2, 3 or even more turtles.
PAGE 23 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
For a simple example, our user has to enter the correct password (‘p@ssword’):
import re
userInput = input(“Enter your password: “)
if re.search(”p@ssword”, userInput):
print(“Correct password entered”)
else:
Print(“Error, incorrect password”)
Rules can be a bit more detailed. If we need a postcode that looks like TS16 0LA we can say:
import re
#postcodeRule is “letter, letter, number, number, space, number, letter, letter”
postcodeRule = “[A-Z][A-Z][0-9][0-9] [0-9][A-Z][A-Z]”
userInput = input(“Enter a postcode: “)
if re.search(postcodeRule,userInput):
print(“Valid postcode!”)
else:
print(“Invalid postcode!”)
The check is case sensitive, and only checks the very start of the string.
PAGE 24 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
There are several codes you can use to create your rules:
a - the letter ‘a‘ + - allow multiple instances
[a-z] - a lower case letter ^ - only match at the start
[A-Z] - an upper case letter $ - only match at the end
[a-zA-Z] - an upper or lower case letter
[0-9] OR \d - a number
[a-zA-Z0-9] OR \w - a number or letter
. - any character
\. - a full stop
Some examples:
import re
string = “Now for something completely different”
if re.search(“^N”,string):
print(“Test 1 - Success!”) #Will pass, it starts with “N”
if re.search(“^for”,string):
print(“Test 2 - Success!”) #Will fail, it doesn’t start with “for”
if re.search(“\w$”,string):
print(“Test 3 - Success!”) #Will pass, it ends with a number or letter
if re.search(“^.+t$”,string):
print(“Test 4 - Success!”)
#Will pass, it starts with a number of characters (^.+) and ends with a “t” (t$)
PAGE 25 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
5.2 – Dictionaries
5.2a - Introduction
Dictionaries are a type of data structure that are a little like lists in that they are a sequence of elements. However,
elements are not accessed using indexes as are lists, but using keys. Each element in a dictionary consists of a key/value
pair separated by a colon. For example “george”:”blue”. The string “george” is the key and “blue” is the value. Keys can be
other datatypes, for example numbers. However, the datatype of all keys in a dictionary must be the same.
Because elements are retrieved using their keys looking them up is done in just one go. This means it is a very fast
operation which takes the same time no matter whether the dictionary has 1 or 1 million elements.
5.2b - An Example
# Note the use of curly brackets at the start and end of the dictionary, and
colons to separate the key/value pairs.
logins = {“john”:”yellow”, “paul”:”red”, “george”:”blue”, “ringo”:”green”}
print(logins[“george”]) => “blue”
And
# Change george’s password to purple
logins[“george”] = “purple”
print(logins)
Gives
{“ringo”: “green”, “paul”: “red”, “john”: “yellow”, “george”: “purple”}
Note how the order of the dictionary has changed. It is not possible to stipulate the order in a dictionary, but this does
not matter as sequential access it not needed because element values are accessed using keys.
5.2c - Iteration
Dictionaries can be iterated over using a for loop like so:
# Print all the keys
for item in logins:
print(item)
# Print all the values
for item in logins:
print(logins[item])
# Print both
for key, value in logins.items():
print(“The key is:”, key, “and the value is:”, value)
Prints:
The key is: ringo and the value is: green
The key is: paul and the value is: red
The key is: john and the value is: yellow
The key is: george and the value is: blue
There are many methods and functions associated with dictionaries. Look at the official Python documentation. Also,
values stored in a dictionary can be virtually any data type. For example, athletes and their list of running times as values.
Note that samantha has one less time than mary.
training_times = {“mary”:[12, 45.23, 32.21], “samantha”:[ 11.5, 40.1]}
PAGE 26 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
f.close()
f = open("temp","r")
print(f.read())
f.close()
You should have the following printout:
Once you have finished with a file you MUST get into the habit of closing it, or problems will occur. To do so simply
write f.close().
PAGE 27 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
It is important to remember that Python keeps track of where you are up to.
Try the following code:
f = open("temp","r")
print(f.readline())
print("That was the first line")
print(f.readline())
print("That was the second line")
print(f.read())
print("That was all the rest")
print(f.readline())
print("I bet that was blank")
f.close()
You can tell Python to go back to the start by using the seek() procedure:
f = open("temp","r")
print(f.readline())
print("That was the first line")
f.seek(0)
print(f.readline())
print("That was the first line again")
f.close()
You can read one character at a time (or 5 characters at a time) by passing a parameter:
f = open("temp","r")
print(“The first letter is:”)
print(f.read(1))
print(“The second letter is:”)
print(f.read(1))
f.close()
PAGE 28 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
5.3e - Writing
At some point you will want to write some data to a file. You can only write strings to file, so you will have to convert any
numbers before you can write them:
x = 3
y = " is the magic number"
f = open("temp","w") #remember that “w” means the old file will be overwritten
x = str(x)
f.write(x + y)
f.close()
f = open("temp","r")
print(f.read())
f.close()
#The second part will print it to the screen to check it looks OK.
f = open("temp","r")
print(f.read())
f.close
PAGE 29 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
#The second part will print it to the screen to check it looks OK.
f = open("temp","r")
print(f.read())
f.close
#This part creates two strings either side of the 4th line.
f = open("temp","r")
string1=""
for n in range(0,3): #Copies the first 3 lines into string1
string1 = string1 + f.readline()
f.readline() #This command makes Python skip the 4th (blank) line
string2=""
for n in range(0,3): #Copies the next 3 lines into string2
string2 = string2 + f.readline()
f.close()
#Next we rewrite all this data to a new file (with the same name).
f = open("temp","w")
f.write(string1)
f.write("4\n") #writes in the missing line in the middle
f.write(string2)
f.write("More!") #writes in the missing line at the end
f.close()
PAGE 30 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
All of these programs should include the following comment block at the start (preferably completed) as well as
appropriate comments within the code to explain what is going on:
"""
Filename:
Author:
Date:
Description:
"""
PAGE 31 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
PAGE 32 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
PAGE 33 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
PAGE 34 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
All of these programs should include the following comment block at the start (preferably completed) as well as
appropriate comments within the code to explain what is going on:
"""
Filename:
Author:
Date:
Description:
"""
PAGE 35 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
Extension 1: Count and output the number of steps required to find the number.
Extension 2: Generate a random number as the target.
Extension 3: Print all of the values that require exactly 7 steps to find them.
Extension 4: Find the mean average number of steps required to find every number frpm 1 to 100.
Extension 5: Calculate the maximum and mean number of steps required if the range of numbers is 200, 1,000, 2,000,
10,000 & 100,000. Are you surprised by the results?
PAGE 36 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
x = str.islower(string[3])
#Returns a bool depending on whether the character is lower case x = True
x = str.isupper(string[0])
#Returns a bool depending on whether the character is upper case x = True
x = str.isdigit(string[5])
#Returns a bool depending on whether the character is a digit x = False
x = str.isspace(string[7])
#Returns a bool depending on whether the character is a space x = True
PAGE 37 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
PAGE 38 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
Run again:
Compare x[0] and x[1], 3 < 5 so no swap
Compare x[1] and x[2], 5 !< 2 so swap [3,2,5,9]
Compare x[2] and x[3], 5 < 9 so no swap
Run again:
Compare x[0] and x[1], 3 !< 2 so swap [2,3,5,9]
Compare x[1] and x[2], 3 < 5 so no swap
Compare x[2] and x[3], 5 < 9 so no swap
Run again:
Compare x[0] and x[1], 2 < 3 so no swap
Compare x[1] and x[2], 3 < 5 so no swap
Compare x[2] and x[3], 5 < 9 so no swap
PAGE 39 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
Extension 1: Write the menu procedure so that the shade will automatically be shown (rather than being hard-coded)
Extension 2: Improve the menu further so that it will produce as many menu items as there are lines in the data file (it
might be useful to use the string “EOF” to signify the end of the file.
Extension 3: Include an extra menu item to allow the user to add their own shades with associated RGB colours. This
should include suitable validation to prevent impossible or incomplete entries.
PAGE 40 OF 41
MARK CLARKSON, 2012
AN INTRODUCTION TO PYTHON
OCR GCSE COMPUTING
Extension 1: Add an extra field to the database for a 4 digit PIN which should be prompted for and checked following
the entry of the ID number. The user should also have the option to change their PIN.
Extension 2: Add another field to record whether the card is blocked. Three incorrect PIN attempts should
permanently lock the card. PIN attempts should only be reset by correctly entering the PIN. Simply removing the card
and trying again should not work.
Extension 3: Create an encoding algorithm that will store the PIN in a format that cannot be read by just looking t the
file. Only by running the PIN attempt through the same algorithm can the match be found.
PAGE 41 OF 41
MARK CLARKSON, 2012