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

ICT1002

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

Input/output & data


Knowledge of Tools/Rules Elements of Functional
Computer programming abstraction formatting
Knowledge (From keyboard;
Variables & Types & Operators &
of Software
Advanced Data Structures From files)
Fundamental concepts of computer programming
2
Advanced data structures in Python

• Declare/use simple variables from last week


– String, int, float, bool etc

name=‘Mike Jackson’
age = 80
salary = 1000.23
Is_student = True

3
Advanced data structures in Python

• Exercises: how to store 100 people’s name in a program?


– E.g. Saul, David, Solomon, Rehoboam, Jeroboam I, Abijah, Baasha, …
Name1 = ‘Saul’
Name2 = ‘David’
Name3 = ‘Solomon’
Name4 = ‘Rehoboam’

4
Advanced data structures in Python
• Sequence – the most basic data structure to store
multiple elements 0 1 2 3

– Each element of a sequence is assigned a number – its


position or index
– The first index is zero, the second index is one, and so forth.
• Python – six built-in types of sequences
– Str, list, tuple, unicode, buffer, xrange
– Indexing, slicing, adding, multiplying, checking for
membership, finding the length of a sequence, and finding its
largest and smallest elements
– Str, list and tuple

5
STRINGS

• A string is a sequence of characters


• Strings are identified by single or double quotation marks:
– ‘Mike’,
– “Something interesting”,
– ‘73’
• The operator + is used for string concatenation:
– ‘Mike’ + ‘Jackson’ evaluates to ‘MikeJackson’
– ‘Mike’ + ‘ ’ + ‘Jackson’ evaluates to ‘Mike Jackson’

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

• A string is a sequence of characters


• We can thus index a string, i.e.
>>> s = ‘abcd’
>>> s[0]
‘a’
>>> s[2]
‘c’

• First character is indexed with 0.


• Last character is indexed with len(s)-1
8
STRING SLICING

>>> s = ‘abcdef’ s[start:stop:step]


>>> s[0:2]
‘ab’ non-inclusive
>>> s[1:5:3]
>>> s[1:2]
‘b’ ‘be’
>>> s[:2]
‘ab’ >>> s[::2]
‘ace’
Slicing returns a new string
9
List
• What is a list
– The most versatile datatype written as a list of comma-separated
values (elements/items) between square brackets
• Create a list:

• Access/read the ith value: name_list[i], where i is from 0 to len() -1

10
List

• Print out the list

• Update the value of the ith item

• Delete one item

11
List

• Check the length of the one list

• Membership checking

• Slicing operations – similar to strings Items


Last 3rd from 1st
item until the
end

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

list.append(obj) Append object obj to list

list.count(obj) Returns count of how many time obj occurs in list

list.extend(seq) Appends the contents of seq to list

list.index(obj) Returns the lowest index in list that obj appears

list.insert(index, obj) Inserts object obj into list at offset index

list.pop(obj=list[-1]) Removes and returns last object or obj from list

list.remove(obj) Removes object obj from list

list.reverse() Revers objects of list in place

list.sort([func]) Sort objects of list, use compare func if given


Example of using built-in methods

15
More cool stuff about list

• The items in one list can have different types

• The items in one list can be any other advanced data structure as well

16
5-minute exercises

• Create a list including five different salaries


– 1000, 2500, 2600, 500, 14
• Print out all the salaries
• Add one more salary (30) to the list
• Find the minimum salary and remove it from the list. If the
removed salary is smaller than 20, add removed salary to the
maximum salary to the list. Otherwise, add removed salary to the
minimum salary from the remaining list.
• In the end, print out the current list length and three biggest salary.
• Bonus: figure out whose salary is above average and whose is not
17
5-minute exercises

• Create one list list1 with items 5, 7 ,8 ,9


• Copy the list1 to another list2
• Change the first item in list 2 into 10
• Print both list 1 and list 2

18
Tips for list
list1
>> list1 = [5, 7, 8, 9] list2
510 7 8 9

>> list2 = list1


>> list2[0] = 10
>> list1[0]
10
How to make a copy of one list with different memory location?

>> list1 = [5, 7, 8, 9] list1 5 7 8 9

>> list2 = list1[:]


list2 510 7 8 9
>> list2[0] = 10
>>list1[0]
5 19
Review

• What is a list
A list of comma-separated values (elements/items) between square
brackets

• List can be:


Access by index
Update
Delete
Add
Sort
…
20
Tuples

• A sequence of immutable Python objects


• Tuples are sequences, just like list

• Difference between tuple and list


– Tuples use parentheses () and lists use square brackets []
– The tuples can not be changed

21
Tuples
• Create a tuple
Basic Operations results
len(tuple1)
5 in tuple1
Concatenation:
• Another way to create a tuple tuple1+(9,10)

Slicing operation results


Tuple1[-2]
• Update one tuple item Tuple1[:2]
Tuple1[1:]

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

What is the best way to store this A003 Tom


data? Student ID Student Name
A001 Mike
A005 Jim
A003 Tom 25
Dictionary

• 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

• Each item in a dictionary consists of one key and its value


• Dictionary declaration
– Each key is separated from its value by a colon (:)
– The items are separated by commas
– The whole thing is enclosed in curly braces
– An empty dictionary without any items is written with just two braces like
{}
Student ID Student Name Store all student information into one dictionary stu_info
A001 Mike
A005 Jim
A003 Tom

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

• Accessing dictionary elements


– The familiar square brackets along with the key to obtain its value

