Objectives: LO-1.1–1.3, LO-2.1–2.4, LO-3.1–3.3, LO-4.1–4.4, LO-5.1–5.3, LO-6.1–6.4,
LO-7.1–7.4, and LO-8.1–8.4
Prerequisites: Modules 1–8
Time: 90 minutes for the 16 questions, worth 100 points, and about 30 minutes more to check
your answers and review what you missed
This self-test mixes questions from the first eight modules, so you practice recalling what each module taught and choosing among its methods, not only applying the one you learned last. It isn’t graded. Take it after Module 8 and before Module 9, in one sitting. If you already program in another language, you can take it before Module 1, to find the modules you can skip. The answers are in the collapsed blocks after each question; open them only once you have written all of yours.
How to take it¶
Set aside 90 minutes without interruptions. Use paper and a pen, with no computer, phone, or notes: the effort of recalling without help is what makes this practice work.
Write an answer to every question before you open any answer. Each question’s heading gives its objectives and its points.
Open the answers and score yourself. Each answer says how its points are given. The points are only for scoring yourself: the course has no grades.
For each question you missed, its objective ID names the module to review: for example, LO-3.2 belongs to Module 3. Run the question’s code in a notebook cell or the interactive interpreter to see the answer for yourself.
Rules for your answers¶
All code is Python 3.12 or newer. When a question asks what a line prints, write exactly what it prints, spaces included.
If a line raises an error, write “error” and the kind of error, such as
TypeError.Where a question asks you to write code, small slips such as a missing colon cost nothing; a wrong method or a wrong result does.
Questions¶
Question 1 (LO-2.1, 8 points)¶
Give the value of each expression and its type: int, float, str, or bool. If it raises an
error, write “error” and the kind of error.
| Expression | Value | Type | |
|---|---|---|---|
| (a) | 7 / 2 | ||
| (b) | -7 // 2 | ||
| (c) | -7 % 3 | ||
| (d) | 2 ** 3 ** 2 | ||
| (e) | 1 + 2 * 3 ** 2 | ||
| (f) | "ab" * 2 | ||
| (g) | 7.0 // 2 | ||
| (h) | "3" + 4 |
Answer
| Expression | Value | Type | |
|---|---|---|---|
| (a) | 7 / 2 | 3.5 | float |
| (b) | -7 // 2 | -4 | int |
| (c) | -7 % 3 | 2 | int |
| (d) | 2 ** 3 ** 2 | 512 | int |
| (e) | 1 + 2 * 3 ** 2 | 19 | int |
| (f) | "ab" * 2 | "abab" | str |
| (g) | 7.0 // 2 | 3.0 | float |
| (h) | "3" + 4 | error | TypeError |
One point for each row, for the value and the type together. / always gives a float. // rounds down, toward the lower number, so -3.5 becomes -4. The remainder follows from the same rounding: -7 / 3 is about -2.33, which rounds down to -3, and -7 - 3 \times (-3) = 2. ** runs from right to left, so (d) is 2^9, and it runs before *, which runs before +, so (e) is 1 + 2 \times 9. A float on either side of // makes the result a float. + can’t join a string and a number. Common mistakes: -3 for (b), from rounding toward zero, and 64 for (d), from working left to right.
Question 2 (LO-1.1, LO-1.3, 6 points)¶
Running the script receipt.py prints this:
Traceback (most recent call last):
File "/home/you/py101/receipt.py", line 4, in <module>
print("Pens: " + pens)
~~~~~~~~~^~~~~~
TypeError: can only concatenate str (not "int") to strThe script is:
pens = 3
price = 1.25
# Print the receipt.
print("Pens: " + pens)
print("Total:", pens * price)(a) (2 points) Which line failed, what kind of error is it, and what does the message mean?
(b) (1 point) Rewrite line 4 so that it prints Pens: 3.
(c) (1 point) Did line 5 run? If line 4 had been print("Pens: " + pens instead, with its closing
parenthesis missing, which lines would have run?
(d) (2 points) Which way of running Python suits each task best: a notebook cell or the
interactive interpreter, or a script file? (i) Checking what 17 % 5 is. (ii) A program that
someone else will run every Monday.
Answer
(a) Line 4. It’s a TypeError: + can join a string to a string, but pens is an int, and Python doesn’t convert it for you. One point for the line and the kind, one for the meaning.
(b) print("Pens:", pens) or print("Pens: " + str(pens)).
(c) No: the script stops at the line that fails, so lines 1 and 2 ran, line 3 is a comment, and line 5 didn’t run. A syntax error stops the script before any of it runs, so with the missing parenthesis no line would have run. The point needs both halves.
(d) (i) A notebook cell or the interactive interpreter, which shows the value at once. (ii) A script file, which is how programs are kept and shared. One point each.
Question 3 (LO-1.2, LO-2.2, 4 points)¶
What does this program print? Then draw the names and the values they refer to at the end.
a = 3
b = a
a = a + 2
c = b * a
b = "b"
print(a, b, c)
print("a + c =", a + c)Answer
5 b 15
a + c = 20b = a makes b refer to 3, the value a had then; changing a to 5 later doesn’t change b. So c is 3 × 5 = 15, and then b moves to the string "b". At the end a refers to 5, b to "b", and c to 15. print separates its arguments with spaces. One point for each printed line, and two for the drawing. The common mistake is c as 25, from thinking b follows a.
Question 4 (LO-2.3, LO-2.4, 7 points)¶
price = input("Price: ") # The user types 2.50
quantity = input("Quantity: ") # The user types 3
total = price * quantity(a) (2 points) The last line stops with a TypeError. Why? And what would price * int(quantity)
give instead?
(b) (2 points) Fix the program so that total is 7.5, and write a line that prints
Total: 7.50, with the number right-aligned in 8 characters and 2 decimals.
(c) (2 points) Why is 0.1 + 0.2 == 0.3 False, and how should a program compare the two sides
instead?
(d) (1 point) What are round(2.5) and round(3.5)?
Answer
(a) input always returns a string, so the line multiplies two strings, which Python can’t do. price * int(quantity) is "2.502.502.50": a string times a whole number repeats it. That’s worse than an error, because the program goes on with a wrong value. One point for each half.
(b) One point for the conversion, one for the format:
price = float(input("Price: "))
quantity = int(input("Quantity: "))
total = price * quantity
print(f"Total: {total:>8.2f}")(c) A float stores the nearest value it can in binary, and 0.1, 0.2, and 0.3 have no exact binary form, so the sum comes out as 0.30000000000000004. Compare floats with math.isclose(0.1 + 0.2, 0.3). One point for each half.
(d) 2 and 4: round takes halves to the even number.
Question 5 (LO-3.1, 6 points)¶
Is each expression True or False?
(a) 3 < 5 and 5 < 4
(b) not 0
(c) "apple" < "Banana"
(d) bool("False")
(e) "10" < "9"
(f) bool([])
Answer
(a) False: both sides must be true. (b) True: 0 counts as false. (c) False: strings compare character by character, and capitals come before lowercase letters, so "B" comes before "a". (d) True: any string but the empty one counts as true, whatever it says. (e) True: these are strings, so the first characters decide, and "1" comes before "9". (f) False: an empty list counts as false. One point each.
Question 6 (LO-3.2, LO-3.3, 6 points)¶
Scores are whole numbers from 0 to 100. A score of 80 or more should give "distinction", 50 to
79 "pass", and below 50 "fail".
def grade(score):
if score >= 50:
return "pass"
elif score >= 80:
return "distinction"
else:
return "fail"(a) (2 points) Which branch can never run, and why?
(b) (2 points) Rewrite the function so that every branch can run.
(c) (2 points) Write the fewest assert tests that reach every branch and test both sides of each
boundary.
Answer
(a) The "distinction" branch. Every score of 80 or more is also 50 or more, so the first condition catches it, and only the first true branch runs.
(b) Put the narrower condition first:
def grade(score):
if score >= 80:
return "distinction"
elif score >= 50:
return "pass"
else:
return "fail"(c) Four tests, at both sides of the two boundaries:
assert grade(80) == "distinction"
assert grade(79) == "pass"
assert grade(50) == "pass"
assert grade(49) == "fail"One point for testing 79 and 80, one for 49 and 50. Tests such as grade(90) and grade(20) reach the branches but miss a mistake such as > 80 in place of >= 80.
Question 7 (LO-4.1, 4 points)¶
n = 10
while n != 0:
print(n)
n = n - 3(a) (2 points) What happens when this runs, and why?
(b) (1 point) Change the condition so that the loop stops after printing 10, 7, 4, and 1.
(c) (1 point) With your condition, give a starting value of n for which the loop body never runs.
Answer
(a) It prints 10, 7, 4, 1, -2, -5, and so on forever. n goes from 1 to -2 without ever being 0, so the condition never becomes false. One point for “forever”, one for why.
(b) while n > 0:
(c) Any value of 0 or less, such as 0: the condition is false at the start, so the body never runs.
Question 8 (LO-4.2, LO-4.4, 6 points)¶
(a) (3 points) Which values does i take in each loop: for i in range(2, 11, 3):,
for i in range(5, 0, -2):, and for i in range(10, 3):?
(b) (3 points) What does each fragment leave in count?
count = 0
for i in range(3):
for j in range(5):
count = count + 1count = 0
for i in range(4):
for j in range(i):
count = count + 1Answer
(a) 2, 5, and 8; then 5, 3, and 1; and no values at all, because counting up from 10 never reaches a number below 3. One point each. stop is never included, so range(2, 11, 3) stops at 8.
(b) 15: the inner loop runs 5 times on each of 3 passes, and the ranges are independent, so multiply. 6: the inner loop runs 0, 1, 2, and 3 times, so add. One point for 15, two for 6.
Question 9 (LO-2.3, LO-4.3, LO-6.2, 5 points)¶
Write a loop that asks Age: until the user types only digits, for a number from 0 to 120, and
then prints Age accepted: 42 (with the age they typed). If they type anything else, print
Please enter a whole number from 0 to 120. and ask again. The program must not stop with an
error, whatever they type.
Answer
while True:
text = input("Age: ")
digits_only = text != ""
for char in text:
if char not in "0123456789":
digits_only = False
if digits_only and int(text) <= 120:
break
print("Please enter a whole number from 0 to 120.")
print(f"Age accepted: {int(text)}")The for loop checks every character before int sees the text, and and stops as soon as digits_only is false, so int never gets text it can’t convert. The empty string needs its own test, because a loop over no characters finds nothing wrong. A loop with input once before it and once inside it, and a condition that describes bad input, earns full marks too.
Two points for a loop that repeats until the input is good, two for checking the characters before converting, and one for the messages. Converting first, as in int(input("Age: ")), stops with a ValueError on "ten" and loses the two points for checking. text.isdigit() is right for every digit on an ordinary keyboard, but Module 6 showed that it accepts "²", which int can’t convert: it earns one of the two.
Question 10 (LO-5.1, LO-5.2, LO-5.3, 7 points)¶
total = 10
def add(x, y=1):
total = x + y
print(total)
result = add(5)
print(result, total)
print(add(y=2, x=3))(a) (3 points) What does the program print?
(b) (2 points) What happens if you then call this function, and why?
def bump():
total = total + 1(c) (1 point) Is add(x=3, 2) a valid call? Why or why not?
(d) (1 point) Rewrite add so that it is more useful to other code.
Answer
(a)
6
None 10
5
Noneadd prints its sum and returns nothing, so it returns None. The total inside add is local, so the global total stays 10. One point for None 10, one for the None at the end, and one for the rest.
(b) It stops with UnboundLocalError. Assigning to total inside bump makes total local throughout the function, so total + 1 reads a local variable that has no value yet. One point for the error, one for the reason.
(c) No: it’s a SyntaxError, because positional arguments must come before keyword arguments.
(d) Return the sum instead of printing it, so the caller can use it: def add(x, y=1): return x + y.
Question 11 (LO-6.1, LO-6.2, 7 points)¶
With s = "Data Science", give the value of each expression. If one raises an error, write
“error” and say why.
(a) s[0] and s[-1]
(b) s[5:8]
(c) s[::2]
(d) s[::-1]
(e) s.lower().count("e")
(f) s.find("z")
(g) s[0] = "d", as a statement
Answer
(a) "D" and "e". (b) "Sci": from index 5 up to, not including, 8. (c) "Dt cec": every second character from index 0, the space included. (d) "ecneicS ataD". (e) 2. (f) -1: find returns -1 when the text isn’t there. (g) Error, a TypeError: strings are immutable, so no operation changes a string in place; build a new one, such as "d" + s[1:].
One point each; (a) needs both values. Common mistakes: "Scie" for (b), from including the stop index, and "Dt Sine" for (c), from forgetting that index 4 is the space.
Question 12 (LO-6.3, LO-6.4, LO-7.3, 6 points)¶
(a) (1 point) What is chr(ord("A") + 2)?
(b) (2 points) "caf\u00e9" and "cafe\u0301" both look like “café” on screen. What is the
length of each, and why do the lengths differ?
(c) (1 point) Are they equal with ==?
(d) (2 points) Write initials(name), which returns the first letter of each word of name in
uppercase: initials("ada lovelace") is "AL", and so is initials(" ada lovelace ").
Answer
(a) "C": ord("A") is 65, and chr(67) is "C".
(b) 4 and 5. len counts code points, not the characters a reader sees. The first string writes é as one code point, U+00E9; the second writes it as e followed by U+0301, a combining accent that draws over the letter before it. One point for the lengths, one for the reason.
(c) No: == compares code points, and they differ.
(d) split() with no argument splits on any run of spaces and ignores spaces at the ends:
def initials(name):
"""Return the uppercase first letter of each word of name."""
return "".join([word[0].upper() for word in name.split()])A loop that adds word[0].upper() to a string is just as good. Splitting on " " gives empty strings for repeated spaces, and ""[0] stops with an IndexError; that loses a point.
Question 13 (LO-7.1, LO-7.2, 6 points)¶
def add_zero(items):
items.append(0)
items = [7]
a = [1, 2, 3]
b = a
c = a[:]
b.append(4)
c[0] = 99
add_zero(a)
print(a)
print(b)
print(c)
print(a.sort())(a) (4 points) What does the program print?
(b) (2 points) Draw the names a, b, c, and items (just before add_zero returns) and the
lists they refer to.
Answer
(a)
[1, 2, 3, 4, 0]
[1, 2, 3, 4, 0]
[99, 2, 3]
Noneb = a makes a second name for the same list, so b.append(4) changes the list a refers to. a[:] copies it, so c is a separate list. Inside add_zero, items starts as a third name for a’s list, so append(0) changes it; items = [7] then moves only the local name to a new list. sort sorts the list in place and returns None. One point for each line.
(b) a and b point to one list, [1, 2, 3, 4, 0]; c points to [99, 2, 3]; and items points to a new list, [7]. Two points for a drawing that shows a and b sharing one list and c apart.
Question 14 (LO-7.3, LO-7.4, 7 points)¶
(a) (2 points) Rewrite this loop as a list comprehension:
lengths = []
for word in words:
if len(word) > 3:
lengths.append(len(word))(b) (1 point) What is [n * n for n in range(5) if n % 2 == 0]?
(c) (2 points) With people = [("Ana", 31), ("Ben", 27), ("Chen", 31)], what is
sorted(people, key=lambda person: (-person[1], person[0]))?
(d) (1 point) What does this print?
for position, (name, age) in enumerate(people, start=1):
print(position, name)(e) (1 point) A program stores a point on a map as its latitude and longitude. Should each point be a tuple or a list? Why?
Answer
(a) lengths = [len(word) for word in words if len(word) > 3]. One point for the expression and the for, one for the if.
(b) [0, 4, 16].
(c) [("Ana", 31), ("Chen", 31), ("Ben", 27)]: the key sorts by age, oldest first, because the age is negated, and then by name, A to Z. One point for the order of the ages, one for Ana before Chen.
(d)
1 Ana
2 Ben
3 Chen(e) A tuple: a point always has two values, each with its own meaning, and it shouldn’t change. A tuple can also be a dictionary key, for example to store what is at each point.
Question 15 (LO-8.1, LO-8.2, 7 points)¶
inventory = {"apples": 3, "pears": 0}
inventory["plums"] = 5
inventory["apples"] = inventory["apples"] + 2
print(inventory)
print(inventory.get("kiwis", 0), "pears" in inventory, 5 in inventory)
print(inventory["kiwis"])(a) (3 points) What does each print show?
(b) (2 points) Write letter_counts(text), which returns a dictionary from each character of
text to how many times it appears: letter_counts("banana") is {"b": 1, "a": 3, "n": 2}. Use
get, not Counter.
(c) (2 points) With the data below, write an expression for the title of Ana’s last loan, and a list comprehension for the names of the members with no loans.
library = {
"members": [
{"name": "Ana", "loans": ["Dune", "Emma"]},
{"name": "Ben", "loans": []},
{"name": "Chen", "loans": ["Kim"]},
]
}Answer
(a) One point for each line:
{'apples': 5, 'pears': 0, 'plums': 5}
0 True Falseand the last print stops with a KeyError, because "kiwis" isn’t a key. in on a dictionary looks at the keys, so 5 in inventory is False even though 5 is a value. "pears" is a key, so it’s True, even though its value is 0.
(b)
def letter_counts(text):
"""Return a dictionary from each character of text to its count."""
counts = {}
for char in text:
counts[char] = counts.get(char, 0) + 1
return countsOne point for the loop and the dictionary, one for get with a default of 0. counts[char] = counts[char] + 1 stops with a KeyError on the first character.
(c) library["members"][0]["loans"][-1], which is "Emma"; and [member["name"] for member in library["members"] if not member["loans"]], which is ["Ben"], because an empty list counts as false. len(member["loans"]) == 0 works too. One point each.
Question 16 (LO-8.3, LO-8.4, 8 points)¶
(a) (2 points) With a = {1, 2, 3, 4} and b = {3, 4, 5}, give a & b, a | b, a - b, and
a ^ b. Then give len(set("banana")).
(b) (4 points) Choose a list, a tuple, a dictionary, or a set for each task, and name the operation that decides it.
Checking each of 10,000 email addresses against a blocklist of a million addresses.
A sensor’s readings, in the order they arrived, to plot over time.
The price of each product, found by its product code.
A color as its red, green, and blue values, used as a key in a dictionary.
(c) (2 points) Suppose that looking for a number that isn’t there takes 0.7 ms in a list of 100,000 numbers. About how long would it take in a list of 1,000,000 numbers? And in a set of 1,000,000 numbers, compared with a set of 100,000?
Answer
(a) {3, 4}, {1, 2, 3, 4, 5}, {1, 2}, and {1, 2, 5}; and 3, for b, a, and n. A set may print its items in any order. Two points for all five, one for three or four.
(b) One point each, for the structure and a reason:
A set of the blocklist:
inon a set uses the address’s hash and goes straight to it, while a list compares the address with up to a million others, 10,000 times.A list: it keeps the order, and appending each new reading at the end is cheap.
A dictionary from product code to price: it finds a value from its key without searching.
A tuple: it has a fixed size, each position has a meaning, and a dictionary key must be a value that can’t change, which rules out a list.
(c) About 7 ms: a list compares the number with every item, so the time grows in proportion to the length, 10 times the items for 10 times the time. A set takes about the same time for both sizes, because it goes straight to the place for the number’s hash. One point each.
After the self-test¶
Add up your points. If you lost points on a question, its objective IDs name the modules to review: reread each one’s summary and redo its practice exercises, which are on the page beside its reading. If you took this self-test before the course, start with the first module whose questions cost you points. Then go on to Module 9.