try
Clauseelse
Clausefinally
ClauseYou can connect to Gradescope to take weekly graded quiz today during the last 15 minutes of the class.
Once you start the quiz you have 15 minutes to finish it.
You can only take this quiz today.
There is not makeup for the weekly quiz because Gradescope does not permit it.
I have posted a solution to homework 8 here.
Let's take a look.
Homework 10 is posted here.
It is due this coming Sunday at 11:59 PM.
Are there any questions before I begin?
def random_integers_write(file, min, max, entries):
def average_from_file(file):
def divide_by_three_count(file):
>>> for = 5
File "<stdin>", line 1
for = 5
^
SyntaxError: invalid syntax
>>> name = "Glenn"
>>> print(nme)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'nme' is not defined
$ cat get_number_1.py
#! /usr/bin/python3
number = int(input("Number: ")
$ ./get_number_1.py
File "./get_number_1.py", line 6
^
SyntaxError: unexpected EOF while parsing
>>> for i in range(5):
... num = i * 2
... print(num)
File "<stdin>", line 3
print(num)
^
IndentationError: unindent does not match any outer indentation level
average = num_1 + num_2 / 2 print ('Average:', average)
$ ./file_open.py
Filename: xxxxxx
Traceback (most recent call last):
File "./file_open.py", line 6, in <module>
file = open(filename, "r")
FileNotFoundError: [Errno 2] No such file or directory: 'xxxxxx'
$ ./file_open.py
Filename: unreadable.txt
Traceback (most recent call last):
File "./file_open.py", line 6, in <module>
file = open(filename, "r")
PermissionError: [Errno 13] Permission denied: 'unreadable.txt'
$ ./int_request.py
Integer: five
Traceback (most recent call last):
File "./int_request.py", line 5, in <module>
number = int(input("Integer: "))
ValueError: invalid literal for int() with base 10: 'five'
>>> round("five")
Traceback (most recent call last):
File "<stdin>, line 1, in <module>
TypeError: type str doesn't define __round__ method
$ ./divide_two_numbers.py
Numerator: 5
Denominator: 0
Traceback (most recent call last):
File "./divide_two_numbers.py", line 7, in <module>
result = numerator / denominator
ZeroDivisionError: division by zero
try
/except
statement
try:
STATEMENT
STATEMENT
...
except:
STATEMENT
STATEMENT
...
try
code block
execute normally ...try
block
except
code block ...open
should always be
put it inside a try
/except
statement
$ cat open_file.py #! /usr/bin/python3 # demonstrates using a try/except statement # to catch exceptions encountered while # trying to open a file filename = input("Filename: ") try: file = open(filename, "r") for line in file: print(line.rstrip()) except: print("Could not open file", filename) $ ./open_file.py Filename: xxxx Could not open file xxxx
for
loopinput
to ask the user for a numberinput
returns a string so we need to use a conversion
function
int
and float
can cause a runtime errortry
/except
statement
while
loopdef get_integer(): while True: number = input("Integer: ") try: number = int(number) return number except: print(number, "cannot be converted into an integer")
try
Clauseopen
with a
string literal
for the filename
file = open("temps.txt", "r")
$ ./temps_average_2.py Filename: xxx Traceback (most recent call last): File "./temps_average_2.py", line 7, in <module> file = open(filename, 'r') FileNotFoundError: [Errno 2] No such file or directory: 'xxx'
open
in the
try
block
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 must work ...open
statement causes a run time error ...try
block
filename = input("Filename: ")
try:
file = open(filename, "r")
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)
except:
print("Cannot open", filename)
$ ./temps_average_4.py Filename: xxx Cannot open xxx
>>> 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 ...
>>> 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
def open_file_read(): while True: filename = input("Filename: ") try: file = open(filename, "r") return file except: print("Cannot open", filename)
$ ./file_open_2.py
Filename: xxx
Cannot open xxx
Filename:
try
/except
statement
try:
STATEMENT
...
except:
STATEMENT
...
except
clauses for each type of
exception object
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)
$ ./file_open_3.py Filename: xxx Cannot find xxx Filename: unreadable.txt You do not have permission to read unreadable.txt Filename:
You do not have permission to read unreadable.txt
>>> open("xxx", "r")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'xxx'
except EXCEPTION_TYPE as VARIABLE:
def open_file_read():
while True:
filename = input("Filename: ")
try:
file = open(filename, "r")
return file
except FileNotFoundError as err:
print(err)
except PermissionError as err:
print(err)
$ ./file_open_4.py Filename: xxx [Errno 2] No such file or directory: 'xxx' Filename: unreadable.txt [Errno 13] Permission denied: 'unreadable.txt' Filename:The text in blue is user input
except
block are called an
exception handler
else
Clausetry
/except
statement can also have an
else
clause
try
block are executed ...else
clause runs if there is no runtime erroropen
command fails
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)
for
loop cannot work
try
code block
try:
file = open(filename, "r")
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)
except:
print("Cannot open", filename)
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)
try
code block should only contain code that
could cause a runtime error
try
clausetry
clauseexcept
clauseelse
clausefinally
Clausetry
/except
statement
finally:
STATEMENT
....
finally
clause will always be executedfinally
clause allows you to clean up any lose ends