Edexcel GCSE Computer Science Python PLS

This document was made for the purpose of revision and helping other students with the Edexcel Application of Computational Thinking computer science examination.

This document follows the GCSE L1-L2 Computer Science 2020 Programming Language Subset (PLS) SAMs Issue 2 closely and provides examples and explanations with the help of w3 schools, GeeksforGeeks and PEP 8.

Comments

Anything on a line after the character # is considered a comment.

print("Hello, World!") #This is a comment
#This is also a comment
print(1+5)

A comment does not have to be text that explains the code, it can also be used to prevent Python from executing code.

#print("Hello, World!")
print("Cheers, Mate!")

Identifiers

Identifiers are names given to variables, classes and functions to help differentiate one from the other. Identifiers cannot be keywords

Function and Variables

Function and variable names should be lowercase, with words separated by underscores where necessary to improve readability.

# Variable names
player_name = input()
number1 = 5

# Function names
process_file(example.csv)
print_hello_to_screen()

Constants

Constants should be written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.

Classes

Class names should normally use the CapWords convention. Such as MyClass or CameraData.

Keywords

Python has 33 reserved keywords that cannot be used as a variable name, function name or any other identifier. All keywords except True, False, and None are in lowercase.

The global keyword defines a global variable that can be used outside of the current scope.

def get_user_name():
    global username = input()


get_user_name()
print(username)

Data Types

These are the data types you need to know, sorted by category:

Category Data Type Keyword
Text Type: str
Numeric Types: intfloat
Sequence Types: listrange
Boolean Type: bool

In Python, the data type is set when you assign a value to a variable:

x = "Hello World"                  #str
x = 20                             #int
x = 20.5                           #float
x = ["apple", "banana", "cherry"]  #list
x = range(6)                       #range
x = True                           #bool

To set the explicitly set the data type, or to convert a variable to another data type, the following functions may be used:

x = str("235") #str
y = int(x)     #int
z = float(y)   #float

Operators

This section contains all the operators you need to know

Arithmetic

Arithmetic Operator Meaning Example Standard Maths Returns
/ division 7 / 2 $7\div2$ 3.5
* multiplication 4 * 7 $4\times7$ 28
** exponentiation 4 ** 2 $4^2$ 16
+ addition 12 + 4 $12+4$ 16
- subtraction 12 - 4 $12-4$ 8
// integer division 7 // 2 $\lfloor{7/2}\rfloor$ 3
% modulus 5 % 3 $5\bmod3$ 2

Relational

Logical Operator Meaning Example Standard Maths Returns
== equal to 5 == 5 $5 =5 $ True
!= not equal to 5 != 4 $5\ne4$ True
> greater than 5 > 3 $7>3$ True
>= greater than or equal to 4 >= 4 $4\ge4$ True
< less than 3 < 4 $3<4$ True
<= less than or equal to 4 <= 4 $4\le4$ True

Logical / Boolean

Operator Standard Maths Meaning
and $\land$ both sides of the test must be true to return true
or $\lor$ either side of the test must be true to return true
not $\lnot$ inverts

Selection

The keyword if can be used to create sections of code that are only executed if the expression given is true.

a = 33
b = 200
if b > a:
  print("b is greater than a")

The keyword else can be added to create a section of code that will run if the given expression is not true. The keyword elif can be added to create a section of code that will run if the selected expression is true and the previous expressions were false.

a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

Repetition

The while keyword can be used to create a block of code that will loop until the given condition returns False.

# Print i as long as i is less than 6:
i = 1
while i < 6:
  print(i)
  i += 1

The break statement can stop the loop even if the condition is true.

i = 1
while i < 6:
  print(i)
  if i == 3:
    break # Exit the loop when i is 3:
  i += 1

The else statement can create a block of code that will run when the condition is no longer true.

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

Iteration

The for loop is used for iterating over a sequence.

# Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

To loop through a set of code a specified number of times, we can use the range() function, which returns a sequence of numbers starting from 0 and incrementing by 1.

# print numbers from 0 to 5
for x in range(6):
  print(x)

The range() function also accepts up to three parameters: range(<start>,<stop>,<step>)

# print numbers between 2 and 30, incrememnting in steps of 3
for x in range(2, 30, 3):
  print(x)

Subprograms

Subprograms can be defined using the def keyword. This creates a block of code that can be executed whenever the function is called by its identifier or name.

