0% found this document useful (0 votes)
394 views46 pages

Info1110 Notes Lecture Notes 13 Weeks PDF

This document contains lecture notes for a 13-week introductory programming course. It covers various programming concepts like variables, data types, operators, conditional statements, loops, functions, lists, files and streams. The notes provide examples and explanations of core Python programming concepts to help students learn. It also includes tips for students taking the course such as practicing regularly and using online resources.

Uploaded by

ansh1510
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
394 views46 pages

Info1110 Notes Lecture Notes 13 Weeks PDF

This document contains lecture notes for a 13-week introductory programming course. It covers various programming concepts like variables, data types, operators, conditional statements, loops, functions, lists, files and streams. The notes provide examples and explanations of core Python programming concepts to help students learn. It also includes tips for students taking the course such as practicing regularly and using online resources.

Uploaded by

ansh1510
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

lOMoARcPSD|14123062

Info1110-notes - Lecture notes 13 weeks

Info1110 (University of Sydney)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

INFO1110 Introduction to Programming

Contents
INFO1110 Introduction to Programming 1

Notes from the creator 3


About these notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Tips for doing well in INFO1110: . . . . . . . . . . . . . . . . . . . . . . . . . . 3

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

Notes from the creator

About these notes

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.

Tips for doing well in INFO1110:

Although these notes supplement studies and understanding of concepts, learning to


program requires constant practise. This is especially relevant to those new to pro-
gramming. There is no substitute to taking the time to go through problems and cod-
ing yourself. I cannot stress this point enough.
1. Don’t be afraid to make mistakes whilst you’re coding
If this is your first time coding, mistakes are inevitable. Don’t be disheartened if
your code doesn’t work straight away or if a concept is hard to grasp. The key
is to perservere, keep going and keep practising. Reframe failures as ways in

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

Assessment timeline and weightings can be found on CUSP.


https://cusp.sydney.edu.au/students/view-unit-page/alpha/INFO1110
The recommended textbook is Sedgewick’s Introduction to Programming in Python: An
Interdisciplinary Approach. It is available for free through the University library website,
or via academic sign-in at:
https://www.oreilly.com/library/view/introduction-to-programming/
9780134076539/?ar

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

Using the terminal

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 ~

It may be helpful to remember these as follows.


• pwd: Print working directory
• ls: List files and directories
• mkdir: Make directory
• cd: Change directory

5
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

Text editors

There are many to choose from. Choose your favourite.