• Accessing a data item that is not part of the dictionary

29
Dictionary
• Update dictionary
– Add a new entry or a key-value pair
– Modify an existing entry
– Delete an existing entry

• Change the name of ‘A001’ into ‘David’

• Add <‘A002’, ‘Solomon’> to the list

30
Dictionary
• Delete one item from one dictionary
– Del dict[key]
• Delete the student with ‘A001’ ID

• Delete all students from stu_info


• Dict.clear ()

31
Dictionary

• Built-in dictionary functions

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

• Develop one program to Student ID Name Grade


store all the student’s A001 Mike 85
A003 Mike 98
information using
A005 Tom 20
dictionaries
• Based on the dictionary, try
to print out the sorted grades

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

Input/output & data


Knowledge of Tools/Rules Elements of Functional
Computer programming abstraction formatting
Knowledge (From keyboard;
Variables & Types & Operators &
of Software
Advanced Data Structures From files)
Fundamental concepts of computer programming
36
ITERATIONS

‘FOR’ LOOPS AND ‘WHILE’ LOOPS


REPETITION/ITERATION CONTROL STRUCTURE
Repeat the following steps 20 times:

1.
2.

While u don’t understand python:


Learn & practice

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

• The form of this type of loop is:


loop header

loop body

statements in body must be indented and aligned


in the same column
for LOOPS – ITERATING OVER A SEQUENCE
• The iterator (variable) of the loop takes its values from a
sequence of values.
for <variable> in <sequence>:
<do something interesting>

• The sequence can be a range, or can be many other things.


COUNT-CONTROLLED LOOPS

• Loops that count through a range of numbers

• To specify a explicit lower bound:


Another example

• Example: bound-delimited summation Lower_bound = 2


Upper_bound = 4
– User input lower bound and upper bound Sum = 2+3+4 = 9

– Calculate the summation from the lower to upper bound


LOOP COMMON ERROR: OFF-BY-ONE ERROR

• Example:

• This is not a syntax error, but rather a logic error


Exercises

• 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

• Develop one program to print out the summation of the even


numbers between 3 to 200

48
CONDITIONAL ITERATION: THE while LOOP

• A while loop statement repeatedly executes a target statement


as long as a given condition is true
• The while syntax in Python
while <expression>:
<body>
• Expression
• Predicate to stay within loop
• Body
• Body that will be evaluated if predicate
<expression> is True
49
CONDITIONAL ITERATION: THE while LOOP

The suit may never be


executed, if the condition is
False to begin with

As long as the condition is True,


the statements within the loop The suit may be executed
are executed forever, if the condition is
Infinite loop
always True
CONDITIONAL ITERATION: THE while LOOP
CONDITIONAL ITERATION: THE while LOOP

If input is not a number, ask


the user to continually input
until the right one

NOTE: str.isdigit() is to test if all characters are digits

52
INFINITE LOOPS

• Generally the result of programming errors.


• The most common reason for a program ‘hanging’
• To quit program execution –
ctrl+C
It is critical to understand
how the loop control
variables change in the
body of the loop
DEFINITE AND INDEFINITE LOOPS
Before entering the loop, it is clear
how many times it will iterate

We don’t really know


how many times it will
iterate
Is there any other ways to terminate one loop?

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

• Develop one program to allow users to input as many number


as they want until they input enter
• Calculate the summation of all the input numbers
• Output the summation to the user in the end

58
Exercises

59
Ways to terminate the loop

• Use break to control loop

• Alternative: Use a Boolean variable to control loop


LOOP LOGIC, ERRORS AND TESTING

• Errors to rule out during testing of while loops:


– Incorrectly initialized loop control variable
– Failure to update this variable correctly within loop
– Failure to test it correctly in continuation condition
• To halt loop that appears to hang during testing, type
Control+c
• If loop must run at least once, use a while True loop with
delayed examination of termination condition
– Ensure a break statement to be reached eventually
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

Input/output & data


Knowledge of Tools/Rules Elements of Functional
Computer programming abstraction formatting
Knowledge (From keyboard;
Variables & Types & Operators &
of Software
Advanced Data Structures From files)
Fundamental concepts of computer programming
62
Files I/O

• Data used in the program is stored in the memory


of one computer
– Once the program stops, the data will be gone

Keep the data permanent?


• Write data to files on disk

63
Files I/O in Python

• Python provides functions and methods necessary to


manipulate files

Process the
Open one file Close the file
data/file

The main steps of file operations in Python

64
Open the file

• Open one file as one file object


– Python’s built-in open() function
– Create one file object that can be utilized

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

• Tip: write function will not make newline automatically


• Programmers control where to make a new line
68
Read data from one file
Read data from the
Open one file Close the file
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

• Read the data line by line


• Obj.readline()
– Read one line data from
the file pointer and the file
pointer points to next line
Saul
David
Solomon
Mike
Tom
70
File Positions

• 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
• ……

Details can be found at: Python online tutorial

73
CSV File Reading and Writing

• Similar procedures with txt file reading and writing


• Different APIs (open(), csv.reader(), csvwriter.writerow(row))
• More materials can be found online
– Example: https://docs.python.org/2/library/csv.html

74
SUMMARY

• Advanced data structures in Python


– List, tuple, dictionary
• Iterations
– For and while loop
– Terminate one loop
• Files I/O operations
Python Project
• No need to use the provided sample dataset
• That is only one example
• You can choose other dataset with your own design features
• You can use any libraries to empower your application in
Python

76

You might also like