# a procedure that prints some text
def my_function():
  print("Hello from a function")


my_function() # running the procedure

Subprograms can also accept parameters, which are variables that can change the behaviour of a procedure based on the arguments given.

def say_hello(name):
    print("Hello " + name)


say_hello("Alex") # calls the procedure thereby printing "Hello Alex"

Subprograms that return a value are called functions, the return keyword can be used to return a value, which will simply put the returned value in the place of where the function was called.

def times_five(x):
  return 5 * x

print(times_five(3)) # prints 15
print(times_five(5)) # prints 25

Inputs and Outputs

Screen and Keyboard

The print() function displays an item in the console. The input() function displays a prompt on the screen and returns the line typed in.

num = input(Enter a number: ')
print("The number you entered was: " + num)

Files

The open() function returns a file and accepts two arguments, the filename, and the method of opening.

Method Function
"r" Read - Default value. Opens a file for reading, error if the file does not exist
"a" Append - Opens a file for appending, creates the file if it does not exist
"w" Write - Opens a file for writing, creates the file if it does not exist
"x" Create - Creates the specified file, returns an error if the file exists

The <fileid>.close() method removes the file from memory.

Reading files

f = open("demofile.txt", "r") # opens file for reading
print(f.read()) # prints contents of file
f.close() # removes file from memory

The <fileid>.readline() method reads a file line by line, reading the next line each time it is called. By looping through this, you can read a whole file, line by line.

f = open("demofile.txt", "r")
for x in f:
  print(x)

f.close()

Writing and Creating files

Appending text to a file will add text to the end of the file.

f = open("demofile2.txt", "a") # opens file for appending
f.write("Now the file has more content!") # appends text to file
f.close()

Writing files will overwrite existing content.

f = open("demofile3.txt", "w") # opens file for writing
f.write("Woops! I have deleted the content!") # overwrites exisitng content
f.close()

Creating a new file is simple

f = open("myfile.txt", "x") # opens a newly created file "myfile.txt"

Existing Subprograms

The pair of <> symbols indicate where expressions or values need to be supplied.

Built-in

The chr(<integer>) function returns the Unicode character represented by <integer>.

x = chr(97) # returns the character that represents the unicode 97, "a"
print(x) # prints "a"

The ord (<char>) function returns the integer that represents the Unicode character <char>. It is the opposite of chr()

x = ord("a") # returns the integer that represents the character "a", 97
print(x) # prints 97

The len(<object>) function returns the length of <object>.

mylist = ["apple", "banana", "cherry"] # creates a  list with 3 items
x = len(mylist) # returns 3 and places it in x

The round (<x>, <n>) function rounds <x> to the number of <n> digits after the decimal (uses the 0.5 rule).

x = round(5.76543, 2) # rounds 5.76543 to 2 decimal places, 5.77
print(x) # prints 5.77

Lists

The <list>.append (<item>) function adds <item> to the end of <list>.

fruits = ['apple', 'banana', 'cherry'] # creates list with strings
fruits.append("orange") # adds "orange" to the end of the list

The del <list>[<index>] function removes the item at <index> from <list>.

x = ["apple", "banana", "cherry"] 
del x[0] # deletes "apple" from list x

Strings

The <string>.find (<substring>) function returns the location of <substring> in <string> and returns -1 if nothing is found.

txt = "Hello, welcome to my world."
x = txt.find("welcome") # looks for "welcome" in the txt string and returns its location
print(x) # which is 7, starting from 0

The <string>.isalpha () function returns True or False if all the characters in the string are alphabetic, A-Z.

txt = "CompanyX"
x = txt.isalpha() # checks if all the characters are alphabetic
print(x) # returns true

The <string>.isalnum () function returns True or False if all the characters in the string are alphabetic, A-Z or numeric 1-9.

txt = "Company12"
x = txt.isalnum() # checks if all the characters are alphabetic or numeric
print(x) # returns true

The <string>.isdigit () function returns True or False if all the characters in the string are numeric, 1-9.

txt = "50800"
x = txt.isdigit() # checks if all the characters are numeric
print(x) # returns true

The <string>.replace (<s1>, <s2>) replaces all occurances of <s1> with <s2>.

txt = "I like bananas"
x = txt.replace("bananas", "apples") # replaces "bananas" with "apples"
print(x) # prints "I like apples"

The <string>.split (<char>) function returns a list of strings that have been seperated based on <char>.

txt = "apple#banana#cherry#orange"
x = txt.split("#") # returns a list of strings split by #
print(x) prints the list: ["apple","banana","cherry","orange"]

The <string>.strip (<char>) function returns a string with all occurances of <char> removed from <string>.

txt = ",,,,,rrttgg.....banana....rrr"
x = txt.strip(",.grt") # removes all instances of ",",".","g","r", and "t" from the string
print(x) # prints "banana"

The <string>.upper () function returns <string> in uppercase.

txt = "Hello my friends"
x = txt.upper() #returns "HELLO MY FRIENDS"
print(x) 

The <string>.lower () function returns <string> in lowercase.

txt = "Hello my FRIENDS"
x = txt.lower() #returns "hello my friends"
print(x)

The <string>.isupper () function returns True or False depending on if <string> is all in uppercase.

txt = "THIS IS NOW!"
x = txt.isupper() #returns True
print(x)

The <string>.islower () function returns True or False depending on if <string> is in lowercase.

txt = "THIS IS now!"
x = txt.isupper() #returns False
print(x)

Formatting Strings

String output can be altered in varying ways to suit the problem requirement and user’s needs.

Placeholders

Placeholders can be defined using named indexes {price}, numbered indexes {0} or with empty placeholders {}.

#named indexes:
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)

