

Appendix C. Answers to the Practice Questions
This appendix contains the answers to the practice problems at the end of each chapter. I highly recommend that you take the time to work through these problems. Programming is more than memorizing syntax and a list of function names. As when learning a foreign language, the more practice you put into it, the more you will get out of it. There are many websites with practice programming problems as well. You can find a list of these at http://nostarch.com/automatestuff/.
Chapter 1
-
The operators are
+,-,*, and/. The values are'hello',-88.8, and5. -
The string is
'spam'; the variable isspam. Strings always start and end with quotes. -
The three data types introduced in this chapter are integers, floating-point numbers, and strings.
-
An expression is a combination of values and operators. All expressions evaluate (that is, reduce) to a single value.
-
An expression evaluates to a single value. A statement does not.
-
The
baconvariable is set to20. Thebacon + 1expression does not reassign the value inbacon(that would need an assignment statement:bacon = bacon + 1). -
Both expressions evaluate to the string
'spamspamspam'. -
Variable names cannot begin with a number.
-
The
int(),float(), andstr() functions will evaluate to the integer, floating-point number, and string versions of the value passed to them. -
The expression causes an error because
99is an integer, and only strings can be concatenated to other strings with the+operator. The correct way isI have eaten ' + str(99) + ' burritos.'.
Chapter 2
-
TrueandFalse, using capital T and F, with the rest of the word in lowercase -
and,or, andnot -
True and TrueisTrue.True and FalseisFalse.False and TrueisFalse.False and FalseisFalse.True or TrueisTrue.True or FalseisTrue.False or TrueisTrue.False or FalseisFalse.not TrueisFalse.not FalseisTrue. -
False False True False False True
-
==,!=,<,>,<=, and>=. -
==is the equal to operator that compares two values and evaluates to a Boolean, while=is the assignment operator that stores a value in a variable. -
A condition is an expression used in a flow control statement that evaluates to a Boolean value.
-
The three blocks are everything inside the
ifstatement and the linesprint('bacon')andprint('ham').print('eggs') if spam > 5: print('bacon') else: print('ham') print('spam') -
The code:
if spam == 1: print('Hello') elif spam == 2: print('Howdy') else: print('Greetings!') -
Press CTRL-C to stop a program stuck in an infinite loop.
-
The
breakstatement will move the execution outside and just after a loop. Thecontinuestatement will move the execution to the start of the loop. -
They all do the same thing. The
range(10)call ranges from0up to (but not including)10,range(0, 10)explicitly tells the loop to start at0, andrange(0, 10, 1)explicitly tells the loop to increase the variable by1on each iteration. -
The code:
for i in range(1, 11): print(i)and:
i = 1 while i <= 10: print(i) i = i + 1 -
This function can be called with
spam.bacon().
Chapter 3
-
Functions reduce the need for duplicate code. This makes programs shorter, easier to read, and easier to update.
-
The code in a function executes when the function is called, not when the function is defined.
-
The
defstatement defines (that is, creates) a function. -
A function consists of the
defstatement and the code in itsdefclause.A function call is what moves the program execution into the function, and the function call evaluates to the function’s return value.
-
There is one global scope, and a local scope is created whenever a function is called.
-
When a function returns, the local scope is destroyed, and all the variables in it are forgotten.
-
A return value is the value that a function call evaluates to. Like any value, a return value can be used as part of an expression.
-
If there is no return statement for a function, its return value is
None. -
A
globalstatement will force a variable in a function to refer to the global variable. -
The data type of
NoneisNoneType. -
That
importstatement imports a module namedareallyourpetsnamederic. (This isn’t a real Python module, by the way.) -
This function can be called with
spam.bacon(). -
Place the line of code that might cause an error in a
tryclause. -
The code that could potentially cause an error goes in the
tryclause.The code that executes if an error happens goes in the
exceptclause.
Chapter 4
-
The empty list value, which is a list value that contains no items. This is similar to how
''is the empty string value. -
spam[2] = 'hello'(Notice that the third value in a list is at index2because the first index is0.) -
'd'(Note that'3' * 2is the string'33', which is passed toint()before being divided by11. This eventually evaluates to3. Expressions can be used wherever values are used.) -
'd'(Negative indexes count from the end.) -
['a', 'b'] -
1 -
[3.14, 'cat', 11, 'cat', True, 99] -
[3.14, 11, 'cat', True] -
The operator for list concatenation is
+, while the operator for replication is*. (This is the same as for strings.) -
While
append()will add values only to the end of a list,insert()can add them anywhere in the list. -
The
delstatement and theremove()list method are two ways to remove values from a list. -
Both lists and strings can be passed to
len(), have indexes and slices, be used inforloops, be concatenated or replicated, and be used with theinandnot inoperators. -
Lists are mutable; they can have values added, removed, or changed. Tuples are immutable; they cannot be changed at all. Also, tuples are written using parentheses,
(and), while lists use the square brackets,[and]. -
(42,)(The trailing comma is mandatory.) -
The
tuple()andlist()functions, respectively -
They contain references to list values.
-
The
copy.copy()function will do a shallow copy of a list, while thecopy.deepcopy()function will do a deep copy of a list. That is, onlycopy.deepcopy()will duplicate any lists inside the list.
Chapter 5
-
Two curly brackets:
{} -
{'foo': 42} -
The items stored in a dictionary are unordered, while the items in a list are ordered.
-
You get a
KeyErrorerror. -
There is no difference. The
inoperator checks whether a value exists as a key in the dictionary. -
'cat' in spamchecks whether there is a'cat'key in the dictionary, while'cat' in spam.values()checks whether there is a value'cat'for one of the keys inspam. -
spam.setdefault('color', 'black') -
pprint.pprint()
Chapter 6
-
Escape characters represent characters in string values that would otherwise be difficult or impossible to type into code.
-
\nis a newline;\tis a tab. -
The
\\escape character will represent a backslash character. -
The single quote in
Howl'sis fine because you’ve used double quotes to mark the beginning and end of the string. -
Multiline strings allow you to use newlines in strings without the
\nescape character. -
The expressions evaluate to the following:
-
'e' -
'Hello' -
'Hello' -
'lo world!
-
-
The expressions evaluate to the following:
-
'HELLO' -
True -
'hello'
-
-
The expressions evaluate to the following:
-
['Remember,', 'remember,', 'the', 'fifth', 'of', 'November.'] -
'There-can-be-only-one.'
-
-
The
rjust(),ljust(), andcenter()string methods, respectively -
The
lstrip()andrstrip()methods remove whitespace from the left and right ends of a string, respectively.
Chapter 7
-
The
re.compile()function returnsRegexobjects. -
Raw strings are used so that backslashes do not have to be escaped.
-
The
search()method returnsMatchobjects. -
The
group()method returns strings of the matched text. -
Group
0is the entire match, group1covers the first set of parentheses, and group2covers the second set of parentheses. -
Periods and parentheses can be escaped with a backslash:
\.,\(, and\). -
If the regex has no groups, a list of strings is returned. If the regex has groups, a list of tuples of strings is returned.
-
The
|character signifies matching “either, or” between two groups. -
The
?character can either mean “match zero or one of the preceding group” or be used to signify nongreedy matching. -
The
+matches one or more. The*matches zero or more. -
The
{3}matches exactly three instances of the preceding group. The{3,5}matches between three and five instances. -
The
\d,\w, and\sshorthand character classes match a single digit, word, or space character, respectively. -
The
\D,\W, and\Sshorthand character classes match a single character that is not a digit, word, or space character, respectively. -
Passing
re.Iorre.IGNORECASEas the second argument tore.compile()will make the matching case insensitive. -
The
.character normally matches any character except the newline character. Ifre.DOTALLis passed as the second argument tore.compile(), then the dot will also match newline characters. -
The
.*performs a greedy match, and the.*?performs a nongreedy match. -
Either
[0-9a-z]or[a-z0-9] -
'X drummers, X pipers, five rings, X hens' -
The
re.VERBOSEargument allows you to add whitespace and comments to the string passed tore.compile(). -
re.compile(r'^\d{1,3}(,\d{3})*$')will create this regex, but other regex strings can produce a similar regular expression. -
re.compile(r'[A-Z][a-z]*\sNakamoto') -
re.compile(r'(Alice|Bob|Carol)\s(eats|pets|throws)\s(apples|cats|baseballs)\.', re.IGNORECASE)
Chapter 8
-
Relative paths are relative to the current working directory.
-
Absolute paths start with the root folder, such as / or C:\.
-
The
os.getcwd()function returns the current working directory. Theos.chdir()function changes the current working directory. -
The
.folder is the current folder, and..is the parent folder. -
C:\bacon\eggs is the dir name, while spam.txt is the base name.
-
The string
'r'for read mode,'w'for write mode, and'a'for append mode -
An existing file opened in write mode is erased and completely overwritten.
-
The
read()method returns the file’s entire contents as a single string value. Thereadlines()method returns a list of strings, where each string is a line from the file’s contents. -
A shelf value resembles a dictionary value; it has keys and values, along with
keys()andvalues()methods that work similarly to the dictionary methods of the same names.
Chapter 9
-
The
shutil.copy()function will copy a single file, whileshutil.copytree()will copy an entire folder, along with all its contents. -
The
shutil.move()function is used for renaming files, as well as moving them. -
The
send2trashfunctions will move a file or folder to the recycle bin, whileshutilfunctions will permanently delete files and folders. -
The
zipfile.ZipFile()function is equivalent to theopen()function; the first argument is the filename, and the second argument is the mode to open the ZIP file in (read, write, or append).
Chapter 10
-
assert spam >= 10, 'The spam variable is less than 10.' -
assert eggs.lower() != bacon.lower(), 'The eggs and bacon variables are the same!'orassert eggs.upper() != bacon.upper(), 'The eggs and bacon variables are the same!' -
assert False, 'This assertion always triggers.' -
To be able to call
logging.debug(), you must have these two lines at the start of your program:import logging logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
-
To be able to send logging messages to a file named programLog.txt with
logging.debug(), you must have these two lines at the start of your program:import logging >>> logging.basicConfig(filename='programLog.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
-
DEBUG, INFO, WARNING, ERROR, and CRITICAL
-
logging.disable(logging.CRITICAL) -
You can disable logging messages without removing the logging function calls. You can selectively disable lower-level logging messages. You can create logging messages. Logging messages provides a timestamp.
-
The Step button will move the debugger into a function call. The Over button will quickly execute the function call without stepping into it. The Out button will quickly execute the rest of the code until it steps out of the function it currently is in.
-
After you click Go, the debugger will stop when it has reached the end of the program or a line with a breakpoint.
-
A breakpoint is a setting on a line of code that causes the debugger to pause when the program execution reaches the line.
-
To set a breakpoint in IDLE, right-click the line and select Set Breakpoint from the context menu.
Chapter 11
-
The
webbrowsermodule has anopen()method that will launch a web browser to a specific URL, and that’s it. Therequestsmodule can download files and pages from the Web. TheBeautifulSoupmodule parses HTML. Finally, theseleniummodule can launch and control a browser. -
The
requests.get()function returns aResponseobject, which has atextattribute that contains the downloaded content as a string. -
The
raise_for_status()method raises an exception if the download had problems and does nothing if the download succeeded. -
The
status_codeattribute of theResponseobject contains the HTTP status code. -
After opening the new file on your computer in
'wb'“write binary” mode, use aforloop that iterates over theResponseobject’siter_content()method to write out chunks to the file. Here’s an example:saveFile = open('filename.html', 'wb') for chunk in res.iter_content(100000): saveFile.write(chunk) -
F12 brings up the developer tools in Chrome. Pressing CTRL-SHIFT-C (on Windows and Linux) or ⌘-OPTION-C (on OS X) brings up the developer tools in Firefox.
-
Right-click the element in the page, and select Inspect Element from the menu.
-
'#main' -
'.highlight' -
'div div' -
'button[value="favorite"]' -
spam.getText() -
linkElem.attrs -
The
seleniummodule is imported withfrom selenium import webdriver. -
The
find_element_*methods return the first matching element as aWebElementobject. Thefind_elements_*methods return a list of all matching elements asWebElementobjects. -
The
click()andsend_keys()methods simulate mouse clicks and keyboard keys, respectively. -
Calling the
submit()method on any element within a form submits the form. -
The
forward(),back(), andrefresh() WebDriverobject methods simulate these browser buttons.
Chapter 12
-
The
openpyxl.load_workbook()function returns aWorkbookobject. -
The
get_sheet_names()method returns aWorksheetobject. -
Call
wb.get_sheet_by_name('Sheet1'). -
Call
wb.get_active_sheet(). -
sheet['C5'].valueorsheet.cell(row=5, column=3).value -
sheet['C5'] = 'Hello'orsheet.cell(row=5, column=3).value = 'Hello' -
cell.rowandcell.column -
They return the highest column and row with values in the sheet, respectively, as integer values.
-
openpyxl.cell.column_index_from_string('M') -
openpyxl.cell.get_column_letter(14) -
sheet['A1':'F1'] -
wb.save('example.xlsx’) -
A formula is set the same way as any value. Set the cell’s
valueattribute to a string of the formula text. Remember that formulas begin with the = sign. -
sheet.row_dimensions[5].height = 100 -
sheet.column_dimensions['C'].hidden = True -
OpenPyXL 2.0.5 does not load freeze panes, print titles, images, or charts.
-
Freeze panes are rows and columns that will always appear on the screen. They are useful for headers.
-
openpyxl.charts.Reference(),openpyxl.charts.Series(),openpyxl.charts. BarChart(),chartObj.append(seriesObj), andadd_chart()
Chapter 13
-
A
Fileobject returned fromopen() -
Read-binary (
'rb') forPdfFileReader()and write-binary ('wb') forPdfFileWriter() -
Calling
getPage(4)will return aPageobject for About This Book, since page 0 is the first page. -
The
numPagesvariable stores an integer of the number of pages in thePdfFileReaderobject. -
Call
decrypt('swordfish'). -
The
rotateClockwise()androtateCounterClockwise()methods. The degrees to rotate is passed as an integer argument. -
docx.Document('demo.docx') -
A document contains multiple paragraphs. A paragraph begins on a new line and contains multiple runs. Runs are contiguous groups of characters within a paragraph.
-
Use
doc.paragraphs. -
A
Runobject has these variables (not a Paragraph). -
Truealways makes theRunobject bolded andFalsemakes it always not bolded, no matter what the style’s bold setting is.Nonewill make theRunobject just use the style’s bold setting. -
Call the
docx.Document()function. -
doc.add_paragraph('Hello there!') -
The integers
0,1,2,3, and4
Chapter 14
-
In Excel, spreadsheets can have values of data types other than strings; cells can have different fonts, sizes, or color settings; cells can have varying widths and heights; adjacent cells can be merged; and you can embed images and charts.
-
You pass a
Fileobject, obtained from a call toopen(). -
Fileobjects need to be opened in read-binary ('rb') forReaderobjects and write-binary ('wb') forWriterobjects. -
The
writerow()method -
The
delimiterargument changes the string used to separate cells in a row. Thelineterminatorargument changes the string used to separate rows. -
json.loads() -
json.dumps()
Chapter 15
-
A reference moment that many date and time programs use. The moment is January 1st, 1970, UTC.
-
time.time() -
time.sleep(5) -
It returns the closest integer to the argument passed. For example,
round(2.4)returns2. -
A
datetimeobject represents a specific moment in time. Atimedeltaobject represents a duration of time. -
threadObj = threading.Thread(target=spam) -
threadObj.start() -
Make sure that code running in one thread does not read or write the same variables as code running in another thread.
-
subprocess.Popen('c:\\Windows\\System32\\calc.exe')
Chapter 16
-
SMTP and IMAP, respectively
-
smtplib.SMTP(),smtpObj.ehlo(),smptObj.starttls(), andsmtpObj.login() -
imapclient.IMAPClient()andimapObj.login() -
A list of strings of IMAP keywords, such as
'BEFORE <date>','FROM <string>', or'SEEN' -
Assign the variable
imaplib._MAXLINEa large integer value, such as10000000. -
The
pyzmailmodule reads downloaded emails. -
You will need the Twilio account SID number, the authentication token number, and your Twilio phone number.
Chapter 17
-
An RGBA value is a tuple of 4 integers, each ranging from 0 to 255. The four integers correspond to the amount of red, green, blue, and alpha (transparency) in the color.
-
A function call to
ImageColor.getcolor('CornflowerBlue', 'RGBA')will return(100, 149, 237, 255), the RGBA value for that color. -
A box tuple is a tuple value of four integers: the left edge x-coordinate, the top edge y-coordinate, the width, and the height, respectively.
-
Image.open('zophie.png') -
imageObj.sizeis a tuple of two integers, the width and the height. -
imageObj.crop((0, 50, 50, 50)). Notice that you are passing a box tuple tocrop(), not four separate integer arguments. -
Call the
imageObj.save('new_filename.png')method of theImageobject. -
The
ImageDrawmodule contains code to draw on images. -
ImageDrawobjects have shape-drawing methods such aspoint(),line(), orrectangle(). They are returned by passing theImageobject to theImageDraw.Draw()function.
Chapter 18
-
Move the mouse to the top-left corner of the screen, that is, the (0, 0) coordinates.
-
pyautogui.size()returns a tuple with two integers for the width and height of the screen. -
pyautogui.position()returns a tuple with two integers for the x- and y-coordinates of the mouse cursor. -
The
moveTo()function moves the mouse to absolute coordinates on the screen, while themoveRel()function moves the mouse relative to the mouse’s current position. -
pyautogui.dragTo()andpyautogui.dragRel() -
pyautogui.typewrite('Hello world!') -
Either pass a list of keyboard key strings to
pyautogui.typewrite()(such as'left') or pass a single keyboard key string topyautogui.press(). -
pyautogui.screenshot('screenshot.png') -
pyautogui.PAUSE = 2
