Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

ENGG1810/9810

ENGG1810/9810
Introduction to Engineering Computing
Week 4: Repeating Actions II

Dr. Imdad Ullah


Faculty of Engineering
ENGG1810/9810

COMMONWEALTH OF AUSTRALIA

Copyright Regulations 1969

WARNING

This material has been reproduced and communicated to you by or on behalf of


the University of Sydney pursuant to Part VB of the Copyright Act 1968 (the Act).

The material in this communication may be subject to copyright under the Act.
Any further reproduction or communication of this material by you may be the
subject of copyright protection under the Act.

Do not remove this notice.


INTRODUCTION
ENGG1810/9810

What will you learn in this course?


Week 1: Introduction to Python

Week 2: Storing Data and Making Decisions Programming


Week 3: Repeating Actions I Basics

Week 4: Repeating Actions II

Week 5: Functions I
Week 6: Functions II Functions
Week 7: Libraries and Modules I
and Packages

Week 8: Libraries and Modules II

Week 9: Application I

Week 10: Application II Advanced


Week 11: Case Study I
Topics

Week 12: Case Study II

Week 13: Revision and Exam Guide


ENGG1810/9810

This week preview!


We have three students in ENGG1810/9810, BTS_V, Emma Watson, Spongebob

ENGG1810/9810 Students We plot their grades for each assessment item

BTS_V Emma Spongebob

ENGG1810/9810 Assessment
No. Assessment
1 Weekly Works (Lab Exercise)
2 Lab Test 1
3 Lab Test 2
4 Final Exam
ENGG1810/9810

This week preview!


We have three students in ENGG1810/9810, BTS_V, Emma Watson, Spongebob

ENGG1810/9810 Students We plot their grades for each assessment item

What do we need
to plot this? Hmm…

BTS_V Emma Spongebob

ENGG1810/9810 Assessment
No. Assessment
1 Weekly Works (Lab Exercise)
2 Lab Test 1
3 Lab Test 2
4 Final Exam
ENGG1810/9810

Today’s Lecture

• Advanced Collections and Visualisation


• Multi-dimensional Collections
• Visualisation: Graph Plotting (with loops)
• File I/O
• Processing of Reading (with Regex)
• Processing of Writing
• Exceptions
ENGG1810/9810

Python Collections
We have three students in ENGG1810/9810, BTS_V, Emma Watson, Spongebob

We plot their grades for each assessment item First, we need representing their name and grade for each item!
Then, for loop? and visualise with matplotlib?
What do we need
to plot this? Hmm…
ENGG1810/9810

Python Collections
We have three students in ENGG1810/9810, BTS_V, Emma Watson, Spongebob

We plot their grades for each assessment item First, we need representing their name and grade for each item!

Lists or Tuples
What do we need items = ['Weekly', 'LabTest1', 'LabTest2', 'FinalExam']
to plot this? Hmm…
btsv = [18, 8, 16, 45]

emma = [20, 8, 16, 42]

sponge = [10, 4, 14, 35]

Dictionaries
bts_v = { emma = { sponge = {
“Weekly”: 18, “Weekly”: 20, “Weekly”: 10,
“LabTest1”: 8, “LabTest1”: 8, “LabTest1”: 4,
“LabTest2”: 16, “LabTest2”: 16, “LabTest2”: 14,
“FinalExam”: 45 “FinalExam”: 42 “FinalExam”: 35
} } }
ENGG1810/9810

Python Collections
We have three students in ENGG1810/9810, BTS_V, Emma Watson, Spongebob

We plot their grades for each assessment item First, we need representing their name and grade for each item!

Lists or Tuples
What do we need items = ['Weekly', 'LabTest1', 'LabTest2', 'FinalExam']
to plot this? Hmm…
btsv = [18, 8, 16, 45]

emma = [20, 8, 16, 42]

sponge = [10, 4, 14, 35] Individual 1-dimensional


data collections

Dictionaries
bts_v = { emma = { sponge = {
“Weekly”: 18, “Weekly”: 20, “Weekly”: 10,
“LabTest1”: 8, “LabTest1”: 8, “LabTest1”: 4,
“LabTest2”: 16, “LabTest2”: 16, “LabTest2”: 14,
“FinalExam”: 45 “FinalExam”: 42 “FinalExam”: 35
} } }
ENGG1810/9810

Python Multi-dimensional Collections


We have three students in ENGG1810/9810, BTS_V, Emma Watson, Spongebob

We plot their grades for each assessment item First, we need representing their name and grade for each item!

We can put lists or dictionaries to the values in dictionary items


What do we need
to plot this? Hmm…

dictionary when values am lists


ENGG1810/9810

Python Multi-dimensional Collections


We have three students in ENGG1810/9810, BTS_V, Emma Watson, Spongebob

We plot their grades for each assessment item First, we need representing their name and grade for each item!

We can put lists or dictionaries to the values in dictionary items


What do we need
to plot this? Hmm…
ENGG1810/9810

Python Multi-dimensional Collections


We have three students in ENGG1810/9810, BTS_V, Emma Watson, Spongebob

We plot their grades for each assessment item First, we need representing their name and grade for each item!

