This appendix contains the answers to the practice questions at the end of each chapter. I highly recommend that you take the time to work through these questions. 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 questions as well.
When it comes to the practice programs, there is no one correct solution. As long as your program performs what the project asks for, you can consider it correct. However, if you want to see examples of completed projects, they are available in the “Download the files used in this book” link at https://
1. The operators are +, -, *, and /. The values are 'hello', -88.8, and 5.
2. The string is 'spam'; the variable is spam. Strings always start and end with quotes.
3. The three data types introduced in this chapter are integers, floating-point numbers, and strings.
4. An expression is a combination of values and operators. All expressions evaluate (that is, reduce) to a single value.
5. An expression evaluates to a single value. A statement does not.
6. The bacon variable is set to 20. The bacon + 1 expression does not reassign the value in bacon (that would need an assignment statement: bacon = bacon + 1).
7. Both expressions evaluate to the string 'spamspamspam'.
8. Variable names cannot begin with a number.
9. The int(), float(), and str() functions will evaluate to the integer, floating-point number, and string versions of the value passed to them.
10. The expression causes an error because 99 is an integer, and only strings can be concatenated to other strings with the + operator. The correct way is I have eaten ' + str(99) + ' burritos.'
1. True and False, using capital T and F, with the rest of the word in lowercase.
2. and, or, and not
3. True and True is True.
True and False is False.
False and True is False.
False and False is False.
True or True is True.
True or False is True.
False or True is True.
False or False is False.
not True is False.
not False is True.
4. False
False
True
False
False
True
5. ==, !=, <, >, <=, and >=
6. == 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.
7. A condition is an expression used in a flow control statement that evaluates to a Boolean value.
8. The lines print('bacon') and print('ham') are each blocks by themselves, and a third block is everything after if spam == 10: and before the final print('Done'):
print('eggs')
if spam > 5:
print('bacon')
else:
print('ham')
print('spam')
9. The code:
if spam == 1:
print('Hello')
elif spam == 2:
print('Howdy')
else:
print('Greetings!')
1. Press CTRL-C to stop a program stuck in an infinite loop.
2. The break statement will move the execution outside and just after a loop. The continue statement will move the execution to the start of the loop.
3. They all do the same thing. The range(10) call ranges from 0 up to (but not including) 10, range(0, 10) explicitly tells the loop to start at 0, and range(0, 10, 1) explicitly tells the loop to increase the variable by 1 on each iteration.
4. The code:
for i in range(1, 11):
print(i)
and:
i = 1
while i <= 10:
print(i)
i = i + 1
5. This function can be called with spam.bacon().
1. Functions reduce the need for duplicate code. This makes programs shorter, easier to read, and easier to update.
2. The code in a function executes when the function is called, not when the function is defined.
3. The def statement defines (that is, creates) a function.
4. A function consists of the def statement and the code in its def clause. A function call is what moves the program execution into the function, and the function call evaluates to the function’s return value.
5. There is one global scope, and a local scope is created whenever a function is called.
6. When a function returns, the local scope is destroyed, and all the variables in it are forgotten.
7. 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.
8. If there is no return statement for a function, its return value is None.
9. A global statement will force a variable in a function to refer to the global variable.
10. The data type of None is NoneType.
11. That import statement imports a module named areallyourpetsnamederic. (This isn’t a real Python module, by the way.)
12. This function can be called with spam.bacon().
13. Place the line of code that might cause an error in a try clause.
14. The code that could potentially cause an error goes in the try clause. The code that executes if an error happens goes in the except clause.
15. The random_number global variable is set once to a random number, and the random_number variable in the get_random_dice_roll() function uses the global variable. This means the same number is returned for every get _random_dice_roll() function call.
1. assert spam >= 10, 'The spam variable is less than 10.'
2. Either assert eggs.lower() != bacon.lower() 'The eggs and bacon variables are the same!' or assert eggs.upper() != bacon.upper(), 'The eggs and bacon variables are the same!'
3. assert False, 'This assertion always triggers.'
4. 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')
5. 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')
6. DEBUG, INFO, WARNING, ERROR, and CRITICAL
7. logging.disable(logging.CRITICAL)
8. 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.
9. The Step In button will move the debugger into a function call. The Step Over button will quickly execute the function call without stepping into it. The Step Out button will quickly execute the rest of the code until it steps out of the function it currently is in.
10. After you click Continue, the debugger will stop when it has reached the end of the program or a line with a breakpoint.
11. A breakpoint is a setting on a line of code that causes the debugger to pause when the program execution reaches the line.
12. To set a breakpoint in Mu, click the line number to make a red dot appear next to it.
1. The empty list value, which is a list value that contains no items. This is similar to how '' is the empty string value.
2. spam[2] = 'hello' (Notice that the third value in a list is at index 2 because the first index is 0.)
3. 'd' (Note that '3' * 2 is the string '33', which is passed to int() before being divided by 11. This eventually evaluates to 3. Expressions can be used wherever values are used.)
4. 'd' (Negative indexes count from the end.)
5. ['a', 'b']
6. 1
7. [3.14, 'cat', 11, 'cat', True, 99]
8. [3.14, 11, 'cat', True]
9. The operator for list concatenation is +, while the operator for replication is *. (This is the same as for strings.)
10. While append() will add values only to the end of a list, insert() can add them anywhere in the list.
11. The del statement and the remove() list method are two ways to remove values from a list.
12. Both lists and strings can be passed to len(), have indexes and slices, be used in for loops, be concatenated or replicated, and be used with the in and not in operators.
13. 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 square brackets, [and].
14. (42,) (The trailing comma is mandatory.)
15. The tuple() and list() functions, respectively.
16. They contain references to list values.
17. The copy.copy() function will do a shallow copy of a list, while the copy.deepcopy() function will do a deep copy of a list. That is, only copy .deepcopy() will duplicate any lists inside the list.
1. Two curly brackets: {}
2. {'foo': 42}
3. The items stored in a dictionary are unordered, while the items in a list are ordered.
4. You get a KeyError error.
5. There is no difference. The in operator checks whether a value exists as a key in the dictionary.
6. The expression 'cat' in spam checks 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 in spam.
7. spam.setdefault('color', 'black')
8. pprint.pprint()
1. Escape characters represent characters in string values that would otherwise be difficult or impossible to type into code.
2. The \n escape character is a newline; the \t escape character is a tab.
3. The \\ escape character will represent a backslash character.
4. The single quote in Howl's is fine because you’ve used double quotes to mark the beginning and end of the string.
5. Multiline strings allow you to use newlines in strings without the \n escape character.
6. The expressions evaluate to the following:
'e'
'Hello'
'Hello'
'lo world!
7. The expressions evaluate to the following:
'HELLO'
True
'hello'
8. The expressions evaluate to the following:
['Remember,', 'remember,', 'the', 'fifth', 'of', 'November.']
'There-can-be-only-one.'
9. The rjust(), ljust(), and center() string methods, respectively.
10. The lstrip() and rstrip() methods remove whitespace from the left and right ends of a string, respectively.
1. The re.compile() function creates Regex objects.
2. Raw strings are used so that backslashes do not have to be escaped.
3. The search() method returns Match objects.
4. The group() method returns strings of the matched text.
5. Group 0 is the entire match, group 1 covers the first set of parentheses, and group 2 covers the second set of parentheses.
6. Periods and parentheses can be escaped with a backslash: \., \(, and \).
7. 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.
8. The | character signifies matching “either, or” between two groups.
9. The ? character can either mean “match zero or one of the preceding group” or be used to signify non-greedy matching.
10. The + matches one or more. The * matches zero or more.
11. The {3} matches exactly three instances of the preceding group. The {3,5} matches between three and five instances.
12. The \d, \w, and \s shorthand character classes match a single digit, word, or space character, respectively.
13. The \D, \W, and \S shorthand character classes match a single character that is not a digit, word, or space character, respectively.
14. The .* performs a greedy match, and the .*? performs a non-greedy match.
15. Either [0-9a-z] or [a-z0-9].
16. Passing re.I or re.IGNORECASE as the second argument to re.compile() will make the matching case insensitive.
17. The . character normally matches any character except the newline character. If re.DOTALL is passed as the second argument to re.compile(), then the dot will also match newline characters.
18. The sub() call will return the string 'X drummers, X pipers, five rings, X hens'.
19. The re.VERBOSE argument allows you to add whitespace and comments to the string passed to re.compile().
1. Relative paths are relative to the current working directory.
2. Absolute paths start with the root folder, such as / or C:\.
3. On Windows, it evaluates to WindowsPath('C:/Users/Al'). On other operating systems, it evaluates to a different kind of Path object but with the same path.
4. The expression 'C:/Users' / 'Al' results in an error, since you can’t use the / operator to join two strings.
5. The os.getcwd() function returns the current working directory. The os.chdir() function changes the current working directory.
6. The . folder is the current folder, and .. is the parent folder.
7. C:\bacon\eggs is the directory name, while spam.txt is the base name.
8. The string 'r' for read mode, 'w' for write mode, and 'a' for append mode.
9. An existing file opened in write mode is erased and completely overwritten.
10. The read() method returns the file’s entire contents as a single string value. The readlines() method returns a list of strings, where each string is a line from the file’s contents.
11. A shelf value resembles a dictionary value; it has keys and values, along with keys() and values() methods that work similarly to the dictionary methods of the same names.
1. The shutil.copy() function will copy a single file, while shutil.copytree() will copy an entire folder, along with all its contents.
2. The shutil.move() function is used for renaming files, as well as moving them.
3. The send2trash function will move a file or folder to the recycle bin, while shutil will permanently delete files and folders.
4. The zipfile.ZipFile() function is equivalent to the open() function; the first argument is the filename, and the second argument is the mode to open the ZIP file in (read, write, or append).
1. The dir command lists folder contents on Windows. The ls command lists folder contents on macOS and Linux.
2. The PATH environment variable contains a list of folders that are checked when a program name is entered into the terminal.
3. The __file__ variable contains the filename of the Python script currently being run. This variable doesn’t exist in the interactive shell.
4. The cls command clears the terminal on Windows, while the clear command does so on macOS and Linux.
5. Run python -m venv .venv on Windows, or python3 -m venv .venv on macOS and Linux.
6. Run python -m PyInstaller --onefile yourScript.py on Windows, or python3 -m PyInstaller --onefile yourScript.py on macOS and Linux.
1. The webbrowser module has an open() method that will launch a web browser to a specific URL, and that’s it. The requests module can download files and pages from the web. The bs4 module parses HTML.
2. The requests.get() function returns a Response object, which has a text attribute that contains the downloaded content as a string.
3. The raise_for_status() method raises an exception if the download had problems and does nothing if the download succeeded.
4. The status_code attribute of the Response object contains the HTTP status code.
5. After opening the new file on your computer in 'wb' “write binary” mode, use a for loop that iterates over the Response object’s iter _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)
6. Most online APIs return their responses formatted as JSON or XML.
7. 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.8. Right-click the element in the page and select Inspect Element from the menu.
9. '#main'
10. '.highlight'
11. spam.gettext()
12. linkElem.attrs
13. The selenium module is imported with from selenium import webdriver.
14. The find_element_* methods return the first matching element as a WebElement object. The find_elements_* methods return a list of all matching elements as WebElement objects.
15. The click() and send_keys() methods simulate mouse clicks and keyboard keys, respectively.
16. The press('Control+A') method simulates pressing CTRL-A.
17. The forward(), back(), and refresh() WebDriver object methods simulate these browser buttons.
18. The go_forward(), go_back(), and reload() Page object methods simulate these browser buttons.
1. The openpyxl.load_workbook() function returns a Workbook object.
2. The sheetnames attribute contains a list of strings of the worksheet titles.
3. Run wb['Sheet1'].
4. Use wb.active.
5. sheet['C5'].value or sheet.cell(row=5, column=3).value
6. sheet['C5'] = 'Hello' or sheet.cell(row=5, column=3).value = 'Hello'
7. cell.row and cell.column
8. They hold the highest column and row with values in the sheet, respectively, as integer values.
9. openpyxl.cell.column_index_from_string('M')
10. openpyxl.cell.get_column_letter(14)
11. sheet['A1':'F1']
12. wb.save('example3.xlsx')
13. A formula is set the same way as any value. Set the cell’s value attribute to a string of the formula text. Remember that formulas begin with the equal sign (=).
14. Pass data_only=True when calling load_workbook() to make OpenPyXL retrieve the calculated results of formulas.
15. sheet.row_dimensions[5].height = 100
16. sheet.column_dimensions['C'].hidden = True
17. Freeze panes are rows and columns that will always appear on the screen. They are useful for headers.
18. openpyxl.chart.Reference(), openpyxl.chart.Series(), openpyxl.chart.BarChart(), chartObj.append(seriesObj), and add_chart()
1. To access Google Sheets, you need a credentials file, a token file for Google Sheets, and a token file for Google Drive.
2. EZSheets has ezsheets.Spreadsheet and ezsheets.Sheet objects.
3. Call the downloadAsExcel() Spreadsheet method.
4. Call the ezsheets.upload() function and pass the filename of the Excel file.
5. Read the value at ss['Students']['B2'].
6. Call ezsheets.getColumnLetterOf(999).
7. Access the rowCount and columnCount properties of the Sheet object.
8. Call the delete() Sheet method. This is only permanent if you pass the permanent=True keyword argument.
9. The Spreadsheet() function and Sheet() Spreadsheet method will create Spreadsheet and Sheet objects, respectively.
10. EZSheets will throttle your method calls.
1. conn = sqlite3.connect('example.db', isolation_level=None)
2. conn.execute('CREATE TABLE students (first_name TEXT, last_name TEXT, favorite_color TEXT) STRICT')
3. Pass the isolation_level=None keyword argument when calling sqlite3.connect().
4. While INTEGER is analogous to Python’s int type, REAL is analogous to Python’s float type.
5. Strict mode adds a requirement that every column must have a data type, and SQLite raises an exception if you try to insert data of the wrong type.
6. The * means “select all columns in the table.”
7. CRUD stands for Create, Read, Update, and Delete, the four standard operations that databases perform.
8. ACID stands for Atomic, Consistent, Isolated, and Durable, the four properties that database transactions should have.
9. INSERT queries add new records to tables.
10. DELETE queries delete records from tables.
11. Without a WHERE clause, the UPDATE query applies to all records in the table, which may or may not be what you want.
12. An index is a data structure that organizes a column’s data, which takes up more storage but makes queries faster. 'CREATE INDEX idx_birthdate ON cats (birthdate)' would create an index for the cats table’s birthdate column.
13. A foreign key links records in one table to a record in another table.
14. You can delete a table named cats by running the query 'DROP TABLE cats'.
15. The string ':memory:' is used in place of a filename to create an in- memory database.
16. The iterdump() method can create the queries to copy a database. You can also copy the database file itself.
1. A File object must be opened in write mode by passing 'w' to open().
2. Calling getPage(4) will return a Page object for page 5, since page 0 is the first page.
3. Call decrypt('swordfish').
4. Rotate pages counterclockwise by passing a negative integer: -90, -180, or -270.
5. docx.Document('demo.docx')
6. Use doc.paragraphs to obtain a list of Paragraph objects.
7. A Paragraph object represents a paragraph of text and is itself made up of one or more Run objects.
8. A Run object has these variables (not a Paragraph object).
9. True always makes the Run object bolded and False always makes it not bolded, no matter what the style’s bold setting is. None will make the Run object just use the style’s bold setting.
10. Call the docx.Document() function.
11. doc.add_paragraph('Hello there!')
12. The integers 0 through 9.
1. 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.
2. You pass a File object, obtained from a call to open().
3. File objects need to be opened in read-binary ('rb') mode for Reader objects and write-binary ('wb') mode for Writer objects.
4. The writerow() method.
5. The delimiter argument changes the string used to separate cells in a row. The lineterminator argument changes the string used to separate rows.
6. All of them can be easily edited with a text editor: CSV, JSON, and XML are plaintext formats.
7. json.loads()
8. json.dumps()
9. XML’s format resembles HTML.
10. JSON represents None values as the keyword null.
11. Boolean values in JSON are written in lowercase: true and false.
1. A reference moment that many date and time programs use. The moment is January 1, 1970, UTC.
2. time.time()
3. time.asctime()
4. time.sleep(5)
5. It returns the closest integer to the argument passed. For example, round(2.4) returns 2.
6. A datetime object represents a specific moment in time. A timedelta object represents a duration of time.
7. Run datetime.datetime(2019, 1, 7).weekday(), which returns 0. This means Monday, as the datetime module uses 0 for Monday, 1 for Tuesday, and so on, up to 6 for Sunday.
1. The credentials.json and token.json files tell the EZGmail module which Google account to use when accessing Gmail.
2. A message represents a single email, while a back-and-forth conversation involving multiple emails is a thread.
3. Include the 'has:attachment' text in the string you pass to search().
4. SMS email gateways are not guaranteed to work, don’t notify you if the message was delivered, and just because they worked before does not mean they will work again.
5. The Requests library can send and receive ntfy notifications.
1. An RGBA value is a tuple of four integers, each ranging from 0 to 255. The four integers correspond to the amount of red, green, blue, and alpha (transparency) in the color.
2. Calling ImageColor.getcolor('CornflowerBlue', 'RGBA') will return (100, 149, 237, 255), the RGBA value for the cornflower blue color.
3. 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.
4. Image.open('zophie.png')
5. im.size is a tuple of two integers, the width and the height.
6. im.crop((0, 50, 50, 50)). Notice that you are passing a box tuple to crop(), not four separate integer arguments.
7. Call the im.save('new_filename.png') method of the Image object.
8. The ImageDraw module contains code to draw on images.
9. ImageDraw objects have shape-drawing methods such as point(), line(), or rectangle(). They are returned by passing the Image object to the ImageDraw.Draw() function.
10. plt.plot() creates a line graph, plt.scatter() creates a scatterplot, plt.bar() creates a bar graph, and plt.pie() creates a pie chart.
11. The savefig() method saves the graph as an image.
12. You cannot call plt.show() twice in a row because it resets the graph data, forcing you to run the graph-making code again if you want to show it a second time.
1. Tesseract recognizes English by default.
2. PyTesseract works with the Pillow image library.
3. The image_to_string() function accepts an Image object and returns a string.
4. No, Tesseract only extracts text from scanned documents of typewritten text and not text from photographs.
5. tess.get_languages() returns a list of language pack strings.
6. You can pass the lang='eng+jpn' keyword argument to identify both English and Japanese text in an image.
7. NAPS2 can be run from a Python script to create PDFs with embedded OCR text.
1. Move the mouse to any corner of the screen.
2. The pyautogui.size() function returns a tuple with two integers for the width and height of the screen.
3. The pyautogui.position() function returns a tuple with two integers for the x- and y-coordinates of the mouse cursor.
4. The moveTo() function moves the mouse to absolute coordinates on the screen, while the move() function moves the mouse relative to the mouse’s current position.
5. pyautogui.dragTo() and pyautogui.drag()
6. pyautogui.typewrite('Hello world!')
7. Either pass a list of keyboard key strings to pyautogui.write() (such as 'left') or pass a single keyboard key string to pyautogui.press().
8. pyautogui.screenshot('screenshot.png')
9. pyautogui.PAUSE = 2
10. You should use Selenium for controlling a web browser instead of PyAutoGUI.
11. PyAutoGUI clicks and types blindly and cannot easily find out if it’s clicking and typing into the correct windows. Unexpected pop-up windows or errors can throw the script off track and require you to shut it down.
12. Call the pyautogui.getWindowsWithTitle('Notepad') function.
13. Run w = pyatuogui.getWindowsWithTitle('Firefox'), and then run w.activate().
1. Call engine.setProperty('rate', 300), for example, to make pyttsx3’s voice speak at 300 words per minute.
2. The pyttsx3 module saves to the WAV audio format.
3. No, pyttsx3 and Whisper do not require an online service or internet access.
4. Yes, pyttsx3 and Whisper support languages other than English.
5. Whisper’s default model is 'base'.
6. SRT (SubRip Subtitle) and VTT Web Video Text Tracks are two common subtitle file formats.
7. Yes, yt-dlp can download from hundreds of video websites other than YouTube.
A flow chart showing how to evaluate the mathematical expression “5 minus 1 in parentheses, multiplied by the result of dividing seven plus one and three minus one.” First, five minus one reduces to four. Next, seven plus one reduces to eight. Then, three minus one reduces to two. After that, eight divided by two reduces to four. Finally, four times four produces the solution, sixteen.
Return to text
A diagram showing how an expression passed to the print function, “You will be ‘ + str(int(myage) + 1) + ‘ in a year,’ evaluates to its final value. First, “my age” is replaced by the string “4”. Then, “int” disappears, and the string “4” is replaced by the integer 4. Next, 4 + 1 evaluates to 5. After that, “str” disappears, and the integer “5” becomes the string “5”. Finally, the strings “You will be” and “5” and “in a year” are added together. The final result is the string “You will be 5 in a year.”
Return to text
A flowchart that begins with a box labeled “Start.” An arrow leads to the question “Is raining?” This question leads to two arrows, one labeled “yes” and one labeled “no.” The “no” branch leads to a box labeled “Go outside,” where a final arrow leads to a box labeled “End.” The “yes” branch leads to the question “Have umbrella?” which branches once again into a “yes” and a “no” arrow. The “yes” arrow leads to the “Go outside” box. The “no” arrow leads to a box labeled “Wait a while,” which leads to the question labeled “Is raining?” The “yes” arrow leads back to the “Wait a while” box. The “no” arrow leads to the “Go outside” box.
Return to text
A diagram evaluating the expression “four is less than five” in parentheses and “five is less than six” in parentheses. First, “four is less than five” reduces to “True.” Next, “five is less than six” reduces to True. Finally, “True and True” reduces to the final value, True.
Return to text
A flowchart that begins with a box labeled “Start.” An arrow leads to the box “name equals Alice,” which leads to the decision point “name equals Alice.” A “true” branch leads to the box “print(‘Hi,Alice.’)”, which leads to “End.” A “false” branch leads directly to “End.”
Return to text
A flowchart that begins with a box labeled “Start.” An arrow leads to the box “name equals Alice,” which leads to the decision point “name equals Alice.” A “true” branch leads to the box “print(‘Hi,Alice.’)”, which leads to “End.” A “false” branch leads to the box “print(‘Hello, stranger.’),” which leads to “End.”
Return to text
A flowchart that begins with a box labeled “Start.” An arrow leads to the box “name equals Alice,” which leads to a box labeled “age equals 15.” This box leads to the decision point “name equals Alice.” A “true” branch leads to the box “print(‘Hi, Alice.’)”, which leads to “End.” A “false” branch leads to the decision point “age is less than 12.” A “true” branch leads to the box“print(‘You are not Alice, kiddo.’),” which leads to “End.” A “false” branch leads directly to “End.”
Return to text
A flowchart that begins with a box labeled “Start.” An arrow leads to the decision point “name equals Alice.” A “true” arrow leads to the box “print(‘Hi, Alice.’),” which leads to End. A “false” arrow leads to the decision point “age is less than 12.” From this decision point, a “true” arrow leads to the box “print(‘You are not Alice, Kiddo.’),” which leads to End. A false arrow leads to the decision point “age is greater than 2000.” From this decision point, a “true” arrow leads to the box “print(‘Unlike you, Alice is not an undead, immortal vampire.’), which leads to End. A “false’ arrow leads to the decision point “age is greater than 100.” From this decision point, a True arrow leads to the box “print(‘You are not Alice, grannie.’),” which leads to End. A False arrow leads directly to End.
Return to text
A flowchart that begins with a box labeled “Start.” An arrow leads to the decision point “name equals Alice.” A “true” arrow leads to the box “print(‘Hi, Alice.’),” which leads to End. A “false” arrow leads to the decision point “age is less than 12.” From this decision point, a “true” arrow leads to the box “print(‘You are not Alice, kiddo.’),” which leads to End. A false arrow leads to the decision point “age is greater than 100.” From this decision point, a True arrow leads to the box “print(‘You are not Alice, grannie.’),” which leads to End. A false arrow leads to the decision point “age is greater than 2000.” From this decision point, a “true” arrow leads to the box “print(‘Unlike you, Alice is not an undead, immortal vampire.’), which leads to End. A False arrow leads directly to End.
Return to text
A flowchart that begins with a box labeled “Start.” An arrow leads to the decision point “name equals Alice.” A “true” arrow leads to the box “print(‘Hi, Alice.’),” which leads to End. A “false” arrow leads to the decision point “age is less than 12.” From this decision point, a “true” arrow leads to the box “print(‘You are not Alice, kiddo.’),” which leads to End. A false arrow leads to the box “print(‘You are neither Alice nor a little kid.”),” which leads to End.
Return to text
A diagram showing the evaluation of a Python expression assigned to the variable “real_capacity.” The expression begins “str(round(advertised_capacity multiplied by discrepancy, 2)).” First, “advertised_capacity” evaluates to 10 and “discrepancy” evaluates to “0.9094947017729282.” Next, “round(10 multiplied by 0.9094947017729282, 2)” evaluates to “round(9.094947017729282, 2).” After that, the expression reduces to “str(9.09),” leading to the final value, the string “9.09”.
Return to text
A flowchart that begins with a box labeled “Start.” An arrow leads to the decision point “spam is less than 5.” A True arrow leads to the box “print(‘Hello, world.’), which leads to the box “spam equals spam plus 1,” which leads to End. A False arrow leads directly to end.
Return to text
A flowchart that begins with a box labeled “Start.” An arrow leads to the decision point “spam is less than 5.” A True arrow leads to the box “print(‘Hello, world.’), which leads to the box “spam equals spam plus 1,” which leads to back to the decision point “spam is less than 5.” A False arrow leads directly to end.
Return to text
A flowchart that begins with a box labeled “Start.” An arrow leads to the decision point “name does not equal ‘your name’.” A True arrow leads to the box “print(‘Please type your name.’),” which leads to the box “name equals input(),” which leads to back to the decision point “name does not equal ‘your name’.” A False arrow leads to the box “print(‘Thank you!’)”, which leads to end.
Return to text
A flowchart that begins with a box labeled “Start.” An arrow leads to the decision point “True.” From there, a crossed-out “False” branch leads to the box “print(Thank You!),” which leads to End, while a True arrow leads to the box “print(‘Please type your name.’),” which leads to the box “name equals input(),” which leads to the decision point “name is equal to ‘your name’.” From here, a True arrow leads to a box labeled “break,” which leads to “print(Thank You!),” which leads to End. A False arrow leads back to the first decision point in the flowchart, “True.”
Return to text
A flowchart that begins with a box labeled “Start.” An arrow leads to the decision point “True.” From there, a crossed-out “False” branch leads to the box “print(‘Access granted.’), which leads to End, while a True arrow leads to the box “print(‘Who are you?’),” which leads to the box “name equals input(),” which leads to the decision point “name is not equal to ‘Joe’.” From here, a True arrow leads to a box labeled “continue,” which leads back to the first decision point in the flowchart, “True.” A False arrow leads to the box “print(‘Hello, Joe. What is the password? (It is a fish.)’),” which leads to the box “password equals input(),” which leads to the decision point “password is equal to ‘swordfish.’” From there, a false arrow leads back to the original decision point, True, while a True arrow leads to a box labeled “break,” which leads to “print(‘Access granted.’), which leads to End.
Return to text
A flowchart that begins with a box labeled “Start.” An arrows leads to a box labeled “print(‘Hello’),” which leads to the decision point “for I in range (5).” From there, an arrow labeled “looping” leads to the box “print(‘On this iteration, I is set to ‘ + str(i)),” which leads back to the previous decision point, “for I in range (5).” At that decision point, another arrow, labeled “Done looping,” leads to End.
Return to text
The evolution of a stack of names, from left to right. The stack begins empty, then contains Alice, then contains Bob on top of Alice, then contains Carol on top of Bob on top of Alice, then contains Bob on top of Alice, then contains Alice, then contains David on top of Alice, then contains Alice, then is empty.
Return to text
The evolution of a stack of function calls, from left to right. The stack begins empty, then contains a(), then contains b() on top of a(), then contains c() on top of b() on top of a(), then contains b() on top of a(), then contains a(), then contains d() on top of a(), then contains a(), then is empty.
Return to text
A screenshot of the Mu interface. On the left side is a Python program with the first line highlighted, “print(‘Enter the first number to add:’).” On the right side are the lists “Name” and “Value” populated with the names and values of variables. At the bottom of the screen is the message ‘Running in debug mode. Use the Stop, Continue, and Step toolbar buttons to debug the script.”
Return to text
A screenshot of the Mu interface. On the left side is a Python program with the second line highlighted, “first = input()”. On the right side are the lists “Name” and “Value” populated with the names and values of variables.
Return to text
A screenshot of the Mu interface. On the left side is a Python program with the last line highlighted, “print(‘The sum is ‘ + first + second + third)”. On the right side are the lists “Name” and “Value” populated with the names and values of variables.
Return to text
A diagram showing how each item in the list “spam equals “cat”, “bat”, “rat”, “elephant”, corresponds to an index. “Cat” corresponds to the index “spam 0,” “bat” corresponds to the index “spam 1,” “rat corresponds to the index “spam 2,” and “elephant corresponds to the index “spam 3.”
Return to text
First, the Python assignment statement “spam equals 42” is represented as the value “42” with the tag “spam” attached to it. Second, the Python assignment statement “eggs equals spam” is represented as the value “42” with two tags, labeled “spam” and “eggs,” attached to it. Third, the Python assignment statement “spam equals 99” is represented as two values; “42” has the tag “eggs” attached to it, and “99” has the tag “spam” attached to it.
Return to text
First, the Python assignment statement “spam equals 42” is represented as the value “[0, 1, 2, 3]” with the tag “spam” attached to it. Second, the Python assignment statement “eggs equals spam” is represented as the value “[0, 1, 2, 3]” with two tags, labeled “spam” and “eggs,” attached to it. Third, the Python assignment statement “eggs[1] = ‘Hello’” is represented as the value “[0, ‘Hello’, 2, 3]” with two tags, “eggs” and “spam”, attached to it.
Return to text
A diagram showing the evaluation of the value of a Path object. Path(‘spam’)/bacon’ becomes WindowsPath(‘spam/bacon’)/‘eggs’. This then becomes WindowsPath(‘spam/bacon/eggs’) /‘ham’. The final value is WindowsPath(‘spam/bacon/eggs/ham’).
Return to text
A diagram showing nested folders and files, accompanied by the relative and absolute paths of the folder or file at each level in the directory. The first folder is “C:\”, its relative path is “..\”, and its absolute path is “C:\”. Within this folder is a “bacon” folder. Its relative path is “.\” and its absolute path is “C:\bacon”. Within bacon is a “fizz” folder. Its relative path is “.\fizz” and its absolute path is “C:\bacon\fizz”. Within fizz is a file, “spam.txt.” Its relative path is .\fizz\spam.txt” and its absolute path is “C:\bacon\fizz\spam.txt.” The “bacon” folder also has a “spam.txt” file. Its relative path is “.\spam.txt” and its absolute path is “C:\bacon\fizz\spam.txt”. The “C:\” folder contains another folder, “eggs.” Its relative path is “..\eggs” and its absolute path is “C:\eggs\spam.txt”. Eggs contains a file, “spam.txt:. Its relative path is “..\eggs\spam.txt” and its absolute path is “C:\eggs\spam.txt”. Finally, the “C:\” folder directly contains its own “spam.txt” file. Its relative path is “..\spam.txt” and its absolute oath is “C:\spam.txt”.
Return to text
A diagram of a filepath on Windows and macOS showing the anchor, parent, name, drive, stem, and suffix. In the windows path “C:\Users\Al\spam.txt”, the drive is “C:”, the anchor is “C:\”, the parent is “\Users\Al\”, the name is “spam.txt”, the stem is “spam,” and the suffix is “.txt”. In the macOS filepath “/home/al/spam.txt”, the anchor is “/“, the parent is “home/al/“, the name is “spam.txt”, the stem is “spam”, and the suffix is “.txt”.
Return to text
A Word document containing several rows of text in various fonts. The first row uses a cursive font and says “It would be a pleasure to have the company of”. The second row uses a bold, sans-serif font and says “RoboCop”. The third row uses the same cursive font as the first row and says “at 11010 Memory Lane on the Evening of”. The fourth row uses sans-serif font and says “April 1st”. The final line contains the cursive font once again and says “at 7 o’clock”.
Return to text