A Quick Refresher · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. Why does this code fail to compile?
a = [1,  # first
     2   # second]
2. What does this print?
def f():
    s = '''a
    b'''
    return s

print(len(f()))
3. What does this print?
def check():
    print('checked')
    return 'yes'

x = 0
res = check() if x else 'no'
print(res)
4. What does this print?
a = 15
if a > 5:
    print('big')
elif a > 10:
    print('bigger')
else:
    print('small')
5. What does this print?
def double(a: int) -> int:
    return a * 2

print(double('ab'))
6. What is printed?
def greet():
    print('hi')

result = greet()
print(result)
7. What does this print?
i = 0
while i < 3:
    i += 1
    if i == 2:
        continue
    print(i)
else:
    print('done')
8. What does this print?
for i in range(3):
    try:
        if i == 1:
            break
    finally:
        print('finally', i)
else:
    print('else')
9. Which statement about Python's for loop is true?
10. What does this print?
class P:
    def __init__(self, x):
        self.x = x

print(P(1) == P(1))
11. A class defines __eq__ and __lt__ (but not __gt__ or __le__). Which comparison raises TypeError?
12. What is printed?
class Temp:
    def __init__(self, c):
        self.c = c
    def __str__(self):
        return f'{self.c} C'
    def __repr__(self):
        return f'Temp({self.c})'

t = Temp(21)
print(t, [t])
13. What does this print?
print(isinstance(True, int), True + True)
14. Which pair of types are both implemented as hash tables?
15. What does this print?
class Account:
    def __init__(self):
        self.__pin = 1234

print(list(vars(Account())))
16. Which of these is not a valid identifier?
17. What does this print?
s = 'hello'
s.upper()
print(s[::-1])
18. What does this print?
grid = [[]] * 3
grid[0].append(1)
print(grid)
19. What does this print?
a = (1)
b = (1,)
print(type(a).__name__, type(b).__name__)
20. What does this print?
x = {}
y = {1, 2, 2, 3}
print(type(x).__name__, len(y))
21. What does this print?
stock = {'apples': 3}
print(stock.get('pears', 0), 'apples' in stock, 3 in stock)
22. What does this print?
nums = [3, 1, 2]
result = nums.sort()
print(result, nums)
23. What does this print?
a = {'x': 1, 'y': 2}
b = {'y': 20, 'z': 30}
print(a | b)

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Find the first negative

Write first_negative(numbers) that returns the index of the first negative number in the list numbers, or -1 if there is none.

Use a for loop with enumerate, break, and the loop's else clause (no index() calls and no flag variable).

Hints (2)
  1. for i, value in enumerate(numbers): gives you the index and the value together.
  2. Stop with break as soon as you find a negative. The loop's else block runs only if you never broke out, which is exactly the "not found" case.
Show a solution
def first_negative(numbers):
    for i, value in enumerate(numbers):
        if value < 0:
            result = i
            break
    else:
        result = -1
    return result

Exercise 2: Ratios without crashing

Write safe_ratios(pairs) that takes a list of (a, b) tuples and returns a tuple (results, attempts):

- results is a list of a / b for every pair where the division works; pairs with b == 0 are skipped (use try / except ZeroDivisionError and continue). - attempts counts every pair processed, including skipped ones. Increment it in a finally block.

Hints (2)
  1. Unpack each pair directly in the loop: for a, b in pairs:.
  2. continue in the except block skips the append, but the finally block still runs first, so the counter is always incremented.
Show a solution
def safe_ratios(pairs):
    results = []
    attempts = 0
    for a, b in pairs:
        try:
            ratio = a / b
        except ZeroDivisionError:
            continue
        finally:
            attempts += 1
        results.append(ratio)
    return results, attempts

Exercise 3: A small Money class

Write a class Money whose instances hold an amount (in cents, an int):

- Money(250) creates an instance; repr() gives 'Money(250)' and str() gives '$2.50'. - amount is a property: setting it to a negative value raises ValueError, **including in __init__**. - == compares amounts, and < compares amounts too. Comparing with a non-Money object should return NotImplemented from your methods (so Money(1) == 1 is simply False).

Hints (3)
  1. Store the value in self._amount and expose it with @property / @amount.setter. In __init__, assign self.amount so the setter validates it.
  2. For str, divmod or // and % split cents into dollars and cents; :02d pads to two digits.
  3. You only need __lt__: Python answers a > b by trying b < a.
Show a solution
class Money:
    def __init__(self, amount):
        self.amount = amount          # goes through the setter

    @property
    def amount(self):
        return self._amount

    @amount.setter
    def amount(self, value):
        if value < 0:
            raise ValueError('amount must not be negative')
        self._amount = value

    def __repr__(self):
        return f'Money({self.amount})'

    def __str__(self):
        return f'${self.amount // 100}.{self.amount % 100:02d}'

    def __eq__(self, other):
        if isinstance(other, Money):
            return self.amount == other.amount
        return NotImplemented

    def __lt__(self, other):
        if isinstance(other, Money):
            return self.amount < other.amount
        return NotImplemented

Exercise 4: Word frequencies

Write word_counts(text) that returns a dict mapping each word in text to the number of times it appears.

- Words are separated by whitespace (use str.split() with no argument). - Counting is case-insensitive: convert words to lower case. - Strip the punctuation characters .,!? from both ends of each word, and skip words that end up empty.

Use a plain dict with get (no collections.Counter).

Hints (3)
  1. text.split() with no argument splits on any whitespace and never produces empty strings.
  2. word.strip('.,!?') removes any of those characters from both ends.
  3. counts[word] = counts.get(word, 0) + 1 handles both new and existing words.
Show a solution
def word_counts(text):
    counts = {}
    for word in text.split():
        word = word.strip('.,!?').lower()
        if word:
            counts[word] = counts.get(word, 0) + 1
    return counts

Exercise 5: Unique items, original order

Write unique_in_order(items) that returns a list of the items in items with duplicates removed, keeping the position of each item's first appearance.

Use a set to remember what you've already seen (so each membership test is fast), and don't modify items.

Hints (2)
  1. A set has no order, so list(set(items)) loses the original positions.
  2. Loop over items, and append an item to the result only if it isn't in a seen set yet; then add it to seen.
Show a solution
def unique_in_order(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result