try
Clauseelse
Clausefinally
Clauselist
Functionfor
Loop with Listslen
Functiontry
Clauseopen
statement
in the try
block of a try
/except
statement
try
/except
statement
you will get an error
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
open
statement working try
/except
statement
>>> 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'
>>> number = float(input("Number: ")) Number: five File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'five' >>> 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
you get an ImportError object
>>> 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, one for each exception type
try:
STATEMENT
...
except EXCEPTION_TYPE_1:
STATEMENT
...
except EXCEPTION_TYPE_2:
STATEMENT
...
...
def open_file_reading():
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
clausetry
block code does not
cause a runtime error
try
clause to
work inside an else
clause
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 no matter
what happens when the script is run
>>> scores = '100 85 76 60 78 65 55 88'
score_1, score_2, score_3, score_4, score_5, score_6, score_7, score_8 = scores.split()
total = score_1, score_2, score_3, score_4, score_5, score_6, score_7, score_8
>>> 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 things into a listlist
on strings
>>> name = "Glenn" >>> characters = list(name) >>> characters ['G', 'l', 'e', 'n', 'n']
>>> name.upper() 'GLENN' >>> name.lower() 'glenn'
>>> name = "Glenn" + " " + "Hoffman" >>> name 'Glenn Hoffman'
>>> n1 = [1,2,3] >>> n2 = [4,5,6] >>> n1 + n2 [1, 2, 3, 4, 5, 6]
>>> n1 + name
Traceback (most recent call last):
File "<stdin>", line 1, in Monday
TypeError: can only concatenate list (not "str") to list
>>> n2 - n1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
>>> n1 / n2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'list' and 'list'
>>> zeros = [0] * 5 >>> zeros [0, 0, 0, 0, 0] >>> numbers = [1, 2, 3] * 3 >>> numbers [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> "Go " * 3 'Go Go Go '
for
Loop with Listsfor
loop will work with a list
>>> 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 >>>
for
loop but it is very cumbersome
>>> even_numbers = [2, 4, 6, 8, 10] >>> count = 0 >>> for n in even_numbers: ... count += 1 ... if count == 3: ... third_element = n ... >>> third_element 6
>>> even_numbers[0] 2 >>> even_numbers[1] 4 >>> even_numbers[2] 6
IndexError
exception
>>> even_numbers[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
len
Functionlen
will return the length of any sequence
>>> even_numbers = [2, 4, 6, 8, 10] >>> len(even_numbers) 5 >>> len("foo")
len
with range
to iterate through a list
for i in range(len(even_numbers)): ... print(even_numbers[i]) ... 2 4 6 8 10
range
works the way it doesnumbers = [1, 4, 6, 8]
>>> numbers[0] = 2 >>> numbers [2, 4, 6, 8]
for
loop to change every element inside a list
>>> for i in range(len(numbers)): ... numbers[i] += 1 ... >>> numbers [3, 5, 7, 9]
Contribute to society and to human well-being, acknowledging that all people are stakeholders in computing
Avoid harm