Lecture 11
Lecture 11
Review: Dictionary
key-value pair
Review
a sequence of values
>>> t1 = ()
>>> t2 = (1)
(1,)
Tuple Assignment
a, b = 2, 3
Return values
def divmod(a,b):
return a//b, a%b
Dictionaries & Tuples
>>> t = d.items()
[(‘b’,18),(‘a’,12)]
Looping
Main
Memory
Persistence?
Others: Persistent
Web servers
Operating Systems
File
filename is a string
mode is optional and should be 'r' if we are
planning reading the file and 'w' if we are
going to write to the file
returns a handle use to manipulate the file
open modes
r
w
a
rb
wb
Text file processing
of lines
A text file has newlines at the end of each
line
File handle as a sequence
A file handle open for read can be treated as a
sequence of strings where each line in the file
is a string in the sequence
We can use the for statement to iterate through
a sequence
Remember - a sequence is an ordered set
File handle as a sequence
or TRACEBACK
Exceptions
success_failure_ratio = num_success/num_failure
print(‘success/failure = ’, success_failure_ratio)
success_failure_ratio = num_success/num_failure
print(‘success/failure = ’, success_failure_ratio)
except IOError:
ZeroDivisionError:
print(‘Division by zero’)
Back to opening file
try:
open(file_name, ‘r’)
except IOError:
print(‘File’, file_name, ‘does not exist’)
The try ... except Clause
try:
<body>
except <exceptionType1>:
<handle1>
except <excetpionType2> as e:
<handle2>
finally:
<finalize_process>
Best practices
Defensive programming
x,y = eval(input(‘Enter integers x,y for the ratio x/y: ’)
try:
print(‘x,y = ’, x/y)
except ZeroDivisionError:
print(‘File’, file_name, ‘does not exist’)
except:
raise ValueError(‘Bad Arguments’)
Defensive programming
x,y = eval(input(‘Enter x,y for the ratio x/y: ’)
assert type(x)==int and type(y) == int
try:
print(‘x,y = ’, x/y)
except ZeroDivisionError:
print(‘File’, file_name, ‘does not exist’)
Unit testing
if __name__ == ‘__main__’:
test()