Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Gcse Computer Science Learning Guide Programing in Python 3

Uploaded by

greeper689yt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Gcse Computer Science Learning Guide Programing in Python 3

Uploaded by

greeper689yt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Detailed guide for learning to program 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.

Python data types


Data Python Explanation Example
type Abbreviation
integer int A whole number. 45
string str A sequence of characters that can include “Have a nice
letters, spaces and other characters. day!”
float float A number with a fractional part. Also known as 16.76
a real number.
Boolean bool Boolean or logical data that can only have one True
of two values: True or False. False

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

Variables and lists (arrays)


Syntax Description Example
variableName = <value> Assigns a value to a myString=”hello world”
variable. myNumber= 89
myAnswer=True
variableName = Computes the value of an number= 7 * 8
<expression> expression and assigns it to answer= len(“this is the
a variable. age”)
listName = Assigns a set of values to a myList=
[value,value,value] list. [“apple”,”oranges”,8]
listName[index] Identifies an element of a myList[2]
list by reference to its
position in the list, where
index is an integer value
starting at 0.
listName[row][column] Identifies an element of a myList[0][6]
nested list (equivalent to a
two dimensional array).

Nested lists in Python (two-dimensional arrays)


How to… Example
initialise a two-dimensional rowLength=4
array columnLength=6
myArray=[[0 for row in range(rowLength)] for column in
range(columnLength)]
address an element in a two- [row][column]

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.")

if <expressionA>: If <expressionA> is true if answer == 1:


<commands1> then <commands1>are print("You will make a new friend
executed, else if this week.")
elif <expressionB>:
<expressionB> is true then
<commands2> elif answer == 2:
<commands2>are
elif <expressionC>: executed, etc. print("You will do well in your
GCSEs.")
<commands3>
elif answer == 3:
print("You will find something you
thought you’d lost.")
try: If <commands1> cause an try:
<commands1> error, then <commands2> ans=numOne/numTwo
are executed. If
except: except ZeroDivisionError:
<commands1> execute
<commands2> successfully, then print("Second number cannot be
else: <commands3>are zero!")
<commands3> executed. else:
print("The answer is: ", ans)

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

Escape sequence Effect


\t tab
\n new line
\\ displays \
\’ displays ‘
\” displays “

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

Rules for variable names


Must begin with a letter (upper or lower case) followed by zero or more other letters or
numbers.
Cannot have spaces in the name.
Can include “_”, e.g. My_variable.
Cannot use reserved Python command words.

Reserved Python command words


and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

Version 2 Page 7
Mathematical operator Operation
symbol
/ divide
* multiply
** exponential
+ add
- subtract
// integer division
% modulus (remainder after the division)

Operator Operator Sample condition Evaluates to


meaning
Equal to == “fred” == “sid” False
Not equal to != 8 != 8 False
Greater than > 10 > 2 True
Greater than or equal to >= 5 >= 5 True
Less than < 40 < 34 False
Less than or equal to <= 2 <= 109 True

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.

Keyboard short cut Explanation


Control c copy selected text
Control v paste
Control a select all
Control x cut selected text
Control f find
Control n open a new window
Control p print
Control s save
Control z undo

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.

turtle.goto() Turtle goes to x,y position. t = turtle.goto(200,-200)


turtle.setheading() Sets the direction the turtle t = setheading(180)
will move (in degrees)
0=north, 90 = east,
180=south, 270=west.
turtle.speed() Sets turtle speed (1 to 10). t = turtle.speed(10)
turtle.position() Reports current position as t.position()
x,y co-ordinates.
turtle.heading() Reports current heading. t.heading()
turtle.circle(radius) Draws a circle of a given t = turtle.circle(15)
radius.
turtle.stamp() Draws a picture of itself on t = turtle.stamp()
the canvas.
turtle.penup() Puts the pen up or down. t = turtle.penup()
turtle.pendown()
turtle.pensize(width) Changes pen size. t = turtle.pensize(5)
turtle.pencolor(colour) Changes pen colour. t = turtle.pencolor(“orange”)
turtle.hideturtle() Hides and shows turtle. t = turtle.hideturtle()
turtle.showturtle()
turtle.clear() Deletes all turtle drawings. t = turtle.clear()
turtle.reset() Deletes drawing, re-centres t = turtle.reset()
turtle and sets variables to
default values. (To reset
everything close Python and
start again.)

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.

Data type The classification of data as being a string, integer, float or


Boolean (logical).
Boolean Boolean or logical data that can only have one of two values, i.e.
True or False (1 = True and 0 = False).
Float A number with a fractional part, e.g. 34.67. Also known as a real
number.
Integer A whole number, e.g. 45.
String A sequence of characters that can include letters, spaces,
symbols, e.g. “This is a name £££46 “

Variable A named location in a computer’s memory where data is stored.


Global variable A variable assignment that is available throughout the whole
program.
Local variable A variable assignment that is only available within a subprogram.
Type declaration When a variable is allocated a particular data type (integer,
string, Boolean, float).
Variable declaration When a value is assigned to a variable.
Constant A variable assignment that stays the same throughout a program.
Data structure A group of related data items. Examples include strings, arrays
and lists.

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.

Subprogram A small computer program that runs within another computer


program. Subprograms are used to split up a program into a
number of smaller programs, with each subprogram performing a
specific function. Subprograms can be called in any order any
number of times.
Function A subprogram that returns a value.
Procedure A subprogram that does not return a value.
Return value The value returned by a subprogram.
Parameter The names that appear in a function definition when passing data
to a function.
Argument A piece of information/value that is required by a function to
perform a task, e.g. function(argument1, argument2)
Built-in subprograms Pre-existing libraries of subprograms that are built into the
programming language.
Library subprograms Pre-existing libraries of sub-programs that can be imported and
used in the programming language.

Mathematical operators Mathematical operators take two operands and perform a


calculation on them.
Examples of mathematical operators are: ‘+’ (addition), ‘-‘
(subtraction), ‘*’ (multiplication), ‘/’ (division).
Precedence The order in which values are calculated.
Integer division Division in which the remainder is discarded, e.g. 10//3 = 3.
Modulus The absolute (non-negative) value of a number. The modulus of -
3 is 3.

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

You might also like