Professional Documents
Culture Documents
ICT1002 Lec3 - Advanced Data Structures & Files IO & Loops - 2019
ICT1002 Lec3 - Advanced Data Structures & Files IO & Loops - 2019
PROGRAMMING FUNDAMENTALS
Week 03
Advanced structure (List&Tuple&Dictionary) & for/while loop
& Files I/O
1
Module Road Map
Wishful
Debugging & Selection &
Thinking Higher-order
DocString Iteration function
Algorithms & Software Recursion
problem solving development
Skills of IT
Objective Python Programming
Professional
name=‘Mike Jackson’
age = 80
salary = 1000.23
Is_student = True
3
Advanced data structures in Python
4
Advanced data structures in Python
• Sequence – the most basic data structure to store
multiple elements 0 1 2 3
5
STRINGS
6
STRINGS
>>> ‘z’ in t
>>> s = ‘ba’
False
>>> t = ‘ck’
>>> s + t >>> ‘bananb’ > t
‘back’ True TIPs:
String
comparison
>>> ‘banan’ <= t
>>> t = s + ‘na’ * 2 From left to
right
True
>>> t
‘banana’ >>> ‘c’ < t
False
7
STRING SLICING
10
List
11
List
• Membership checking
12
List built-in functions
Built-in Functions Function Description
cmp(list1, list2) Compare elements of both lists
len(list) Gives the total length of the list
max(list) Returns item from the list with max value
min(list) Returns item from the list with min value
list(seq) Converts a tuple into list
List built-in methods
Built-in method Function Description
15
More cool stuff about list
• The items in one list can be any other advanced data structure as well
16
5-minute exercises
18
Tips for list
list1
>> list1 = [5, 7, 8, 9] list2
510 7 8 9
• What is a list
A list of comma-separated values (elements/items) between square
brackets
21
Tuples
• Create a tuple
Basic Operations results
len(tuple1)
5 in tuple1
Concatenation:
• Another way to create a tuple tuple1+(9,10)
22
Tuples
• Python built-in functions for tuples
Functions Description
cmp(tuple1, tuple2) Compare elements of both tuples
len(tuple) Gives the total length of the tuple
max(tuple) Returns item from the tuple with max value
min(tuple) Returns item from the tuple with min value
tuple(seq) Coverts a list into tuple
• Usability
– To store data that can not be changed
23
Review
• What is a tuple
A sequence of comma-separated values (elements/items) between
parentheses ()
• Features of a tuple
Can be accessed but can not be changed
24
Store pair data
• Students information
– Each student has a student ID
– Each student has a name
– ID is unique and name not A001 Mike A005 Jim
• Search one student’s name according
to the ID
• List
– A linear collection of values that stay in order
• Dictionary
– A “bag” of values, each with its own label
• Dictionaries in different languages
– Associative arrays – perl/php
– Properties or map or hashmap – java
– Property bag – C#/.Net
26
Dictionary
Student Information 27
Dictionary
• Keys are unique within one dictionary while values may not be
• The values can be of any type
– Strings, numbers, tuples, lists, dictionaries etc
• The keys must be of an immutable data type
– Strings, numbers, or tuples
28
Dictionary
29
Dictionary
• Update dictionary
– Add a new entry or a key-value pair
– Modify an existing entry
– Delete an existing entry
30
Dictionary
• Delete one item from one dictionary
– Del dict[key]
• Delete the student with ‘A001’ ID
31
Dictionary
Function Description
cmp(dict1, dict2) Compare elements of both dictionaries
len(dict) Give the length of the dictionary, which is the
number of items in the dictionary
str(dict) Produce a printable string representation of a
dictionary
32
Dictionary
• Built-in dictionary methods
Methonds Description
dict.clear() Removes all elements of the dictionary dict
dict.copy() Returns a shallow copoy of dictionary dict
dict.fromkeys(seq,value) Create a new dictionary with keys from seq and values set to
value
dict.get(key, default=None) For key key, return value or default if key not in dictionary
dict.has_key(key) Return True if key in dictionary, false otherwise
dict.items() Return a list of dict’s (key, value) tuple pairs
dict.keys() Return a list of dict’s keys
dict.setdefault(key,default=None) Similar to get(), but will set dic[key]=default if key is not
already in dict
dict.update(dict2) Add dictionary dict2’s key-value pairs to dic
dict.values() Returns list of dictionary dict’s values 33
Exercises
34
Review
• What is a list
– A list of comma-separated elements rounded by square brackets []
• What is a tuple
– A sequence of comma-separated elements rounded by parentheses
()
• What is a dictionary
– A set of key and value pairs
– Each key is separated from its value by a colon (:)
– The items are separated by commas
– The whole thing is enclosed in curly braces
35
Module Road Map
Wishful
Debugging & Selection &
Thinking Higher-order
DocString Iteration function
Algorithms & Software Recursion
problem solving development
Skills of IT
Objective Python Programming
Professional
1.
2.
38
range() function
• range()
– Generate a list of numbers
– Generally used to iterate over with for loops
• range(stop)
– Stop: number of integers to generate starting from 0
• range([start,]stop[,step])
– Start: starting num of the sequence
– Stop: generate num up to, but not including this num
– Step: difference between each num in the sequence
39
for: EXECUTING A STATEMENT A GIVEN
NUMBER OF TIMES
• Python’s for loop is the control statement that most easily
supports definite iteration
loop body
• Example:
• Given one string ‘for loop is so cool!’, and print all the character
except the ‘ ’ using a for loop.
• Given one tuple with items (‘Saul’, ‘David’, ‘Solomon’), print all
the items with welcome message, e,g. Welcome XXX!
• Develop one program to print out the summation of the even
number between 3 to 300
45
Exercises
• Given one string “for loop is so cool!”, and print all the
character except the ‘ ’ using a for loop.
46
Exercises
• Given one tuple with items (‘Saul’, ‘David’, ‘Solomon’), print all
the items with welcome message, e,g. Welcome XXX!
47
Exercises
48
CONDITIONAL ITERATION: THE while LOOP
52
INFINITE LOOPS
55
Break & continue
for j in range(10): 0
‘break’ is used to
print(j) 1
break out
if j == 3: 2 of loop
break 3
for j in range(10): 1
if j % 2 == 0: 3 ‘continue’ is used to
continue 5 skip current
print(j) 7 iteration
9
Break & continue
1 ‘break’ is used
to break out
of loop
1
3 ‘continue’ is used
to skip current
5
iteration
7
…
57
5-min Exercises
58
Exercises
59
Ways to terminate the loop
Skills of IT
Objective Python Programming
Professional
63
Files I/O in Python
Process the
Open one file Close the file
data/file
64
Open the file
Syntax:
file_object = open(file_name [, access_mode] [, buffering])
65
Files I/O
Syntax:
File_object = open(file_name [, access_mode] [, buffering])
• File_name
– this argument is a string value that contains the name of the file that you want to access
• Access_mode
– Determine the mode in which the file has to be opened, i.e., read, write, append, etc.
– Optional, the default model is read(r)
• Buffering
– 0: no buffering takes place
– 1: line buffering is performed
– Greater than 1: buffering action is performed with the indicated buffer size
– No value or negative: system default value
66
mode description
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb For reading only in binary format. The file pointer is placed at the beginning of the file.
r+ For both reading and writing. The file pointer placed at the beginning of the file.
rb+ For both reading and writing in binary. The file pointer placed at the beginning of the file.
w For writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
wb For writing only in binary. Overwrites the file if the file exists. Otherwise, creates a new file for writing.
w+ Both writing and reading. Overwrites the existing file if the file exists. Otherwise, creates a new file
wb+ Both writing and reading in binary. Overwrite the existing file if the file exists. Otherwise, create a new file
a For appending. The file pointer is at the end of the file if the file exists. Otherwise, create a new file
ab For appending in binary. The file pointer is at the end of the file if the file exists. Otherwise, create a new file for
writing
a+ For appending and reading. The file pointer is at the end of the file if file exists. Otherwise, create a new file
reading and writing
ab+ For both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in
the append mode. Otherwise, it creates a new file for reading and writing. 67
Write data to one file
Open one file Write data to the file Close the file
• obj.write(str)
write the data to the
file
• Obj.close()
Close the file
• obj.read([count])
Read count bytes from
the file pointer
If count is not specified,
read as much as possible
69
More ways to read data from one file
• Tell()
– Check where is the current file pointer
• Seek(offset[,from])
– Change the current file pointer position
– The offset argument indicates the number of bytes to be moved
– The from argument specifies the reference position from where the
bytes are to be moved
• 0: use the beginning of the file as the reference position
• 1: use the current position as the reference position
• 2: use the end of the file as the reference position
71
Example
72
More cool functions for files operation
• Renaming files
• Deleting files
• Create directories
• Delete directories
• ……
73
CSV File Reading and Writing
74
SUMMARY
76