Try running these in Mu or even interactively in the REPL. A good way to learn is to run a snippet then try modifying it - predict what will happen before running your changes.
Look at our tutorial sites or the official documentation for more details and examples!
Contents:
Programs always have to operate on data. The basic data types that we will use in this course are:
str
: Strings / text. String literals use single or double quotes. E.g., "this is a string", 'and so is this'.int
: integers / whole numbers. E.g., 1, -2, 42
float
: Real numbers. E.g., 3.14, 2.0, -2.345
bool
: Boolean, True
/False
valuesData is assigned to variables using the =
operator. E.g.,
number_of_sides = 5
weight = 56.7
Can find the type of any object in Python using type
. E.g.,
type(weight) # returns float
The basic 1D array-like data structure is the list
. E.g.,
chords = [1, 4, 5]
words = ["Bob", "the", "Builder"]
print("Hello")
name = input("What is your name? ")
print("Hi", name)
Convert inputted data from a str
to a number by wrapping in int
or float
:
dist_str = input("Distance in meters? ")
dist_m = float(dist_str) # convert to a Real number
dist_ft = dist_m * 3.28084
print("Distance in feet =", dist_ft)
All of the standard arithmetic including the Order of Operations (BODMAS/PEMA/etc) work on variables in Python. Addition, Subtraction, Multiplication, Division, Exponentiation become +
, -
, *
, /
, **
respectively.
(5 + 3) * 2**2 # evaluates as 8 * 4 = 32
5 + 3 * 2**2 # evaluates as 5 + 3*4 = 17
[12 / 6, 12 / 5] # evaluates to [2.0, 2.4]
Note that the division of two integers yields a real number (a float). Can get true integer division using the DIV operator //
and the associated MOD operator %
. You are expected to know these operators in the IGCSE. These give the quotient and remainder when used on positive numbers.
[19 // 7, 19 % 7] # evaluates to [2, 5] respectively
[3284 % 10, (3283 // 10) % 10, (3283 // 100) % 10] # yields [4, 8, 2]
Variables - allow their contents to vary, for example:
x = 5 # initialise x to the integer 5
x = x + 1 # x has now been incremented 6
x = "width" # now x is pointing to a string value
Note that variables in Python don't have to stay the same type. But it is often bad practice to change their type.
Comparisons
These create Booleans (True/False) that can be used to control branching (IF statements and loops) in code.
2 == 1+1
. To see if they're not equal: 1 != 2
.<
(Less Than), <=
(Less Than or Equal), e.g., 2 < 3
and 2 <= 2
are both True
statements.>
(Greater Than), >=
(Greater Than or Equal), There are lots more built-in functions in the math
module (docs.python.org/3/library/math.html).
Building strings and parsing (reading) strings is key to communicating with the user of a program or app.
"IG" + "CS" + "E" # becomes "IGCSE"
"$"*3 == "$$$" # is True
"Na "*16 + "Batman!"
text = "IGCSE"
# 01234 the five characters have indices 0 to 4
text[0] # is "I"
text[2] # is "C"
text[-2] # is "E"
text[2:4] # is "CS" - note that slices include the first index but not the last
text = "IGCSE"
text = text.lower() # variable now contains "igcse". Also have .upper() method
text = text.title() # variable now contains "Igcse"
" abc ".strip() # removes the leading and following white space characters
text.index("C") # returns 2, which is the index of "C" in text
.format
method, e.g.,"Hello {0}! 7*8 != {1}. {emot}".format(text, 42, emot = ":-)")
Python only has the IF conditional statement. IGCSE Pseudocode also uses the CASE construction for multiway selection. In Python, just use a elif sequence (or a dictionary lookup...)
Can use if
, or if
-else
or if
-elif
-...-elif
-else
structures, with any number of elif
s in between. Notes:
elif
is short for "else if". age = 13 # numbers from en.wikipedia.org/wiki/Education_in_Singapore
if age < 6:
print("Preschool or Kindergarten")
elif age <= 12:
print("Primary school")
elif age < 18:
print("Secondary school")
else:
print("No school?")
Condition Controlled Loops
Python (and Java) and IGCSE pseudocode has a pre-test loop called while
and WHILE - ENDWHILE respectively. These loops can run zero or more times.
number = 70
while number >= 11:
print(number)
number = number - 11
print("remainder after dividing by 11 is:", number)
Infinite loops and the post-test loop
IGCSE pseudocode includes a REPEAT-UNTIL (post-test) loop that doesn't exist in Python. However, the same logic can be obtained by using break inside an infinite loop. These loops run one or more times.
while True:
text = input("Enter an id or just press enter to exit: ")
if len(text.strip()) == 0:
break
Count controlled loops
When looping a known number of times a for loop (a FOR-NEXT loop in pseudocode) is used
# print the first 10 powers of 2. Note: range(10) ~= [0, 1, ..., 8, 9]
for index in range(10):
print(index, 2**index)
Extension: In Python, for loops are designed to loop over any iterable object (e.g., a string, a list, or a range). Compare the following for loops, which one is more readable?
text = "IGCSE"
for idx in range(len(text)):
print(text[idx]*5)
for char in text:
print(char*5)
In IGCSE pseudocode you need to know the concept of an Array. An array consists of a fixed number of elements of the same data type. E.g., [1, 4, 5, 6, 2]
or ['a', 'd', 'e']
or [1.1, 2.3, 3.5, 4.7]
. Elements are indexed from 0
to the len(array)-1
.
In Python, the structure that is most commonly used is a list
, which is sequence of data, but not necessarily of the same type and the list is allowed to change length. (Technically, it is a dynamic array of object references).
In pseudocode, stick to using arrays of a fixed length and type.
You can then initialise arrays to be "blank" such as
names = [""]*4 # ['', '', '', '']
marks = [0]*4 # [0, 0, 0 ,0]
remember in Python you don't need to declare variables before their use. So you can also just use an array literal containing what is in the array
names = ["bob", "elle", "eve", "ned"]
print(names) # ['bob', 'elle', 'eve', 'ned']
Indexing and reassigning elements
print(names[1]) # prints elle
names[0] = "adam" # ['adam', 'elle', 'eve', 'ned']
Appending, inserting, deleting and slicing elements from an array
Don't do this in IGCSE pseudocode!
names.append("zara") # ['adam', 'elle', 'eve', 'ned', 'zara']
names.remove("ned") # ['adam', 'elle', 'eve', 'zara']
names[1:3] # is ['elle', 'eve']
Methods and operators
You can test if an element is in a list using the in keyword
'bobby' in names # yields False
You can get the length of a list using the function len, e.g., len(names)
Some other useful list methods:
data.count(value) # counts the number of times value occurs in data
data.find(value) # finds the index of the first occurrence of value in data.
data.reverse()
and data.sort()
modify data to be reversed or sorted respectively.reversed(data)
and sorted(data)
that return new generators/lists respectively.Looping over a list (or any iterable)
Use a count controlled loop to iterate over a list, e.g.,
for idx in range(len(names)):
print(names[idx].title())
Or equivalently (when not writing IGCSE pseudocode), just loop over the list
for name in names:
print(name.title())
These are a really important part of programming clean, modular, readable and reusable code.
Functions (also called Procedures or Methods depending on context) allow you to define chunks of functionality that can be used and reused in other parts of your program. This makes the main line of your program more readable (provided you use sensible function names) and it saves doubling up on code.
The basic structure is:
help(function_name)
, and can generate the developer documentation for your program.def function_name(parameter1, parameter2, ...):
"Docstring explaining the function"
# Body of function
# That does all of the work
return value
Example
def square_cube(num):
"squares even numbers and cubes all other numbers"
if num % 2 == 0:
result = num**2
else:
result = num**3
return result
for count in range(1, 11):
print(square_cube(count))
These are like set generator notation in Mathematics, very handy for writing usable code in Python.
In maths, you can denote the set of square numbers ending in one by: {x² | x ∈ ℕ and x mod 10 = 1}. In Python the corresponding (truncated) list is [x**2 for x in range(100) if x % 10 == 1]
.
You can also use similar notation to generate tuples, sets, and dictionaries in Python.
This is really useful in real life programming, for example, to convert a string of numbers into a list of integers you could use a "classic" for loop
data_str = "23, 25, 20, 26, 16"
data_list = data.split(",")
nums = []
for idx in range(len(data_list)):
nums.append(int(data_list[idx]))
print(nums)
or you can use a comprehension
data_str = "23, 25, 20, 26, 16"
nums = [int(num) for num in data_str.split(",")]
print(nums)
you can even cleanly select (filter) for the values greater than 20
data_str = "23, 25, 20, 26, 16"
nums = [int(num) for num in data_str.split(",") if int(num) > 20]
print(nums)
Since Python 3, there have been type hints available in Python. These are not used by the interpreter, but can help IDEs and programmers in designing good code.
Type hints in Python are designed to be similar to function notation in Mathematics. For example, the function: f(x) = ∛(x²) maps reals to reals, which is denoted f: ℝ→ℝ.
In Python, you can write
def f(x: float) -> float:
return (x**2)**(1/3)
You can also hint the type of variables using a similar notation
year: int = 2019
For a comprehensive discussion, see https://realpython.com/python-type-checking/
The following algorithms are ones that it is expected you can recognise, explain and (pseudo)code