try
Clauseelse
Clausefinally
Clauselist
Functionfor
Loop with Listslen
FunctionI have posted homework 10 here.
It is due this coming Sunday at 11:59 PM.
If you have the textbook you should read Chapter 7, Lists and Tuples, from Starting Out with Python.
The answers to Quiz 8 are posted here.
Let's take a look.
Are there any questions before I begin?
chmod 755 FILENAME
#! /usr/bin/python3
try
Clauseopen
must always be put inside the
try
block ...
try
/except
statement open
creates an exception ...except
clause catches it ...try/except
statement ...
filename = input("Filename: ") try: file = open(filename, "r") except: print("Cannot open", filename) count = 0 total = 0 for line in file: count += 1 date, temp = line.split() temp = int(temp) total += temp average = round(total/count, 2) print("Average:", average) $ ./temps_average_3.py Filename: xxx Cannot open xxx Traceback (most recent call last): File "./temps_average_3.py", line 15, in <module> for line in file: NameError: name 'file' is not defined
try
block
>>> open("xxx.txt","r")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'xxx.txt'
file = open("test.txt","r")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
PermissionError: [Errno 13] Permission denied: 'test.txt'
>>> round("foo") Number: foo File "<stdin>", line 1, in <module> TypeError: type str doesn't define __round__ method
>>> number = float(input("Number: ")) Number: 5..4 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: could not convert string to float: '5..4'
import
a module that doesn't exist ...
>>> import foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'foo'
>>> print(5/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
except
clauses in a
try
/except
statement
try:
STATEMENT
...
except EXCEPTION_TYPE_1:
STATEMENT
...
except EXCEPTION_TYPE_2:
STATEMENT
...
...
def open_file_read():
while True:
filename = input("Filename: ")
try:
file = open(filename, "r")
return file
except FileNotFoundError:
print("Cannot find", filename)
except PermissionError:
print("You do not have permission to read", filename)
else
Clausetry
/except
statement can also have an
else
clause
else
block runs if there is no runtime errortry
block
try
block statements
working properly ...
else
block
try:
file = open(filename, "r")
except:
print("Cannot open", filename)
else:
count = 0
total = 0
for line in file:
count += 1
date, temp = line.split()
temp = int(temp)
total += temp
average = round(total/count, 2)
print("Average:", average)
finally
Clausetry
/except
statement
finally:
STATEMENT
....
finally
clause will always be executedfinally
clause allows you to clean up any lose ends ...>>> even_numbers = [2, 4, 6, 8, 10] >>> even_numbers [2, 4, 6, 8, 10]
>>> courses = ["IT 244", "IT 341", "IT 116"] >>> courses ['IT 244', 'IT 341', 'IT 116']
float
values
>>> expenses = [37.55, 21.25, 32.00] >>> expenses [37.55, 21.25, 32.0]
>>> results = [True, False, True] >>>results [True, False, True]
>>> python_class = ["IT 116", 32, "McCormack 2-621"] >>> python_class
>>> lists = [ numbers, results, expenses] >>> lists [[5, 8, 2, 9, 7, 6, 3], [True, False, True], [37.55, 21.25, 32.0]]
list
Functionlist
list
is a conversion function just like int
and
str
list
turns objects that are collections of values into a listlist
on strings
>>> name = "Glenn" >>> characters = list(name) >>> characters ['G', 'l', 'e, 'n', 'n']
>>> name.upper() 'GLENN' >>> name.lower() 'glenn'
for
Loop with Listsfor
loops will work with any sequence object>>> numbers = [1, 2, 3, 4, 5] >>> for n in numbers: ... print(n) ... 1 2 3 4 5
for
loop with strings
>>> team = "Red Sox" >>> for char in team: ... print(char) ... R e d S o x >>>
>>> new_list = [] >>> new_list []
len
Functionlen
will return the length of any sequence
>>> even_numbers = [2, 4, 6, 8, 10] >>> len(even_numbers) 5 >>> len("foo") 3
min
and max
...
min
returns the smallest value in a list
>>> l6 [1, 4, 5, 6] >>> min(l6) 1
max
returns the largest
max(l6) 6
file = open("numbs.txt","r") numbs = [] for line in file: num = int(line) numbs.append(num) print(numbs)
$ ./list_from_file.py [46, 19, 35, 43, 35, 33, 42]