• Visual Studio Code (https://code.visualstudio.com/)
• Atom (https://atom.io/)
• Sublime Text (https://www.sublimetext.com/3)
• Nano
• Vim

The print function

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

Variables and Expressions

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

The basic mathematical operators are


• + add
• - subtract
• * multiply
• / divide
print(6 + 4)
print(6 - 4)
print(6 * 4)
print(6 / 4)

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

The logical boolean operators in Python are:


• not (flips the boolean value)
• and
• or

Truth table for and

and True False


True True False
False False False

8
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

print(True and True)


print(True and False)
print(False and True)
print(False and False)

True
False
False
False

Truth table for or

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

Python data types


• str: string
• int: integer
• float: floating point (real number)
• bool: boolean

More operators

Comparison operators

Used to compare values. They all return a boolean value.


• < less than
• > greater than
• <= less than or equal to

9
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

• >= greater than or equal to


• == equals to (equality operator)
• != not equal to

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

In Python, variable names must conform to the following rules


• Can only use letters (a-z, A-Z), digits (0-9), and underscore (_)
• Cannot start with a digit (0-9)
Conventionally, Python variables should
• use snake case (e.g. number, maximum_value, smallest_box)
– no capitals
– use underscores to separate words, if required
https://www.python.org/dev/peps/pep-0008/#function-and-variable-names

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

The if keyword is generally followed by a boolean condition.

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

if weather == "sunny" and temperature > 25:


print("Let's go to the beach")

print("End of program")

Let's go to the beach


End of program

weather = "sunny"
temperature = 15

if weather == "sunny" and temperature > 25:


print("Let's go to the beach")

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

if weather == "sunny" and temperature > 25:


print("Let's go to the beach")
elif weather == "sunny" and temperature > 15:
print("Let's go to the dog park")
elif weather == "sunny" and temperature > 5:
print("Let's go out for lunch; remember to pack a jumper")

print("End of program")

Let's go to the dog park


End of program

weather = "sunny"
temperature = 30

if weather == "sunny" and temperature > 25:


print("Let's go to the beach")

11
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

elif weather == "sunny" and temperature > 15:


print("Let's go to the dog park")
elif weather == "sunny" and temperature > 5:
print("Let's go out for lunch; remember to pack a jumper")

print("End of program")

Let's go to the beach


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

if weather == "sunny" and temperature > 25:


print("Let's go to the beach")
elif weather == "sunny" and temperature > 15:
print("Let's go to the dog park")
elif weather == "sunny" and temperature > 5:
print("Let's go out for lunch; remember to pack a jumper")
else:
print("Let's stay inside")

print("End of program")

Let's stay inside


End of program

Ternary operator

The ternary operator is a one-line shortcut for writing an if-else condition.


<value_if_condition_is_true> if <condition> else <value_if_condition_is_false>

weather = "rainy"

should_go_outside = True if weather == "sunny" else False


print(should_go_outside)

False

while loops

While a condition is true, the while loop body will be run.

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

i = 0 # initialise a counter variable


while i < 5: # ensure a stopping condition
print(i)
i = i + 1 # update the counter variable

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

Control flow diagrams

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

And here is a concrete example, alongside the corresponding code.

i = 2
while i < 10:
i = i - 1
i = i * 5

Week 04

Lists

Here is how to create a list.

14
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

my_list = [5, 3, 8, 6]

Use len to find the length of a list.

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])

IndexError: list index out of range

Iterating through a list

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 = ["dog", "cat", "fish"]


print(pets)

['dog', 'cat', 'fish']


We can add elements to the end of a list with the append function.

pets.append("axolotl")
print(pets)

['dog', 'cat', 'fish', 'axolotl']


We can remove elements at a specific index with the pop function.

pets.pop(1)
print(pets)

['dog', 'fish', 'axolotl']

Filtering elements in a list

numbers = [4, 6, 3, 88, 45, 53, 24]


even_numbers = []

i = 0
while i < len(numbers):
number = numbers[i]
if number % 2 == 0:
even_numbers.append(number)
i = i + 1

print(even_numbers)

[4, 6, 88, 24]

things = ["dog", "dancer", "blue bottle", "deer", "caramel"]


things_starting_with_d = []

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)

['dog', 'dancer', 'deer']

Week 05

The type function

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]))

x = "it also works with variables"


print(type(x))

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

• The inputs are called arguments or parameters


• The output is called the return value
• The function name and list of arguments make up the function signature or
function prototype.

17
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

Why use functions?

Why do we need to use functions?


• Organizes code into logical group so it is tidy and easy to understand
• Code can be re-used
• No need to repeat code – this reduces error

Examples

def add(a, b):


return a + b

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

# Or another way of writing the above


# because (n % 2 == 0) is a boolean expression
def is_even(n):
return n % 2 == 0

print(is_even(4))
print(is_even(5))
print(is_even(6))

True
False
True

Ending a function

There are two ways a function can end:


1. If the function returns using the return keyword
2. If the function raises an error

18
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

The difference between print and return

Returning from a function and printing in a function are different things!


If a function does not explicitly return anything, the function will return None.

def print_hello(name):
print("Hello, {}".format(name))

def get_hello_string(name):
return "Hello, {}".format(name)

print("> calling print_hello")


ret = print_hello("Alice")
print(ret)

print("> calling get_hello_string")


ret = get_hello_string("Bob")
print(ret)

> calling print_hello


Hello, Alice
None
> calling get_hello_string
Hello, Bob

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,

the behaviour of this function is undefined.


