Try running these in your IDE 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 the tutorial sites linked on our main Python page or the official documentation for more details and examples!
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'.
A single letter or digit or symbol or space, etc... is known as a character (chr).
There is no character data type in Python - for good reasons - so just use strings of length 1.
int: integers / whole numbers. E.g., 1, -2, 42
float: Real numbers. E.g., 3.14, 2.0, -2.345
bool: Boolean, True/False values
Data 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 <class 'float'>
You should read <class 'float'> as "the variable weight is a member of the class 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:
num_people = int(input("How many people are coming to the event? "))
print("You will need", round((num_people + 2) / 4), "tables.")
or
dist_str = input("Distance in meters? ")
dist_m = float(dist_str) # convert string to an approximate 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 VCE. These give the quotient and remainder when used on positive numbers.
[19 // 7, 19 % 7] # evaluates to [2, 5] respectively
that is: "7 goes into 19: 2 times with 5 remainder".
This can be used to extract digits from numbers, e.g., to get the 1st & 3rd digits left of the decimal point
[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.
To compare two numbers numerically: 2 == 1+1. To see if they're not equal: 1 != 2.
To compare the order of two numbers use
< (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.
String "arithmetic":
Concatenation: "COMP" + "UT" + "ING" # becomes "COMPUTING"
Repetition: "$"*3 == "$$$" # is True
Both - guess the output: "Na "*16 + "Batman!"
String indexing and slicing - getting parts of a string
text = "COMPUTING"
# 012345678 the nine characters have indices 0 to 8
text[0] # is "C"
text[2] # is "O"
text[-2] # is "N"
text[2:4] # is "OM" - note that slices include the first index but not the last
String Methods. Uses the "dot" notation. In the following, let text = "FHS"
text = text.lower() # variable now contains "fhs". Also have .upper() method
text = text.title() # variable now contains "Fhs"
" abc ".strip() # removes the leading and following white space characters
text.index("H") # returns 1, which is the index of "H" in text
String Formatting: There are a few options, but most portable one is the .format method, e.g.,
"Hello {0}! 7*8 != {1}. {emot}".format(text, 42, emot = ":-)")
Formatted Strings: Variables and expressions can more easily be substituted into a string using f-strings. Try running the following
x = 5; pi = 3.14159; name = "Guido"
print(f"Hi {name}, the value of x is {x}, and 2π rounds to {2*pi:.2f}")
Strings can also be formatted using the .format method described above
Python only has the IF conditional statement. VCE 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 elifs in between. Notes:
elif is short for "else if".
Code after the colon needs to have a consistent indentation that defines the start and end of that block.
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 VCE pseudocode has a pre-test loop called while and WHILE - ENDWHILE respectively, see the pseudocode dictionary for details and comparisons. 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
VCE 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 equivalent FOR loops, which one is more readable?
text = "VCE"
for idx in range(len(text)):
print(text[idx]*5)
for char in text:
print(char*5)
In VCE pseudocode you need to know the concept of an Array. An array is a sequence that 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 usually 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 VCE pseudocode when working with Arrays!
names.append("zara") # ['adam', 'elle', 'eve', 'ned', 'zara']
names.remove("ned") # ['adam', 'elle', 'eve', 'zara']
names[1:3] # ['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 built-in 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.
Warning: the above methods do not return anything (they return None), rather the data is modified in place.
You can use reversed(data) and sorted(data) if you need to return 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 VCE pseudocode), just loop over the list
for name in names:
print(name.title())
Other data structures you need to know for the VCE include:
2D and multidimensional arrays
Queues and Stacks
Linked Lists
Associative arrays (dictionaries, hash tables)
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:
you define a function with some valid identifier (name).
The function can take 0 or more input parameters
Good practice is to use a docstring to describe what the function does
this gives users helpful info if they type help(function_name), and can generate the developer documentation for your program.
The function does some work and then optionally returns an output value
The function is then called (used) in subsequent code
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
Count
Sum and Average
Min/Max (Value and/or position)
Find (Linear Search)
Details are in the Control Structures, Pseudocode and Trace Tables page. TODO: Complete this page!