Python Lecture 2
Python Lecture 2
• Today:
• Exception handling
Odds and ends
• List slice notation
• Multiline strings
• Docstrings
List slices (1)
a = [1, 2, 3, 4, 5]
print a[0] # 1
print a[4] # 5
print a[5] # error!
a[0] = 42
List slices (2)
a = [1, 2, 3, 4, 5]
a[1:3] # [2, 3] (new list)
a[:] # copy of a
a[-1] # last element of a
a[:-1] # all but last
a[1:] # all but first
List slices (3)
a = [1, 2, 3, 4, 5]
a[1:3] # [2, 3] (new list)
a[1:3] = [20, 30]
print a
[1, 20, 30, 4, 5]
List slices (4)
a = [1, 2, 3, 4, 5]
a[1:3] = [20, 30, 40]
print a
[1, 20, 30, 40, 4, 5]
Multiline strings
s = "this is a string"
s2 = 'this is too'
s3 = "so 'is' this"
sl = """this is a
multiline string."""
sl2 = '''this is also a
multiline string'''
Docstrings (1)
• Multiline strings most useful for
documentation strings aka "docstrings":
def foo(x):
"""Comment stating the purpose of
the function 'foo'. """
# code...
def some_function():
if something_bad_happens():
# SomeException leaves function
raise SomeException("bad!")
else:
# do the normal thing
Raising exceptions (2)
def some_other_function():
try:
some_function()
except SomeException, e:
# e gets the exception that was caught
print e.msg
Summing up