We can put dictionaries to the values in list items


What do we need
to plot this? Hmm…

Name Weekly LabTest1 LabTest2 FinalExam


BTS_V 18 8 16 45

Emma 20 8 16 42

Spongebob 10 4 14 35

There are several other ways


you can store those data
ENGG1810/9810

Today’s Lecture

• Advanced Collections and Visualisation


• Multi-dimensional Collections
• Visualisation: Graph Plotting (with loops)
• File I/O
• Processing of Reading (with Regex)
• Processing of Writing
• Exceptions
ENGG1810/9810

Python Visualisation
We plot their grades for each assessment item First, we need representing their name and grade for each item!
Then, for loop, and visualise with matplotlib

If we use Individual 1-dimensional data

Lists or Tuples
items = ['Weekly', 'LabTest1', 'LabTest2', 'FinalExam']

btsv = [18, 8, 16, 45]

emma = [20, 8, 16, 42]

sponge = [10, 4, 14, 35]


ENGG1810/9810

Python Visualisation (with loops)


We plot their grades for each assessment item for loop, and visualise with matplotlib
Start matplotlib pyplot

Multiple lists

The subplots() function you can


draw multiple plots in one figure
ENGG1810/9810

Python Visualisation (with loops)


We plot their grades for each assessment item for loop, and visualise with matplotlib
Start matplotlib pyplot

Multiple lists

The subplots() function you can


draw multiple plots in one figure
ENGG1810/9810

Python Visualisation (with loops)


We plot their grades for each assessment item for loop, and visualise with matplotlib
Start matplotlib pyplot

Multiple lists

controls
2 The subplots() function you can
draw multiple plots in one figure
layout
ucancontroltheareaofgraph
x y

nightof
numberabove
nav
ENGG1810/9810

Python Visualisation (with loops)


We plot their grades for each assessment item for loop, and visualise with matplotlib
Start matplotlib pyplot

Multiple lists

The subplots() function you can


draw multiple plots in one figure

anav
Y
location
x y
some
ENGG1810/9810

Python Visualisation (with loops)


We plot their grades for each assessment item for loop, and visualise with matplotlib
Start matplotlib pyplot

Multiple lists

The subplots() function you can


draw multiple plots in one figure

Add this code block


ENGG1810/9810

Python Visualisation (with loops)


We plot their grades for each assessment item for loop, and visualise with matplotlib
Start matplotlib pyplot

Multiple lists

axes
The subplots() function you can
draw multiple plots in one figure

Add this code block


ENGG1810/9810

Python Visualisation (with loops)


We plot their grades for each assessment item First, we need representing their name and grade for each item!
Then, maybe for loop, and visualise with matplotlib?

If we use multi-dimensional data


ENGG1810/9810

Python Visualisation (with loops)


We plot their grades for each assessment item for loop, and visualise with matplotlib

key value

I
Multi-dimensional dictionary

ac
intagers got
ENGG1810/9810

Python Visualisation (with loops)


We plot their grades for each assessment item for loop, and visualise with matplotlib

key value
Multi-dimensional dictionary
ENGG1810/9810

Python Visualisation (with loops)


We plot their grades for each assessment item for loop, and visualise with matplotlib

key value
Multi-dimensional dictionary

Same as page 16

Same as page 19
ENGG1810/9810

Python Visualisation (with loops)


We plot their grades for each assessment item for loop, and visualise with matplotlib

key value
Multi-dimensional dictionary
ENGG1810/9810

Today’s Lecture

• Advanced Collections and Visualisation


• Multi-dimensional Collections
• Visualisation: Graph Plotting (with loops)
• File I/O
• Processing of Reading (with Regex)
• Processing of Writing
• Exceptions
ENGG1810/9810

Python File I/O

The mailman on Main Street in Los Angeles tackled the problem in the
fall of 1943 - the third year of World War II.

He stood before building #100, where supposably a Mr. F.B.Iers was


supposed to be working in room 1619. However, there was neither a
Federal Building Company nor even a room 1619. Somehow, the post
card made its way to room 619 where the FBI maintained an office.
ENGG1810/9810

Python File I/O

The mailman on Main Street in Los Angeles tackled the problem in the
fall of 1943 - the third year of World War II.

He stood before building #100, where supposably a Mr. F.B.Iers was


supposed to be working in room 1619. However, there was neither a
Federal Building Company nor even a room 1619. Somehow, the post
card made its way to room 619 where the FBI maintained an office.
ENGG1810/9810

Python File I/O


ENGG1810/9810

Python File I/O

open(file, mode)
In order to open a file

- file filename
- mode mode

There are mainly four mode:


• "r" - Read - Default value. Opens a file for
reading, error if the file does not exist

• "a" - Append - Opens a file for appending,


creates the file if it does not exist

• "w" - Write - Opens a file for writing,


creates the file if it does not exist

• "x" - Create - Creates the specified file,


returns an error if the file exists
ENGG1810/9810

Python File I/O

open(file, mode)
In order to open a file

- file filename
- mode mode

read(size)
for reading the content of the file

- size specified size of characters

What if we change the size?


ENGG1810/9810

Python File I/O

