Text
stringlengths
1
9.41k
Accordingly, there aren’t many cases where we’d even want to handle these exceptions. Sometimes we want to handle TypeError or IndexError.
It’s very often the case that we want to handle ValueError or ZeroDivisionError. It’s almost always the case that we want to handle FileNotFoundError.
Much of this depends on context, and there’s a little art in determining which exceptions are handled, and how they should be handled. 293 ----- **Learning objectives** - You will understand why many of the Python exceptions are raised. - You will learn how to deal with exceptions when they are raised, and ho...
Exceptions occur when something goes wrong.
We refer to this as raising an exception. Exceptions may be raised by the Python interpreter or by built-in functions or by methods provided by Python modules.
You may even raise exceptions in your own code (but we’ll get to that later). Exceptions include information about the type of exception which has been raised, and where in the code the exception occurred.
Sometimes, quite a bit of information is provided by the exception.
In general, a good approach is to start at the last few lines of the exception message, and work backward if necessary to see what went wrong. There are many types of built-in exceptions in Python.
Here are a few that you’re likely to have seen before. ``` SyntaxError ``` When a module is executed or imported, Python will read the file, and try parsing the file.
If, during this process, the parser encounters a syntax error, a SyntaxError exception is raised.
SyntaxError can also be raised when invalid syntax is used in the Python shell. ``` >>> # if requires a condition and colon >>> if File "<stdin>", line 1 if ^ SyntaxError: invalid syntax ``` Here you see the exception includes information about the error and where the error occurred.
The ^ is used to point to a portion of code where the error occurred. ----- ``` IndentationError IndentationError is a subtype of SyntaxError.
Recall that indentation ``` is significant in Python—we use it to structure branches, loops, and functions.
So IndentationError occurs when Python encounters a syntax error that it attributes to invalid indentation. ``` if True: x = 1 # This should be indented! File "<stdin>", line 2 x = 1 # should be indented ^ IndentationError: expected an indented block after 'if' statement on line 1 ``` Again, almos...
Here Python is informing us that it was expecting an indented block of code immediately following an if statement. ``` AttributeError ``` There are several ways an AttributeError can be raised.
You may have encountered an AttributeError by misspelling the name of a method in a module you’ve imported. ``` >>> import math >>> math.foo # There is no such method or constant in math Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'math' has no attribute 'foo...
An ``` AttributeError is only related to the availability of attributes and not ``` violations of the Python syntax rules. ``` NameError ``` A NameError is raised when Python cannot find an identifier.
For example, if you were to try to perform a calculation with some variable x without previously having assigned a value to x. ``` >>> x + 1 # Without having previously assigned a value to x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined ``` Any attem...
This presumes, of course, that the index is valid—that is, there is an element at that index.
If you try to access an element of a sequence by its index, and there is no index, Python will raise an IndexError. ``` >>> lst = [] >>> lst[2] # There is no element at index 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range ``` This (above) fails b...
Hence, 2 is an invalid index and an IndexError is raised. Here’s another example: ``` >>> alphabet = 'abcdefghijklmnopqrstuvwxyz' >>> alphabet[26] # Python is 0-indexed so z has index 25 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range TypeError ``...
For example, sequence indices—for lists, tuples, strings—must be integers.
If we try using a float or str as an index, Python will raise a TypeError. ``` >>> lst = [6, 5, 4, 3, 2] >>> lst['foo'] # Can't use a string as an index Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers or slices, not str >>> lst[1.0] # Can't us...
For example, we cannot concatenate an int to a str or add a str to an int. ``` >>> 'foo' + 1 # Try concatenating 1 with 'foo' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str >>> 1 + 'foo' # Try adding 'foo' to 1 Traceback (most r...
We cannot calculate the sum of any list or tuple which contains a string. ``` >>> sum('Add me up!') # Can't sum a string Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> sum(1) # Python sum() requires an iterable of numer...
For example, math.sqrt(x) will raise a ``` ValueError if we try to take the square root of a negative number. >>> import math >>> math.sqrt(-1) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: math domain error ``` Note that dividing by zero is considered an arithmetic erro...
If we try to, Python will raise a ZeroDivisionError.
Note that this occurs with floor division and modulus as well (as they depend on division). ``` >>> 10 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero >>> 10 % 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDi...
There are many ways this can go wrong, but one common issue is FileNotFoundError. This exception is raised when Python cannot find the specified file.
The file may not exist, may be in the wrong directory, or may be named incorrectly. ``` open('non-existent file') Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: 'non-existent file' ###### 15.2 Handling exceptions ``` So far, ...
What this means is that when an exception is raised, a specific block of code can be executed to deal with the problem. For this we have, minimally, a try/except compound statement.
This involves creating two blocks of code: a try block and an exception handler—an except block. The code in the try block is code where we want to guard against unhandled exceptions.
A try block is followed by an except block.
The ----- ``` except block specifies the type of exception we wish to handle, and code ``` for handling the exception. ###### Input validation with try/except Here’s an example of input validation using try/except.
Let’s say we want a positive integer as input.
We’ve seen how to validate input in a ``` while loop. while True: n = int(input("Please enter a positive integer: ")) if n > 0: break ``` This ensures that if the user enters an integer that’s less than one, that they’ll be prompted again until they supply a positive integer.
But what happens if the naughty user enters something that cannot be converted to an integer? ``` Please enter a positive integer: cheese Traceback (most recent call last): File "/.../code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 2, in <module> ValueError: invalid literal fo...
We put the code that could result in a ValueError in a try block, and then provide an exception handler in an except block. Here’s how we’d do it. ``` while True: try: user_input = input("Enter a positive integer: ") n = int(user_input) if n > 0: break except ValueError: p...
Now mischief (or failure to read instructions) is handled gracefully. ###### Getting an index with try/except Earlier, we saw that .index() will raise a ValueError exception if the argument passed to the .index() method is not found in the underlying sequence. ``` >>> lst = ['apple', 'boat', 'cat', 'drama'] >>> l...
Sometimes these two approaches are referred to as “look before you leap” (LBYL) and “it’s easier to ask forgiveness than it is to ask for permission” (EAFP).
Python favors the latter approach. Why is this the case?
Usually, EAFP makes your code more readable, and there’s no guarantee that the programmer can anticipate and write all the necessary checks to ensure an operation will be successful. ----- In this example, it’s a bit of a toss up.
We could write: ``` if s in lst: print(f'The index of "{s}" in {lst} is {lst.index(s)}.') else: print(f'"{s}" was not found in {lst}.') ``` Or we could write (as we did earlier): ``` try: print(f'The index of "{s}" in {lst} is {lst.index(s)}.') except ValueError: print(f'"{s}" was not found in ...
Catching and handling these exceptions can hide defects that should be corrected. - Use separate except blocks to handle different kinds of exceptions. Don’t: - Write one handler for different exception types. - Wrap all your code in one big try block. - Use exception handling to hide programming errors. ...
SyntaxError b. IndentationError c. IndexError d. NameError e. TypeError f. AttributeError g. ZeroDivisionError h.
FileNotFoundError ###### Exercise 02 Now write a try/except for the following exceptions, starting with code you wrote for exercise 01. a. ValueError b. ZeroDivisionError c.
FileNotFoundError ###### Exercise 03 ``` SyntaxError and IndentationError should always be fixed in your code. ``` Under normal circumstances, these can’t be handled.
NameError and ----- ``` AttributeError almost always arise from programming defects.
There’s ``` almost never any reason to write try/except for these. Fix the code you wrote in exercise 01, for the following: a. SyntaxError b. IndentationError c. AttributeError d.
NameError ###### Exercise 04 Usually, (but not always) IndexError and TypeError are due to programming defects. Take a look at the code you wrote to cause these errors in exercise 01.
Does what you wrote constitute a programming defect?
If so, fix it. If you believe the code you wrote constitutes a legitimate case for try/except, write try/except for each of these. ----- ----- #### Chapter 16 ### Dictionaries Dictionaries are ubiquitous, no doubt due to their usefulness and flexibility.
Dictionaries store information in key/value pairs—we look up a value in a dictionary by its key.
In this chapter we’ll learn about dictionaries: how to create them, modify them, iterate over them and so on. **Learning objectives** - You will learn how to create a dictionary. - You will understand that dictionaries are mutable, meaning that their contents may change. - You will learn how to access individ...
We’ve also seen how to access individual elements within a list, tuple, or string by the element’s index. 305 ----- ``` >>> lst = ['rossi', 'agostini', 'marquez', 'doohan', 'lorenzo'] >>> lst[0] 'rossi' >>> lst[2] 'marquez' >>> t = ('hearts', 'clubs', 'diamonds', 'spades') >>> t[1] 'clubs' ``` This...
Imagine if such a dictionary used numeric indices to look up words. Let’s say we wanted to look up the word “pianist.” How would we know its index? We’d have to hunt through the dictionary to find it.
Even if all the words were in lexicographic order, it would still be a nuisance having to find a word this way. The good news is that dictionaries don’t work that way.
We can look up the meaning of the word by finding the word itself.
This is the basic idea of dictionaries in Python. A Python dictionary, simply put, is a data structure which associates _keys and values.
In the case of a conventional dictionary, each word is a_ _key, and the associated definition or definitions are the values._ Here’s how the entry for “pianist” appears in my dictionary:[1] _pianist n.
a person who plays the piano, esp._ a skilled or professional performer Here pianist is the key, and the rest is the value.
We can write this, with some liberty, as a Python dictionary, thus: ``` >>> d = {'pianist': "a person who plays the piano, " \ ... "esp.
a skilled or professional performer"} ``` The entries of a dictionary appear within braces {}.
The key/value pairs are separated by a colon, thus: <key>: <value>, where <key> is a valid key, and <value> is a valid value. We can look up values in a dictionary by their key.
The syntax is similar to accessing elements in a list or tuple by their indices. ``` >>> d['pianist'] 'a person who plays the piano, esp.
a skilled or professional performer' ``` Like lists, dictionaries are mutable. Let’s add a few more words to our dictionary.
To add a new entry to a dictionary, we can use this approach: 1Webster’s New World Dictionary of the American Language, Second College Edition. ----- ``` >>> d['cicada'] = "any of a family of large flylike " \ ...
"insects with transparent wings" >>> d['proclivity'] = "a natural or habitual tendency or " \ ... "inclination, esp. toward something " \ ...
"discreditable" >>> d['tern'] = "any of several sea birds, related to the " \ ... "gulls, but smaller, with a more slender " \ ...
"body and beak, and a deeply forked tail" >>> d['firewood'] = "wood used as fuel" >>> d['holophytic'] = "obtaining nutrition by photosynthesis, " \ ...
"as do green plants and some bacteria" ``` Now let’s inspect our dictionary. ``` >>> d {'pianist': 'a person who plays the piano, esp.
a skilled or professional performer', 'cicada': 'any of a family of large flylike insects with transparent wings', 'proclivity': 'a natural or habitual tendency or inclination, esp.
toward something discreditable', 'tern': 'any of several sea birds, related to the gulls, but smaller, with a more slender body and beak, and a deeply forked tail', 'firewood': 'wood used as fuel', 'holophytic': 'obtaining nutrition by photosynthesis, as do green plants and some bacteria'} ``` We see that ou...
a skilled or professional performer' 'cicada' 'any of a family of large flylike insects with transparent wings' 'proclivity' 'a natural or habitual tendency or inclination, esp.
toward something discreditable' 'tern' 'any of several sea birds, related to the gulls, but smaller, with a more slender body and beak, and a deeply forked tail' 'firewood' 'wood used as fuel' 'holophytic' 'obtaining nutrition by photosynthesis, as do green plants and some bacteria' ``` W...
'Mali': 'Bamako', ... 'Argentina': 'Buenos Aires', ... 'Thailand': 'Bangkok', ...
'Australia': 'Sydney'} # oops! >>> d['Australia'] = 'Canberra' # fixed! ``` So far, in the examples above, keys and values have been strings.
But this needn’t be the case. There are constraints on the kinds of things we can use as keys, but almost anything can be used as a value. Here are some examples of valid keys: ``` >>> d = {(1, 2): 'My key is the tuple (1, 2)', 100: 'My key is the integer 100', 'football': 'My key is the string "footbal...
'major': 'computer science', ... 'gpa': 3.14}, ... 'epickle': {'name': 'Edwina Pickle', ... 'major': 'biomedical engineering', ... 'gpa': 3.71}, ...
'aftoure': {'name': 'Ali Farka Touré', ... 'major': 'music', ... 'gpa': 4.00}} >>> students['aftoure']['major'] 'music' >>> recipes = {'bolognese': ['beef', 'onion', 'sweet pepper', ...
'celery', 'parsley', 'white wine', ... 'olive oil', 'garlic', 'milk', ... 'black pepper', 'basil', 'salt'], ... 'french toast': ['baguette', 'egg', 'milk', ... 'butter', 'cinnamon', ...
'maple syrup'], ``` ----- ``` ... 'fritters': ['potatoes', 'red onion', 'carrot', ... 'red onion', 'garlic', 'flour', ... 'paprika', 'marjoram', 'salt', ...
'black pepper', 'canola oil']} >>> recipes['french toast'] ['baguette', 'egg', 'milk', 'butter', 'cinnamon', 'maple syrup'] >>> recipes['french toast'][-1] 'maple syrup' >>> coordinates = {'Northampton': (42.5364, -70.9857), ...
'Kokomo': (40.4812, -86.1418), ... 'Boca Raton': (26.3760, -80.1223), ... 'Sausalito': (37.8658, -122.4980), ... 'Amarillo': (35.1991, -101.8452), ...
'Fargo': (46.8771, -96.7898)} >>> lat, lon = coordinates['Fargo'] # tuple unpacking >>> lat 46.8771 >>> lon -96.7898 ###### Restrictions on keys ``` Keys in a dictionary must be hashable.
In order for an object to be hashable, it must be immutable, or if it is an immutable container of other objects (for example, a tuple) then all the objects contained must also be immutable.
Valid keys include objects of type int, float (OK, but a little strange), str, bool (also OK, but use cases are limited).
Tuples can also serve as keys as long as they do not contain any mutable objects. ``` >>> d = {0: 'Alexei Fyodorovich', 1: 'Dmitri Fyodorovich', ...
2: 'Ivan Fyodorovich', 3: 'Fyodor Pavlovich', ... 4: 'Agrafena Alexandrovna', 5: 'Pavel Fyodorovich', ...
6: 'Zosima', 7: 'Katerina Ivanovna'} >>> d = {True: 'if porcupines are blue, then the sky is pink', ...
False: 'chunky monkey is the best ice cream'} >>> d = {'Phelps': 23, 'Latynina': 9, 'Nurmi': 9, 'Spitz': 9, ...
'Lewis': 9, 'Bjørgen': 8} ``` However, these are not permitted: ----- ``` >>> d = {['hello']: 'goodbye'} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' >>> d = {(0, [1]): 'foo'} Traceback (most recent call last): File "<stdin>", line 1, in <...
'willard': 'vermont', 'simone': 'connecticut'} >>> 'wanda' in d True >>> 'dobbie' in d False >>> 'dobbie' not in d True ###### 16.2 Iterating over dictionaries ``` If we iterate over a dictionary as we do with a list, this yields the dictionary’s keys. ``` >>> furniture = {'living room': ['armchair', 's...
'bedroom': ['bed', 'nightstand', 'dresser'], ... 'office': ['desk', 'chair', 'cabinet']} ... >>> for x in furniture: ...
print(x) ... living room bedroom office ``` Usually, when iterating over a dictionary we use dictionary view ob_jects.
These objects provide a dynamic view into a dictionary’s keys,_ values, or entries. ----- Dictionaries have three different view objects: items, keys, and values. Dictionaries have methods that return these view objects: - dict.keys() which provides a view of a dictionary’s keys, - dict.values() which provides...
'bedroom': ['bed', 'nightstand', 'dresser'], ... 'office': ['desk', 'chair', 'cabinet']} >>> for key in furniture.keys(): ...
print(key) ... living room bedroom office ``` Note that it’s common to exclude .keys() if it’s keys you want, since the default behavior is to iterate over keys (as shown in the previous example). ###### Iterating over the values of a dictionary ``` >>> for value in furniture.values(): ...
print(value) ... ['armchair', 'sofa', 'table'] ['bed', 'nightstand', 'dresser'] ['desk', 'chair', 'cabinet'] Iterating over the items of a dictionary >>> for item in furniture.items(): ...
print(item) ... ('living room', ['armchair', 'sofa', 'table']) ('bedroom', ['bed', 'nightstand', 'dresser']) ('office', ['desk', 'chair', 'cabinet']) ``` ----- ###### Iterating over the items of a dictionary using tuple unpacking ``` >>> for key, value in furniture.items(): ...