Gcse Computer Science Learning Guide Programing in Python 3
Gcse Computer Science Learning Guide Programing in Python 3
This is a general guide to assist in learning Python 3. Not all the components here are
necessary for teaching or learning programming for Edexcel GCSE (9-1) Computer Science,
for example Turtle graphics knowledge is not required. Teachers should refer to the
specification for the content which will be assessed.
Built-in functions
Syntax Description Example
len() Calculates the length of a string. >>> ans=len("my string")
>>> ans
9
print() Displays information on the screen. >>> print(“Hello world”)
type() Displays the type (int, bool, str or float) >>> ans=7.8
of a variable or value. >>> type(ans)
<class 'float'>
int() Converts a string or float value into an >>> ans=7.8
integer number. >>> int(ans)
Often used in conjunction with the input 7
function, e.g.
number = int(input(“Please enter the
number of T-shirts you require:”))
input(“prompt”) Prompts for input from the user. The >>> reply=input("Enter
data entered is assigned to a variable. your name: ")
Enter your name: Fred
>>> reply
'Fred'
Version 2 Page 1
Built-in functions
Syntax Description Example
range() Creates a list of numbers. >>> for next in
Often used with the for loop, e.g. range(1,4):
range(start number, end number, in print(next)
steps of). End number is the number 1
after the last number required. 2
3
max() Returns the largest of a set of numbers. >>>max(12,16, 33)
33
Version 2 Page 2
dimensional array
assign a value to an element myArray[0][4] = 99
in a two-dimensional array myArray[2][3] = 74
print the contents of a two- for row in range(rowLength):
dimensional array, a row at a print(myArray[row])
time
Version 2 Page 3
Selection constructs
Syntax Description Example
if <expression>: If <expression> is true if colour == "green":
<commands> then commands are print("It is safe for you to cross.")
executed.
if <expression>: If<expression> is true if colour == "green":
<commands1> then<commands1> are print("It is safe for your to cross.")
executed otherwise
else: else:
<commands2> are
<commands2> executed print("STOP! It is not safe to cross.")
Version 2 Page 4
Iteration constructs
Syntax Description Example
for variable in Executes myList=["cat","dog","cow","donkey","rabbit","canary"]
<expression>: <commands> for next in myList:
<commands> for a fixed
print(next)
number of
times, given by
<expression>.
while Executes answer="N"
<condition>: <commands counter=0
<commands> whilst
while answer != "Y":
<condition> is
true. This is a print("Are you hungry? You have been asked {0}
pre-condition times.".format(counter))
loop. answer = input("Please respond Y or N:")
counter = counter + 1
print("Please get something to eat!")
File handling
Syntax Description Example
<file identifier variable> = Opens a file. The flag is: myFile=open(“file.txt”,“r”)
open(<filename>, “flag”) reading (r), writing (w) myFile=open(“file.txt”,“w”)
appending (a). This opens the
file and creates a file object.
<file identifier Closes the file. myFile.close()
variable>.close()
<file identifier Writes string to a file. Use “\n” myFile.write(“this is a record
variable>.write(<string>) at the end of each record. \n”)
Variable = <file identifier Reads a line from a file and record = myFile.readline()
variable>.readline() assigns to a variable.
Version 2 Page 5
How to… Explanation
start the debugger In IDLE shell choose Debug/Debugger
save a file File > Save
Hint: file type is always.py
run a program Run > Run module
or F5
display the last command entered in the alt p
shell
repeat the last command entered in the alt n
shell
indent and dedent blocks of code Select and use Format > Indent and Format
> Dedent
interrupt a program that is running control z or control c
Precedence
Parentheses control the order in which expressions are calculated. Anything in parentheses
is evaluated first.
The precedence order is: parenthesis (round brackets), exponential, division and
multiplication, subtract and add.
BEDMAS
Version 2 Page 6
Python errors Description
TypeError When an operation is attempted that is invalid for that type of
data.
RuntimeError An error that occurs when the program is running.
NameError When a name is used that is not known about (often a
misspelt variable name).
ZeroDivisionError Dividing a number by zero.
KeyBoardInterrupt When a program is interrupted from the keyboard by pressing
control+c
Version 2 Page 7
Mathematical operator Operation
symbol
/ divide
* multiply
** exponential
+ add
- subtract
// integer division
% modulus (remainder after the division)
Symbol Description
AND Returns true if both conditions are true.
OR Returns true if one of the conditions is true.
NOT Reverses the outcome of the expression; true becomes false, false
becomes true.
Version 2 Page 8
Python command colour What does it Example
coding show
green strings “hello”
purple functions print()
black variables and data myName
orange key commands if
red comments # This is a comment
Version 2 Page 9
Examples of modules
math module
Function name Function explanation Example
math.pi Displays the pi constant. >>>math.pi
3.141592653589793
math.pow() Displays the first number >>> ans=math.pow(2,3)
raised to the power of the >>>ans
second number.
8.0
math.sqrt() Displays the square root >>> ans=math.sqrt(1024)
of a number. >>>ans
32.0
random module
Function name Function explanation Example
random() Returns a random >>> import random
number. >>> ans =
random.randint(1,6)
>>>ans
3
winsound module
Function name Function explanation Example
winsound.Beep(frequency,duration Makes a sound in the import winsound
) range frequency (hertz) frequency = 100
for the duration
for i in range (40):
(milliseconds).
winsound.Beep(frequency
,200)
frequency = frequency +
50
winsound.PlaySound(filename, Plays the sound file winsound.PlaySound("SystemE
flags) identified by file name xit", winsound.SND_ALIAS)
using the flags to indicate
type.
webbrowser module
Function name Function Example
explanation
webbrowser.open("URL") Open the URL given as a webbrowser.open("http://ww
string in the default web w.bbc.co.uk")
Version 2 Page 10
browser.
Version 2 Page 11
Turtle graphics (using x,y cartesian co-ordinates)
Turtle command Explanation example
import turtle Imports module for turtle import turtle
graphics.
t = turtle.Pen() Makes a turtle. t = turtle.Pen()
turtle.shape(“shape”) Sets shape of turtle (“arrow”, t = turtle.shape(“turtle”)
“turtle”, “circle”, “square”).
turtle.color(colour) Changes turtle colour. t = turtle.color(“red”)
turtle.forward(distance) Moves turtle t = turtle.forward(“100”)
turtle.backward(distance) forward/backward by distance
given in direction it is
heading.
turtle.right(angle) Turtle turns right or left by t = turtle.right(“90”)
turtle.left(angle) angle given.
Version 2 Page 12
turtle.undo(number) Undoes the last command. t = turtle.undo()
turtle.delay(number) Inserts a delay before next t = turtle.delay(50)
command.
Version 2 Page 13
Glossary
Term Definition
Algorithm A sequence of steps to perform a task.
Flowchart A graphical representation of an algorithm that uses flow lines
and shapes to represent the operations.
Pseudocode Pseudocode looks a bit like a programming language but, unlike a
real programming language, it does not require a strict syntax.
This makes it particularly useful for designing programs.
Because it is not an actual programming language, pseudocode
cannot be compiled into executable code.
Structured English Similar to pseudocode, structured English is a way of describing
an algorithm using English words to describe each step of the
process.
Program code The set of instructions that form a program written in a particular
programming language.
Command sequence A block of program commands that are executed sequentially, i.e.
one after the other.
Loop A piece of code that keeps repeating until a certain condition is
reached.
Version 2 Page 14
Term Definition
Output Data that is sent out from a program to a screen, a file or a
printer.
Indentation Positioning a block of code, e.g. a for loop or an if statement,
further from the margin than the main program.
The use of indentation makes programs easier to read.
In Python correct indentation is very important, since indenting
starts a block and unindenting ends it.
Comment Text included in code that is for the human reader and is ignored
by the program.
In Python, comments are indicated by the # symbol at the start
of a line.
Structural components The parts of a program such as variable declarations, data
structures or subprograms.
Version 2 Page 15
Term Definition
Relational operators Relational operators take two operands and compare them.
Examples of relational operators are: < (less than) < (greater
than), == (equal to), != (not equal to).
Relational operators are used in conditional statements, especially
in loops, where the result of the comparison decides whether
execution should proceed.
Logical operators Logical operators take two operands and compare them,
returning True or False depending on the outcome.
Examples of logical operators are: AND, OR, NOT.
Logic error An error in the design of a program, such as the use of a wrong
programming control structure or the wrong logic in a condition
statement.
This type of error may not produce an error message, just the
wrong outcome.
Runtime error An error detected during program execution, often due to a
mistake in the algorithm or in the type of data used.
Syntax error An error that occurs when a program statement cannot be
understood because it does not follow the rules of the
programming language.
Trace table A technique used to test for logical errors in a program. Each
column of the table is used to represent a variable and each row
to show the values of the variables at different stages of the
program.
Break point A point in the code when a program is halted so that the
programmer can investigate the values of variables to help locate
errors.
Bug An error in the code that prevents a program from running
properly, or from running at all.
Debugger A tool that helps to detect, locate and correct faults (or bugs) in
programs.
Single step When a program is executed one statement at a time under user
control.
Watchers Allow the programmer to watch for certain events, such as
variables changing as the program is running.
Test plan A list of tests to be carried out, designed to test a program in the
widest possible range of situations to make sure it is working.
Test data Data used in a test plan to test what happens when the input
data is valid, invalid or extreme.
Valid test data Test data that is within the normal range and should be accepted
by the program.
Version 2 Page 16
Term Definition
Invalid test data Test data that is outside the normal range and should be rejected
by the program.
Extreme test data Test data that is still valid, but is on the absolute limits of the
normal range and should be accepted by the program.
Textual user interface A type of interface in which the user interacts with the computer
program by using a keyboard to enter commands and make
selections.
Graphical User Interface A type of user interface that uses windows, icons, buttons and
(GUI) menus. A pointer is used to make selections.
Validation Validation is designed to ensure that a program only operates on
appropriate data, e.g. that it has an appropriate format or value.
It involves checking the data that a user enters or that is read in
from a file and rejecting data that does not meet specified
requirements.
However, validation can only prove that the data entered is
appropriate, not that it is correct.
Integrated development A text editor with useful built in tools to help programmers
environment (IDE) develop programs, e.g. IDLE.
Cartesian co-ordinates A co-ordinate system that specifies a point uniquely using (x,y)
co-ordinates.
Version 2 Page 17