#All return "My name is John, I'm 36"

The * operator can be used to generate a line of repeated strings or characters.

print("1="*10)
# will print "=========="

Joining or concatenating strings can be done with the + operator.

message = "My name is "
name = "Alex"
print(message + name)
# prints "My name is Alex"

Strings can be sliced with [a:b] with a and b being integers that are positions within a string.

print("Hello, World"[2:5])
# prints "llo"

Library modules

This section contains all the library modules that are required, these are all built-in modules.

To import a library module, use import <library> at the start of your code.

import random # imports the random module

Random module

Use randint(a,b) to return a random integer between a and b (inclusive).

import random
print(random.randint(3, 9)) # prints a random number between 3 and 9 inclusive

Use random.random() to return a random float in the range of 0.0 and 1.0.

import random
print(random.random()) # prints a random float between 0.0 and 1.0

Math module

Use import math at the start of your program to import the math module.

Method Math notation What does it do? Example Output
math.ceil(x) $\lceil x\rceil$ Rounds a number upwards to its nearest integer math.ceil(1.4) $2$
math.floor(y) $\lfloor y\rfloor$ Rounds a number downwards to its nearest integer math.floor(22.6) $22$
math.sqrt(z) $\sqrt{z}$ Square roots a number math.sqrt(16) $4.0$
math.pi $\pi$ Returns pi math.pi $3.14\ldots$

Time module

The only method that is required for the examination is the time.sleep(<sec>) method, which suspends the program for <sec> seconds, then resumes on the next line of the program.

import time

print("Printed immediately.") # prints when the program is run
time.sleep(2.4)
print("Printed after 2.4 seconds.") # prints 2.4 seconds after

Turtle graphics

Getting started

When the turtle is created, it is initially pointing to the right (east).

The turtle window and turtle canvas can be different sizes. The canvas is the space where the turtle can draw, whereas the window is the size of the operating system window.

To create a custom window size, turtle.Screen() is used, in this example, it has been set to screen.

import turtle
screen = turtle.Screen()
screen.setup(800,400) # sets the window size to 800 x 400 pixels

To create a custom canvas size, turtle.screensize is used.

import turtle
turtle.screensize(800,400) # sets the canvas to 800 x 400 pixels

Creation and movement

To create a new turtle, use turtle.Turtle().

import turtle
turtle1 = turtle.Turtle() # creates a new turtle

To move the turtle forwards and backwards in the direction it is facing, use turtle.forward(<setps>) and turtle.back(<setps>), with <steps> being the amount moved.

import turtle
turtle.forward(100) # moves the turtle 100 steps forward
turtle.back(200) # moves the turtle 100 steps backwards

turtle.left(<degrees>) and turlte.right(<degrees>) turn the turtle left or right by <degrees> degrees.

press the ▶ icon above to run the code!

To hide or show the turtle, turtle.hideturtle() and turlte.showturtle() can be used

import turtle
turtle.hideturtle() # hides turtle on running the program

To speed up or slow down the turtle, turtle.speed(<value>) can be used, with <value> being the speed.

press the ▶ icon above to run the code!

Positioning and direction

This section is not completed!