"""
if n % 2 == 0:
return n // 2
return 3 * n + 1

Week 06

Streams and files

Input and output streams

A stream is a flow of data – into or out of a program.


• Streams flowing into the program are input streams: keyboard, compact disk
• Streams flowing out the program are output streams: monitor, hard drive
Streams only exist while a program is running. After the program ends, the stream is
closed. On the other hand, files can remain after programs end.
This is useful because:
• Files can be reused by different programs
• Convenient way to deal with large amounts of data
• Does not require user effort

File types

There are, generally, two types of files.


1. Binary files – less space used, read and edited by a program
2. Text files – human readable, can be edited by a human
There are no rules to what can be stored in a file.

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

1. Absolute path (from root directory, \)


2. Relative path (relative destination from current working directory)

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

Opening files in Python

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

Reading from a file

We use the open function to open a file.


The open function takes a filepath as its first argument and a mode as the second argu-
ment. In this case, we want to read from the file, so we specify "r" as reading mode.

f = open("sample.txt", "r")
print(f)
f.close()

<_io.TextIOWrapper name='sample.txt' mode='r' encoding='UTF-8'>


Remember to close your files after you finish working with them.
Why do we need to close files?
• It signals to the operating system that we are done working with the file.
• If we opened the file for writing, closing the file will flush the buffer and make
sure our changes are saved on disk.
• Having too many files open at once (like having too many programs open at
once) will slow down the computer.
There are two common ways to read from files:

21
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

1. Using readline to read the next line as a string


2. Using readlines to read all lines as a list

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()

['Apple\n', 'Banana\n', 'Carrot\n']


Note: each line you read will have a newline character (\n) at the end. A newline
character is typed when you press the Enter key on your keyboard. It is whitespace
and can be removed with the strip function.
https://docs.python.org/3/library/stdtypes.html#str.strip

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()

['Apple\n', 'Banana\n', 'Carrot\n']


[]

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()

['Axetol\n', 'Bandicoot\n', 'Cheetah\n']

23
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

Using with to automatically close a file

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.

with open("sample.txt", "r") as f:


print(f.readline())

print(f.readline()) # The file will be closed outside 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

ValueError: I/O operation on closed file.

Exceptions

An exception is an object that signals an unusual occurrence during execution.


When the exception object is created, it is termed ‘throwing an exception’ (or in
Python, ‘raising an exception’).
1. try statement – will try to run the code, an exception may occur
2. raise statement – generates an exception object
3. except statement – catches an exception object
4. finally statement – always runs, regardless of whether an exception occurred
try:
<try block>
except <exception type>:
<except block>
except <exception type>:
<except block>
finally:
<finally block>
Some common exceptions you can catch: TypeError, ValueError, FileNotFoundError.

Difference between TypeError and ValueError

What is the difference between TypeError and ValueError? Consider the following.
A TypeError happens when you give a function the wrong type.

value = int([2, 3]) # the int function expects a string

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.

value = int('42b') # we give it a string, but the string value is␣


֒→wrong

-----------------------------------------------
ValueError Traceback (most recent call last)
----> 1 value = int('42b')

ValueError: invalid literal for int() with base 10: '42b'

Using try and except

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

FileNotFoundError: [Errno 2] No such file or directory: 'non-existant-file.txt'


We can try some code which may not work and “catch” errors that may occur with
the except keyword.

try:
f = open("non-existant-file.txt", "r")
except FileNotFoundError:
print("The file could not be found.")

The file could not be found.


Some important points to note.
• If an exception occurs in a try block, the rest of the block will be ignored.
• If no exception occurs, all except blocks after the try block are ignored.
If the exception cannot be handled within its own function, the function will terminate
and throw it back to the caller. Recall, there are two ways a function can terminate.

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()

'Apple' could not be converted to float.

Handling multiple exceptions

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

Testing is about comparing actual output with expected output.


Without testing, you cannot be sure that your code works as you intend it to. Testing
makes reliable code. Compilation is not a guarantee of correctness. We need to make
sure the output and the values our program produces match with what we expect it
to.
It’s good practice to think about exactly what it is you want your functions and code
to do before you start writing up code.
• What is it’s normal functionality?
• What should happen when given bad or unexpected input?
• Edge and corner cases?
These questions can also help inform how you write tests. Don’t be afraid of failing
tests. Testing helps identify problems in your code so you can make the steps to fix the
problems.

Types of tests

There are different ways to test a program:


• Tracing code
– Desk checks, for example
• Black box testing
– Cannot see code – no reference to how the programs works
– Processes input and output only
– Quick and powerful
• White box testing
– Can see code – looks inside the function
– Can choose values to test different execution paths
• Testing by printing:
– Print after most (if not every) step
– Tells us which path has been executed
– Makes code messy
• Regression testing
– Running the same set of tests after the code is modified

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?

When testing, look for:


• Extreme cases
• Boundary (or edge) points
– Maximums
– Minimums
• Different execution paths
– For best code coverage, you need to think of all the possible ways the code
may run

Important keywords

Here are some key terms you should be familar with.


• Coverage: the proportion of the code that is tested
• Execution path: the route your program takes when it is run
• Assertion: a condition – what is it you want to ensure?
– Preconditions and postconditions are assertions placed before and after
some piece of code
• Invariant: a condition which is always true

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

Writing in/out tests

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

Comparing floating point numbers

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.

def is_almost_equal(a, b, error):


"""Returns true if difference of a and b is less than the error.
֒→"""

difference = abs(a - b)
return difference < error

print(is_almost_equal(1.4, 1.45, 0.001))


print(is_almost_equal(1.4, 1.45, 0.1))
print(is_almost_equal(0.1 + 0.2, 0.3, 0.001))

False
True
True

29
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

Week 08

List idioms

Reading input until a sentinal value

Example: Read in user input and echo back the input, until the user types in ‘stop’.

command = input('Enter a command: ')


while command != 'stop':
print(command)
command = input('Enter a command: ')

Enter a command: hello


hello
Enter a command: world
world
Enter a command: stop

Finding a specific value in a list

Example: Find the index and value of the first negative number in a list of numbers.

numbers = [8, 4, 6, -8, -2, 10]

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

numbers = [8, 4, 6, -8, -2, 10]

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

Counting the number of occurences in a list

Example: Count the number of words in a list that have 4 letters.

words = ['folk', 'mop', 'lamb', 'weekly', 'baby']

count = 0

i = 0
while i < len(words):
word = words[i]
if len(word) == 4:
count = count + 1
i = i + 1

print(count)

Finding the max/min value in a list

There are generally two ways to approach these questions.


• Set the smallest/largest variable to None
• Set the smallest/largest variable to the first element in the list
Example: Find the largest number in the list.

numbers = [4, 6, 12, -10, 3]

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.

words = ['folklore', 'rag', 'lamb', 'intensify', 'weekly']

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.

numbers = [-4, -6, -12, -10, -3]

largest = 0

i = 0
while i < len(numbers):
number = numbers[i]
if number > largest:
largest = number
i = i + 1

# This answer is incorrect, why?


print(largest)

32
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

Filtering a list in-place

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.

numbers = [4, 6, 3, 88, 45, 53, 24]

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)

[4, 6, 88, 24]


Or, we avoid handling the shifting list by iterating backwards.

numbers = [4, 6, 3, 88, 45, 53, 24]

i = len(numbers) - 1
while i >= 0:
number = numbers[i]
if number % 2 != 0:
numbers.pop(i)
i = i - 1

print(numbers)

[4, 6, 88, 24]

Filtering a list, without mutation

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.

numbers = [4, 6, 3, 88, 45, 53, 24]


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)

[4, 6, 88, 24]

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

A constructor tells you how to build an object.


It creates a space in memory for the object when it is called. In python, we declare the
constructor using __init__.
self is a keyword to describe and refer to the instance of the class.

class Book:
def __init__(self, title, author, year):
self.title = title
self.author = author
self.year = year

Let’s create instances of the Book class.


b1 = Book("To Kill A Mockingbird", "Harper Lee", 1960)

# 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)

b2 = Book("Great Expectations", "Charles Dickens", 1843)

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 vs class attributes

An instance attribute is a variable whose value is unique to each object.


• This variable is only accessible in the scope of this object
• It is defined inside the constructor function, __init__(self, ...), of the class
A class attribute is a Python variable that belongs to a class rather than a particular
object.
• It is shared between all the objects of this class.
• We define class attributes outside of the constructor function.

Instance vs class methods

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

def __init__(self, radius):


self.radius = radius # an instance variable

# An instance method
def calculate_area(self):
return Circle.pi * (self.radius ** 2)

# A class method, does not take self keyword


def get_pi():

35
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

return Circle.pi

# No need to create a Circle instance to call class method


print(Circle.get_pi())

# Create a circle instance with radius 2


c1 = Circle(2)
# Return the calculated area
# You can only call this method on instances of Circle
print(c1.calculate_area())

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

There are many ways to debug your program:


• Python debugger, https://docs.python.org/3/library/pdb.html
• Using the interactive interpreter
• Add print statements (often easiest, though not recommended)

%%bash

# Using the Python debugger


python3 -m pdb my_module.py

# Using the interactive interpreter


python3 -i my_module.py

Week 11

Recursion

A recursive method calls itself. It’s definition contains an invocation of itself.


The following rules apply to all recursive functions.
• The heart of the method is an if-else statement (or other branching statement)
leading to different cases.
• One or more of the branches should include a recursive invocation. These solve
‘smaller’ versions of the task.
• One or more branches must have no recursive call. These are your
base/stopping cases.
If no base class is provided, you end up with infinite recursion.
• Program will end when it runs out of resources (stack overflow!)
All recursive problems can be written iteratively (using while or for loops). All itera-
tive problems can be written recursively.

Why use 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

Why shouldn’t we use recursion?

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

– Each function call requires Python to construct a stack frame


• Some problems are easier to solve with an iterative solution

Recap

When writing a recursive method, you need


• A base case
• A recursive case
Do I need to use recursion for my problem?
• Any case solvable with recursion, can also be solved with while loops.
• However many methods are called, however deep you step, you will always be
stepping backward through your methods.
NOTE: Every time the method is called, a new function is loaded into the memory
with it’s own copies of local variables and arguments. So if you have called the same
function 5 times, Python has stored the data in each of those function invocations.

Writing a recursive function

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

What is the base case? What is the recursive case?


• Base case: 1! = 1
• Recursive relation: n! = n × (n − 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

Recall, a list can contain any data-types.

my_list = [45, 5.34, 'apples', True]


print(my_list)

[45, 5.34, 'apples', True]


Lists can have lists as their elements.
Here are two different ways of writing the same list.

two_d_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print(two_d_list)
print(len(two_d_list))

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]


3

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

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]


3

Iterating through a 2D list

For a one-dimensional list, we needed to maintain one index. For a two-dimensional


list, we need to maintain two indices (a row index and a column index).

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],
]

for row in two_d_list:


for elem in row:
print(elem, end=', ')
print() # Move to new line

1, 2, 3,
4, 5, 6,
7, 8, 9,

41
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

Arrays

Arrays vs lists

What is similar between arrays and lists?


• Both are an ordered collection of elements
• Both are indexable
• Both have length
What is the difference between an array and a list?

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

Why use arrays?

Why should we use arrays over lists?


• Faster to iterate over the elements because elements are stored contiguously in
memory
• Smaller memory footprint because elements are stored as values, rather than
references

The numpy package

Numpy is a python package for creating arrays.


Numpy documentation can be found here: https://docs.scipy.org/doc/numpy/
reference/

Importing numpy

To use numpy, you need to import it.

import numpy as np

print(np)

<module 'numpy' from '/usr/local/lib/python3.7/site-packages/numpy/


֒→__init__.py'>

42
Downloaded by Anthony Wen ([email protected])
lOMoARcPSD|14123062

Creating an array in numpy

The documentation has good documentation on array creation: https:


//docs.scipy.org/doc/numpy/reference/routines.array-creation.html#
routines-array-creation
The easiest way to create a numpy array is from a python list.

import numpy as np

arr1 = np.array([4, 5, 6])


arr2 = np.array([[3, 4, 5], [4, 8, 2], [4, 5, 6]])

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.]]

Iterating through a 2D numpy array

Iterating through a two-dimensional array is the same as iterating through a two-


dimenional list. You can use the len function to find the length of the dimension.

import numpy as np

arr = np.array([[3, 4, 5], [4, 8, 2], [4, 5, 6]])

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

arr = np.array([[3, 4, 5], [4, 8, 2]])

print("The shape of the array is {}".format(arr.shape))

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

The shape of the array is (2, 3)


3, 4, 5,
4, 8, 2,

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

• What is unit testing?


• What is regression 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

Classes and objects

• 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

• What is a base case?


• Given some recursive code, identify:
– Base case
– Recursive case
– The output of a function call (what is printed or returned?)

45
Downloaded by Anthony Wen ([email protected])

You might also like