Info1110 Notes Lecture Notes 13 Weeks PDF
Info1110 Notes Lecture Notes 13 Weeks PDF
Contents
INFO1110 Introduction to Programming 1
Week 01 5
Course outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Introduction to computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Using the terminal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Text editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
The print function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Variables and Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Shorthand assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Equality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Boolean operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Truth table for and . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Truth table for or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Week 02 9
Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
More operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Comparison operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Naming variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Desk checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Week 03 10
Conditional flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
if keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
elif keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
else keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Ternary operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
while loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Control flow diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Week 04 14
Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Iterating through a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Modifying a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Filtering elements in a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Week 05 17
The type function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Why use functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Ending a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
The difference between print and return . . . . . . . . . . . . . . . . . . 19
Best practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
General rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Docstrings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Week 06 20
Streams and files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Input and output streams . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
File types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
File paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
File modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Opening files in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Reading from a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Writing to a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Using with to automatically close a file . . . . . . . . . . . . . . . . . . . . 24
Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Difference between TypeError and ValueError . . . . . . . . . . . . . . . 24
Using try and except . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Using finally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Handling multiple exceptions . . . . . . . . . . . . . . . . . . . . . . . . . 26
Week 07 27
Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Types of tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
What to test? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Important keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Writing assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Writing in/out tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Comparing floating point numbers . . . . . . . . . . . . . . . . . . . . . . . . . 29
Week 08 30
List idioms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Reading input until a sentinal value . . . . . . . . . . . . . . . . . . . . . 30
Finding a specific value in a list . . . . . . . . . . . . . . . . . . . . . . . . 30
Counting the number of occurences in a list . . . . . . . . . . . . . . . . . 31
Finding the max/min value in a list . . . . . . . . . . . . . . . . . . . . . 31
Filtering a list in-place . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Filtering a list, without mutation . . . . . . . . . . . . . . . . . . . . . . . 33
Week 09 34
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Instance vs class attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Instance vs class methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Week 10 36
Test methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Test-driven development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Week 11 37
Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Why use recursion? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Why shouldn’t we use recursion? . . . . . . . . . . . . . . . . . . . . . . . 37
Recap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Writing a recursive function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Cumulative sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Factorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Week 12 40
Lists redux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Iterating through a 2D list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Arrays vs lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Why use arrays? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
The numpy package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Importing numpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Creating an array in numpy . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Iterating through a 2D numpy array . . . . . . . . . . . . . . . . . . . . . . 43
Week 13 44
Revision questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
General programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Classes and objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
The following notes and examples are written to target Python version 3.4 and above.
Code blocks beginning with %%bash contain bash commands which can be run in the
terminal.
3
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
which you can learn and grow. Chances are that when you make a mistake, it’s
more likely you’ll remember it and then never make the same mistake again.
2. Ask for help when you need it
The staff are there to help you. If you don’t quite understand a concept, don’t
just ignore it. Ask for help! It’s better to be constantly asking for help rather
than letting it pile up and realising before the final that you don’t understand
anything at all. If you’re afraid of asking in person, you can use Ed, or research
online. There are plenty of resources out there: Stackoverflow, YouTube, online
tutorials, etc.
3. Nail the fundamentals
All the concepts build upon each other. Make sure you have a solid grasp of the
fundamentals. Remember that this is an introduction to programming, so you
want to be building a good understanding of the concepts. A good base means
that you are able to learn harder concepts and different languages faster.
4. Keep up to date (this includes lecture content and tutorial work)
The workload builds up, so it’s important to keep up to date. It’s understandable
that uni gets busy, but try at least to be up to date with the previous week’s work
before the next week starts. This way you aren’t cramming right before a quiz or
an exam.
5. Go to the tutorials
The tutorials are a great place for learning and getting help if you need it. Im-
portant concepts are often reviewed and emphasised. There’s also a weekly task
that counts towards your attendance/overall grade. They’re easy marks that
you shouldn’t waste - especially if you don’t feel confident about the final.
6. Do the best that you can throughout the semester and before the finals
A 60% weighted final is a lot of pressure on just one paper, so make sure your
cumulative mark up until that point is the best that it can be. It places a lot less
pressure on you and gives you that extra bit of confidence. Plus, doing well
during the semester is a good indicator that you know your content, so that’s
always good.
7. Practise! Practise! Practise!
If this final point is the only thing you take away from all these tips, I’d be happy.
Remember that coding is something that requires time, work and practise. If
you’re a beginner programmer and you want to do well, you have to put in the
effort. If you’re struggling to understand a particular concept, do more problems
on that topic. You aren’t just limited to tutorial problems, there are so many sites
online. If you want somewhere to get started, I recommend checking out
• CodingBat, https://codingbat.com/python
• HackerRank, https://www.hackerrank.com/domains/python
• ProjectEuler, https://projecteuler.net/archives
4
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Week 01
Course outline
Introduction to computers
A program is a set of instructions that a computer can understand, and then execute.
A compiler will translate a source code into machine code.
• Write source code – code which a human can read
• Compile the code to executable code – code which a computer can read
• The computer then runs the executable code
You can tell Python to compile and run your program with the python3 command in
the terminal.
To check which version on Python you are running, enter the following command in
the terminal.
python3 --version
Instead of navigating the folders (directories) on your computer using File Explorer
on Windows or Finder on MacOS, you can navigate your computer using commands
in the terminal. Here are the important ones to know.
Action Command
To show your current folder pwd
To list files in the current folder ls
To make a new folder mkdir [DIRECTORY_NAME]
To move into a folder cd [DIRECTORY_NAME]
To go back to your home folder cd ~
5
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Text editors
The print function can be used to print things to the terminal. You need to invoke the
print function with parentheses () and pass inside the parenthesis what you want it
to print.
print("Hello, world!")
print(42)
Hello, world!
42
Everything on your computer is stored as zeros and ones (binary), each zero or one is
known as a bit. 8 bits make 1 byte.
A variable is memory space, reserved by a name (identifier). There are two types of
variables:
1. Primitive: these use a fixed amount of memory
2. Object: memory used for objects can changed over time
Note: In python, everything is an object. Objects are covered in more detail
in week 6.
When working with variables:
1. DECLARE a variable
2. INITIALISE the variable
3. USE the variable
By declaring variables, You can now refer to the reserved memory space by its name.
Give your variable a value by initializing it. If not initialized, the memory space will
be filled by a default value (which differs between machines).
Variables in python are function scoped. A variable declared within a func-
tion can only be used inside that function.
Expressions are a combination of variables and other items which can be evaluated,
and will produce a value. We construct expressions using operators
6
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Operators
10
2
24
1.5
We also have
• % modulo/modulus
• // floor divide
print(6 % 4)
print(6 // 4)
2
1
Assignment
= is the assignment operator. Values on the LEFT are assigned values on the RIGHT.
x = 10
print(x)
10
In the code above, the value 10 is being assigned to the variable x. The variable x is
then evaluated before it is passed into the print function.
Shorthand assignment
x += n # is equivalent to x = x + n
x -= n # is equivalent to x = x - n
x *= n # is equivalent to x = x * n
x /= n # is equivalent to n = x / n
x = 10
x += 2
7
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
print(x)
x = 10
x -= 2
print(x)
x = 10
x *= 2
print(x)
x = 10
x /= 2
print(x)
12
8
20
5.0
Equality
== is the equality operator. It compares the value on the LEFT to the value on the right.
print(10 == 5 + 5)
print(10 == 1 + 5)
True
False
Boolean operators
8
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
True
False
False
False
or True False
True True True
False True False
print(True or True)
print(True or False)
print(False or True)
print(False or False)
True
True
True
False
Week 02
Data types
More operators
Comparison operators
9
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
print(4 > 5)
print(4 < 5)
print(4 <= 5)
print(4 == 5)
print(5 > 5)
print(5 != 6)
False
True
True
False
False
True
Naming variables
Desk checks
A ‘desk check’ is a pen and paper test. It reveals discrepancies between actual and
expected results.
We generally format our desk checks as a table.
• Create a column for each variable
• Create a new row for each change
Week 03
Conditional flow
if keyword
10
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
if <condition>:
<if block>
If the condition is true, then the if block (the indented lines of code) is run.
weather = "sunny"
temperature = 30
print("End of program")
weather = "sunny"
temperature = 15
print("End of program")
End of program
elif keyword
We can add additional conditions using elif (else if). elif conditions are only
checked if all previous if and elif conditions are false.
weather = "sunny"
temperature = 20
print("End of program")
weather = "sunny"
temperature = 30
11
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
print("End of program")
else keyword
We can add an else block as a catch-all condition. Note: else does not need a boolean
condition. The else block will only run if all previous if and elif conditions are false.
weather = "rainy"
temperature = 22
print("End of program")
Ternary operator
weather = "rainy"
False
while loops
12
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
while <condition>:
<while block>
When writing while loops for counting, keep 3 things in mind.
1. Initialise a counter variable
2. Update the counter variable
3. Ensure there is a stopping condition
0
1
2
3
4
You can force exit a loop by using break You can force a reiteration (go back to start)
with continue
How to end a loop?
• Ask before iterating: Ask the user if it is time to end the loop
– A user can end a loop by entering a sentinel value
– For example, Enter all test scores followed by negative number
• Using break and continue keywords
– Using break and continue can add complexity and should be avoided, if
possible
A flowchart can be used to easily convey the control flow and execution paths of a
program.
• Boxes represent code statements
• Diamonds represent conditions, i.e. decision points
– If a diamond does not have an arrow going back to it, it’s an if statement
– If a diamond has an arrow going back to it, it’s a while loop
• Direction of the execution paths are represented by arrows
Here is an if and if-else flowchat.
13
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
i = 2
while i < 10:
i = i - 1
i = i * 5
Week 04
Lists
14
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
my_list = [5, 3, 8, 6]
print(len(my_list))
4
A list can be indexed using square brackets [].
Note: The first element in the list is at index zero.
list elements 5 3 8 6
index 0 1 2 3
print(my_list[0])
print(my_list[1])
print(my_list[2])
5
3
8
What happens when we choose an index that doesn’t exist?
print(my_list[4])
Recall, we can use a while loop to count. Why not count the indices of the list – from
0 up to one less than the length of the list.
i = 0
while i < len(my_list):
print(i)
i = i + 1
0
1
2
3
Rather than printing out the index, let’s use it to index the list and print out the element
at that index.
i = 0
while i < len(my_list):
elem = my_list[i]
print(elem)
15
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
i = i + 1
5
3
8
6
Modifying a list
pets.append("axolotl")
print(pets)
pets.pop(1)
print(pets)
i = 0
while i < len(numbers):
number = numbers[i]
if number % 2 == 0:
even_numbers.append(number)
i = i + 1
print(even_numbers)
i = 0
while i < len(things):
16
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
thing = things[i]
if thing.startswith("d"):
things_starting_with_d.append(thing)
i = i + 1
print(things_starting_with_d)
Week 05
The type function can be used to find the data type of an object.
print(type("Hello World"))
print(type(100))
print(type(3.1415))
print(type([1, 2, "hello", 3]))
<class 'str'>
<class 'int'>
<class 'float'>
<class 'list'>
<class 'str'>
This becomes particularly useful later on with type checking.
Functions
A function is a series of instructions that will (sometimes, but not always) take input,
and produce output. This is similar to mathematics functions, e.g. f ( x ) = sin( x ) is a
function called f which takes an input x and returns an output sin( x ).
import math
def f(x):
return math.sin(x)
17
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Examples
result = add(1, 4)
print(result)
def is_even(n):
if n % 2 == 0:
return True
return False
print(is_even(4))
print(is_even(5))
print(is_even(6))
True
False
True
print(is_even(4))
print(is_even(5))
print(is_even(6))
True
False
True
Ending a function
18
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
def print_hello(name):
print("Hello, {}".format(name))
def get_hello_string(name):
return "Hello, {}".format(name)
Best practice
General rules
Here are some general things to keep in mind when writing functions
• A function should do one thing, and one thing well
• Avoid long functions (over 50 lines)
– If your function is getting too long, break it up into smaller units
• Place returns statements near the end of your methods
• Avoid using global variables inside your function
Docstrings
Docstrings (documentation strings) are used as a comment to describe what your func-
tion does.
Include in your docstrings:
• What does the function do?
– What inputs does it expect?
– What output does it return?
• What assumptions does the function make?
• Does the function mutate the input parameters?
19
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
def my_function():
"""This is a docstring."""
pass
def next_hailstone_number(n):
"""
Returns the hailstone number following the number `n`.
This function assumes `n` is an integer. If `n` is not an␣
֒→integer,
Week 06
File types
File paths
Files are stored in your file system and can be referenced by a path.
A file path can be written in two ways:
20
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
File modes
When you open a file for reading (read mode), the program assumes the file exists and
you have permission to read from the file.
When you open a file for writing (write mode), you always begin with an empty file.
• If file already exists, program will override
• If file does not exist, program will create it
To add to the end of an existing file, you will want to append (append mode).
The following code writes the string contents to a file called sample.txt. After running
the below command in your terminal, you should be able to see a new file with the ls
command.
%%bash
cat << EOF > sample.txt
Apple
Banana
Carrot
EOF
f = open("sample.txt", "r")
print(f)
f.close()
21
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
f = open("sample.txt", "r")
print(f.readline())
print(f.readline())
print(f.readline())
f.close()
Apple
Banana
Carrot
f = open("sample.txt", "r")
print(f.readlines())
f.close()
f = open("sample.txt", "r")
lines = f.readlines()
f.close()
i = 0
while i < len(lines):
line = lines[i]
print(line.strip())
i = i + 1
Apple
Banana
Carrot
What happens when you call readline when there are no more lines to be read? What
happens when you call readline more than once?
f = open("sample.txt", "r")
print(f.readline()) # 'Apple\n'
print(f.readline()) # 'Banana\n'
print(f.readline()) # 'Carrot\n'
print(f.readline()) # ''
print(f.readline()) # ''
f.close()
22
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Apple
Banana
Carrot
f = open("sample.txt", "r")
print(f.readlines())
print(f.readlines())
f.close()
Writing to a file
Opening a file for writing is just like opening a file for reading – except you give it "w"
for write mode.
Be careful. If the filepath already exists, it will overwrite the existing file!
f = open("sample.txt", "w")
f.write("Axetol")
f.write("Bandicoot")
f.write("Cheetah")
f.close()
f = open("sample.txt", "r")
print(f.readlines())
f.close()
['AxetolBandicootCheetah']
Unlike the print function, the write function does not automatically add a newline
\n to the end.
f = open("sample.txt", "w")
f.write("Axetol\n")
f.write("Bandicoot\n")
f.write("Cheetah\n")
f.close()
f = open("sample.txt", "r")
print(f.readlines())
f.close()
23
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Python supports context managers using the with keyword. By opening a file with the
with keyword, Python will know to close the file after you leave the with block.
Axetol
-----------------------------------------------
ValueError Traceback (most recent call last)
2 print(f.readline())
3
----> 4 print(f.readline()) # The file will be closed outside the with block
Exceptions
What is the difference between TypeError and ValueError? Consider the following.
A TypeError happens when you give a function the wrong type.
24
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
----------------------------------------------
TypeError Traceback (most recent call last)
----> 1 value = int([2, 3])
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list
A ValueError happens when you give the function the right type, but the contents of
the type is incorrect.
-----------------------------------------------
ValueError Traceback (most recent call last)
----> 1 value = int('42b')
The following code opens a file that does not exist. A FileNotFoundError is raised.
f = open("non-existant-file.txt", "r")
------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
----> 1 f = open("non-existant-file.txt", "r")
try:
f = open("non-existant-file.txt", "r")
except FileNotFoundError:
print("The file could not be found.")
def starts_with_a(word):
"""
Returns true if `word` starts with the letter 'a'.
If `word` is not a string, an AttributeError is raised.
"""
25
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
return word.startswith('a')
try:
print(starts_with_a('alphabet'))
print(starts_with_a(34))
except AttributeError:
print("Something went wrong.")
True
Something went wrong.
Using finally
The finally block is executed regardless whether an exception was thrown or not.
You may find it useful when making sure that a file is closed, even if an exception
occurs.
# Read a file and attempt to convert each line to a float
try:
f = open("sample.txt", "r")
lines = f.readlines()
i = 0
while i < len(lines):
line = lines[0].strip()
print(float(line))
except ValueError:
print("'{}' could not be converted to float.".format(line))
finally:
f.close()
You can catch different exceptions by adding multiple except blocks after the try
block.
try:
<try block>
except <exception type>:
<except block>
except <exception type>:
<except block>
finally:
<finally block>
However, only one except block will execute per try block. It is best practice to catch
more specific exceptions first.
26
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
try:
pass
except FileNotFoundError:
pass
except OSError:
pass
except Exception: # catch all exceptions
pass
Week 07
Testing
Types of tests
27
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
– Checks that you haven’t broken something that used to work (might possi-
bly have been previously implemented incorrectly)
– Can be automated, allows repeating
– Make a test class, test program, test driver
What to test?
Important keywords
Writing assertions
An assertion is a boolean expression written at some point in the program. We use the
assert keyword to assert that the condition is true.
assert 2 + 2 == 4
If the expectation of what the programmer knows should be true at this point does not
match the actual state of the program, execution is stopped.
assert 2 + 2 == 5
---------------------------------------------------
AssertionError Traceback (most recent call last)
----> 1 assert 2 + 2 == 5
AssertionError:
28
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Exercise: Write input-output tests for a program that counts the number of vowels in
a string, outputting the total number of vowels, the most popular vowel, and a count
of the number of times this particular vowel appears.
We can write the .in and .out files depending on what we expect the output to be
for any particular input. This is an example of what the input/output files could look
like:
# test_1.in
this is a test string
# test_1.out
Total vowels: 5, The letter "i": 3
To test the difference between the expected output (your .out file) and the actual out-
put of your program when given a particular input (the .in file), we use the diff
command. We use the command line as below:
%%bash
python3 program.py < test_1.in | diff - test_1.out
Do NOT use equality to compare floating point numbers. Floating point numbers are
not precise.
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
0.30000000000000004
False
So how do I compare floating point numbers?
We can assume two numbers are equal if their difference is close to zero.
difference = abs(a - b)
return difference < error
False
True
True
29
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Week 08
List idioms
Example: Read in user input and echo back the input, until the user types in ‘stop’.
Example: Find the index and value of the first negative number in a list of numbers.
first_neg_index = None
first_neg_value = None
i = 0
while i < len(numbers):
number = numbers[i]
if number < 0:
first_neg_index = i
first_neg_value = number
break
i = i + 1
print(first_neg_index)
print(first_neg_value)
3
-8
Example: Find the index and value of the last negative number in a list of numbers.
We can do this by
• iterating backwards through the list, or
• taking out the break statement so the search continues
30
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
last_neg_index = None
last_neg_value = None
i = 0
while i < len(numbers):
number = numbers[i]
if number < 0:
last_neg_index = i
last_neg_value = number
i = i + 1
print(last_neg_index)
print(last_neg_value)
4
-2
count = 0
i = 0
while i < len(words):
word = words[i]
if len(word) == 4:
count = count + 1
i = i + 1
print(count)
largest = None
31
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
i = 0
while i < len(numbers):
number = numbers[i]
if largest is None:
largest = number
if number > largest:
largest = number
i = i + 1
print(largest)
12
Example: Find the longest word in the list.
longest_word = None
i = 0
while i < len(words):
word = words[i]
if longest_word is None:
longest_word = word
if len(word) > len(longest_word):
longest_word = word
i = i + 1
print(longest_word)
intensify
Here’s a common mistake students make.
Exercise: Find the largest number in the list.
largest = 0
i = 0
while i < len(numbers):
number = numbers[i]
if number > largest:
largest = number
i = i + 1
32
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
You can filter a list by removing elements you do not want to keep.
Example: Given a list of numbers, filter the list to keep only the even numbers.
i = 0
while i < len(numbers):
number = numbers[i]
if number % 2 != 0:
numbers.pop(i)
continue # Removing an element will shift the list down
i = i + 1
print(numbers)
i = len(numbers) - 1
while i >= 0:
number = numbers[i]
if number % 2 != 0:
numbers.pop(i)
i = i - 1
print(numbers)
Alternatively, you can filter a list by creating a new list and adding elements which
you want to keep.
This is generally the better (and easier) approach.
Example: Given a list of numbers, filter the list to keep only the even numbers.
i = 0
while i < len(numbers):
number = numbers[i]
if number % 2 == 0:
even_numbers.append(number)
33
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
i = i + 1
print(even_numbers)
Week 09
Classes
We can think of classes as a template for all the variables and methods of a particular
kind of object.
Consider books as an example.
• All books have certain properties, or attributes
– For example: title, author, year of publication, etc.
• If we define a template for the creation of such objects, we can easily keep track
of all the data relating to that one specific item.
– This also allows us to make multiple different instances of that class,
i.e. making and storing data for lots of different books.
Constructors
class Book:
def __init__(self, title, author, year):
self.title = title
self.author = author
self.year = year
# We can access instance variables using the dot operator followed by␣
֒→the name of the attribute needed
print(b1.title)
print(b1.author)
print(b1.year)
34
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
print(b2.title)
print(b2.author)
print(b2.year)
To Kill A Mockingbird
Harper Lee
1960
Great Expectations
Charles Dickens
1843
Instance methods:
• Must have self when declaring the method’s definition
• Needs specific instance of an object for invocation
Class methods:
• Can be invoked using class name
– Does not need object for invocation
• Cannot reference an instance variable
• Cannot invoke instance methods of the class
– Unless it has an object and uses this object in invocation
– i.e. cannot use things with implicit or explicit self as its calling object
class Circle:
pi = 3.141592 # a class attribute
# An instance method
def calculate_area(self):
return Circle.pi * (self.radius ** 2)
35
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
return Circle.pi
3.141592
12.566368
Both instance methods and class methods can take in additional parameters within
their definitions.
Week 10
Test methodology
With testing of any program, there are three basic steps you need to follow:
1. Design a set of tests
• Think about the different equivalence classes
• Think about the different execution paths (white-box only)
2. Write the corresponding tests
• .in and .out files for input/output testing
• assert for testing in Python
3. Run the program against each of your testcases.
• If the tests pick up an error, go and fix it, then run again
Test-driven development
Test-driven development (TDD) is about writing tests before you begin implementing
your program.
Why?
• Tests are written to the specification, rather than the implementation
• Can help you make API design decisions
– What are the inputs and outputs of the function?
– What methods should the class have?
• Helps you define and/or understand the behaviour of the code before you go to
implement it
36
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Debugging
%%bash
Week 11
Recursion
If an problem can be solved by first solving a smaller version of that problems, it’s
likely you can use recursion.
• Some problems are inherently recursive
• Sometimes makes code easier to understand
Sometimes, an iterative solution is better. Here are some reasons to avoid recursion.
• Recursion is slower than iteration
37
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Recap
Cumulative sum
Exercise: Write a recursive function that returns the cumulative sum from 0 up until a
specified number. If the specified number is negative, return 0.
# Using recursion
def cumulative_sum(n):
if n <= 0:
return 0
else:
return n + cumulative_sum(n-1)
print(cumulative_sum(0))
print(cumulative_sum(3))
print(cumulative_sum(10))
0
6
55
# Using iteration
def cumulative_sum(n):
if n <= 0:
return 0
total = 0
num = 1
while num <= n:
total += num
38
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
num += 1
return total
print(cumulative_sum(0))
print(cumulative_sum(3))
print(cumulative_sum(10))
0
6
55
Factorials
Exercise: Write a recursive function which calculates the factorial of a given integer, n.
How do we express a factorial recursively?
10! = 10 × 9!
= 10 × 9 × 8!
= 10 × 9 × 8 × 7!
= ...
= 10 × 9 × 8 × · · · × 2 × 1
# Using recursion
def factorial(n):
# base case
if n == 1:
return 1
# recursive relation
return n * factorial(n-1)
print(factorial(1))
print(factorial(2))
print(factorial(5))
print(factorial(10))
1
2
120
3628800
Here’s a visual explanation of all the layers of each recursive call.
https://www.cs.rice.edu/~ogilvie/assets/recursion.png
39
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
# Using iteration
def factorial(n):
product = 1
i = 1
while i <= n:
product = product * i
i = i + 1
return product
print(factorial(1))
print(factorial(2))
print(factorial(5))
print(factorial(10))
1
2
120
3628800
Week 12
Lists redux
print(two_d_list)
print(len(two_d_list))
two_d_list = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print(two_d_list)
40
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
print(len(two_d_list))
two_d_list = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
row = 0
while row < len(two_d_list):
col = 0
while col < len(two_d_list[row]):
elem = two_d_list[row][col]
print(elem, end=', ')
col += 1
print() # Move to new line
row += 1
1, 2, 3,
4, 5, 6,
7, 8, 9,
Here’s how to do the same thing with Python for loops.
two_d_list = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
1, 2, 3,
4, 5, 6,
7, 8, 9,
41
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Arrays
Arrays vs lists
Arrays Lists
All elements must be the same Elements can be different data-types
data-type
Are fixed length Can grow when appending elements
Elements are stored contiguously in Elements are NOT stored contiguously
memory in memory
Elements are stored as values Elements are stored as references
Smaller memory footprint Larger memory footprint
Faster to iterate Slower to iterate
Importing numpy
import numpy as np
print(np)
42
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
import numpy as np
print(arr1)
print(arr2)
[4 5 6]
[[3 4 5]
[4 8 2]
[4 5 6]]
Or, you can create an array with all elements initialized to zero or one.
import numpy as np
arr1 = np.zeros(4)
arr2 = np.ones((3, 5))
print(arr1)
print(arr2)
[0. 0. 0. 0.]
[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]
import numpy as np
row = 0
while row < len(arr):
col = 0
while col < len(arr[row]):
elem = arr[row][col]
print(elem, end=', ')
43
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
col += 1
print() # Move to new line
row += 1
3, 4, 5,
4, 8, 2,
4, 5, 6,
Alternatively, you can use the shape attribute, which gives you the size of each dimen-
sion.
import numpy as np
row = 0
while row < arr.shape[0]:
col = 0
while col < arr.shape[1]:
elem = arr[row][col]
print(elem, end=', ')
col += 1
print() # Move to new line
row += 1
Week 13
Revision questions
General programming
• What is a program?
• What is a compiler?
– Translate human readable code to machine readable code
• What is syntax?
– Rules of a language
• What does compilation or syntax error mean?
– Language does not make sense to compiler
• What is a string?
– A char array with associated functions
• What is a list? How is it different to a tuple?
• Draw truth tables for and, or, and not.
44
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062
Testing
Functions
• What is a function?
• What is the function signature?
– Name of function, data types of parameters, order of parameters
• How does a function deal with errors that it cannot handle?
– Exception thrown back to calling function
• What is a class?
– Blueprint to generate objects and functions for these objects
– A way to encapsulate (hide) data
– Puts functions together with data
• Why do we need classes?
– Reusable
– Generate instances of the class
• What is a constructor?
– A function which defines how to build an object
• What is an object?
• How do you create an object?
• What are instance variables?
– Variable unique to an object
• How are instance variables accessed?
– Using the dot operator, object.variable
• What is the difference between instance variables and class variables?
– Class variables don’t need an instance of a class
– Instance variables need an instance of a class
Recursion
45
Downloaded by Anthony Wen ([email protected])