open(file, mode)
In order to open a file

- file filename
- mode mode

letters
ing read(size)
for reading the content of the file

- size specified size of characters

What if we change the size?


ENGG1810/9810

Python File I/O


Can we remove those punctuations? I want to clean it!

Yes, we can use Python RegEx!


• A RegEx (Regular Expression) is a sequence of characters that forms a search pattern.
• RegEx can be used to check if a string contains the specified search pattern.
ENGG1810/9810

Python RegEx
Can we remove those punctuations? I want to clean it!

Yes, we can use Python RegEx!


• A RegEx (Regular Expression) is a sequence of characters that forms a search pattern.
• RegEx can be used to check if a string contains the specified search pattern.

Start with Import re

The sub() function replaces the The split() function returns a list where
matches with the text of your choice: the string has been split at each match:
ENGG1810/9810

Python File I/O


Can we remove those punctuations? I want to clean it with Regex!

Replace every
: (colon) or , (comma) or . (full stop)
character with ‘’ (nothing)

[] – a set of characters
ENGG1810/9810

Python File I/O


Can we fix it to all uppercases or lowercases?

The upper() method returns a string


where all characters are in upper case.
Symbols and Numbers are ignored.

You can also try lower() method


ENGG1810/9810

Python File I/O


Let’s try to extract two words from each line!
You can see that in the editor but each line is separated by the line break \n
We can check it in the Shell
I
newline

So we can use \n and extracted each line!


ENGG1810/9810

Python File I/O


Let’s try to extract two words from each line!
1. Use \n to extract each line.
2. Extract two words from each line

The split() function returns a list where the string has


been split at each match.

Hence, it returns a list where the object uppercase has


been split at each match of ‘\n’
ENGG1810/9810

Python File I/O


Let’s try to extract two words from each line!
1. Use \n to extract each line.
2. Extract two words from each line

uppercase.split(‘\n’) : a list where the object uppercase


has been split at each match of ‘\n’

line : each line (each item in the list uppercase.split(‘\n’) )

line.split(‘ ’) : a list where the object line


has been split at each match of ‘ ’ (whitespace)
ENGG1810/9810

Python File I/O


We can print this in a clean way!

list + list: combine those two lists together


ENGG1810/9810

Python File I/O


Much cleaner! Print like a sentence.

The join()method returns a string by joining all the


elements of an iterable (list, string, tuple), separated
by a string separator.
ENGG1810/9810

Python File I/O


Much cleaner! Print like a sentence.

Join function
ENGG1810/9810

Today’s Lecture

• Advanced Collections and Visualisation


• Multi-dimensional Collections
• Visualisation: Graph Plotting (with loops)
• File I/O
• Processing of Reading (with Regex)
• Processing of Writing
• Exceptions
ENGG1810/9810

Python File I/O


Can we add more contents to the file? Remember?
We created the letter_cp.txt file and copied the
content from the letter.txt. open(file, mode)
In order to open a file

- file filename
- mode mode

There are mainly four mode:


• "r" - Read - Default value. Opens a file for
reading, error if the file does not exist

• "a" - Append - Opens a file for appending,


creates the file if it does not exist

• "w" - Write - Opens a file for writing,


creates the file if it does not exist

• "x" - Create - Creates the specified file,


returns an error if the file exists
ENGG1810/9810

Python File I/O


Can we add more contents to the file?
We created the letter_cp.txt file and copied the
content from the letter.txt.

to append

After appending
ENGG1810/9810

Python File I/O

We can overwrite this file


Due to the security issue, we decided to overwrite any
existing content in the letter_cp.txt file.

clears a

After overwriting
ENGG1810/9810

Today’s Lecture

• Advanced Collections and Visualisation


• Multi-dimensional Collections
• Visualisation: Graph Plotting (with loops)
• File I/O
• Processing of Reading (with Regex)
• Processing of Writing
• Exceptions
ENGG1810/9810

Python File and Exception


What if we open/read/write/append the file that is not existed?
e.g. File is not found in the directory

If there is no file test.txt


ENGG1810/9810

Python File and Exception


What if we open/read/write/append the file that is not existed?
e.g. File is not found in the directory

If there is no file test.txt If there is no file test.txt

It doesnt
exist
ENGG1810/9810

Python File and Exception


What if we open/read/write/append the file that is not existed?
e.g. File is not found in the directory

Python has general set of tools for handling such errors called exception handling

Try to do what we intend to do try:


<statements we intend to do>
except <ExceptionName>:
<statements for handling errors>

If it fails or something goes wrong,


program executes codes in except block

NOTE: If nothing goes wrong, the execute block does not run and
program moves to the first line after the try-except block.
ENGG1810/9810

Python File and Exception

Exceptions can be everywhere!


- File is not found in the directory
- Unable to write to file
- User does not input the right data/format
- A division by zero ‘0’
- Mismatch calculations e.g., adding integer number with a string literal

If we do not handle exceptions,


- Output of the program is unexpected
- Program fail to execute but cryptic error message is provided

More exceptions will be covered in later weeks!


ENGG1810/9810

THANKS FOR
WATCHING
Good luck in studying

You might also like