>>> data = "this is not an integer" >>> "%d" % data Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: int argument required >>> "%d %d" % (1, 2, 3) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: not all arguments converted during string formatting
>>> f = open('bee.tsv')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'bee.tsv'
try statement
try statement is:
try: statements that may throw an exception except exception_type1 [, exception_data1]: recovery statements for exception_type1 errors except exception_type2 [, exception_data2]: recovery statements for exception_type2 errors else: statements executed if no exceptions thrown finally: statements always executed whether exception thrown or not
except
or finally clauseelse and finally clauses are optionaltry Statementstry clause are first executedelse clause are executedexcept
clauses and the corresponding recovery statements
are executedexcept
clause is found, the exception is handled "normally"
(as if the statements were not in a try statement)
and neither else nor any except clause statements
are executedtry Statements (cont.)try may be function calls
try statementstry Statements (cont.)finally clause are always executed
finally
is executed after the else clause
(if there is one)except clause, the statements are
executed after the except clausefinally
statements executed, and the exception rethrown
try:
f = open(“bee.tsv”)
except IOError:
f = open(“bee.txt”)
… # Regenerate data directly from bee.txt
f.close() # closes bee.txt file
else:
… # Read cached data from bee.tsv
f.close() # closes bee.tsv fileIOError
exception will still be thrown because the open
call in the recovery statements is not in a
try statement
f.close() in a finally
clause because we may not have opened the file
successfully (f is not defined)with statement):
try:
with open("bee.tsv") as f:
… # Read cached data from bee.tsv
except IOError:
try:
with open(“bee.txt”) as f:
… # Regenerate data directly from bee.txt
except IOError:
… # ComplainIOError when we try to open either filetry statements can be used in
anticipation of rare or unusual conditionsd is a histogram and we want to update
the count for some keys
# Approach A: LBYL - Look Before You Leap
if my_key in d: # Check first
d[my_key] += 1 # Guaranteed safe
else:
d[my_key] = 1 # First time, rare case
# Approach B: EAFP - Easier to Ask for Forgiveness than Permission
try:
d[my_key] += 1 # Just do it
except KeyError:
d[my_key] = 1 # First time, rare case
except clauses are generally considered
more unusual than else clausestry Statementsexcept: clause
(without specifying exception types) in a
try statement
except clause matches any exception typetry
statements that may properly recover from specific
types of errors
def linecount(filename):
count = 0
for line in open(filename):
count += 1
return count
print(linecount(“wc.py”))
>>> import wc
7
>>> print(wc)
<module 'wc' from 'wc.py'>
>>> import wc
>>> wc.linecount("wc.py")
7
>>> wc.linecount("bee.tsv")
75
>>> import 0wc
File "", line 1
import 0wc
^
SyntaxError: invalid syntax
import wc the first time:
wc, which references the module object,
for accessing the contents of the moduleimport wc again only does only the very
last step, i.e., the code in wc.py is not
executed more than oncedef linecount(…) statement in wc.py
creates a function named linecount
in the wc modulewc.linecount__name__ which contains the name of the module
wc.__name__ has value
"wc"import wc creates two things:
__name__ attribute in module.zzz = wc and refer to
zzz.linecount, but the module name
is still wc (as witnessed by
zzz.__name__)wc (from the
import) and zzz (from the assignment)
that refer to the same module, wcimport statement
import module as myname
import module
except the variable created in the importing
module is named myname instead of
modulefrom module import name
import statement is executedfrom module import *
_) in the imported module,
a corresponding variable of the same name
is created in the importing module# Using gmod.print_var >>> var = 20 >>> import gmod 10 >>> gmod.print_var() 10 >>> from gmod import print_var >>> print_var() 10
# Contents of gmod.py var = 10 def print_var(): print(var) print_var()
sys.path or PYTHONPATH
(see notes from
previous
week)shiftread_grams in all of them?shift so that it is not duplicated)shift functionread_grams returns two dictionaries with specific
key and value types,
e.g., dictionary values are redundant list of wordsnext_word = random.choice(m2[prefix])
prefix
in dictionary m2prefix using
bigram-suffix mapping m2def random_suffix(m, prefix): return random.choice(m[prefix])
next_word = random_suffix(m2, prefix)
next_word = random.choice(m2[prefix])
random_suffix is implemented
(e.g., bias the word choice by the length of
the word) without changing any other code in the programclass syntax that allows us to
group data together and access them by name
class ClassName: """Documentation string""" Instance1 = ClassName() instance1.first_attribute = first_value print(instance1.first_attribute) Instance2 = ClassName() instance2.second_attribute = second_value print(instance2.second_attribute)