Extras · Practice

Quiz & exercises

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

Quiz

1. What does this print?
import random

random.seed(42)
a = [random.randint(1, 100) for _ in range(5)]
random.seed(42)
b = [random.randint(1, 100) for _ in range(5)]
print(a == b)
2. What does this print?
import random

random.seed(0)
x = random.random()
y = random.random()
print(x == y)
3. You need to pick 5 different winners from a list of 100 entrants. Which call is right?
4. What happens here?
import random
print(random.sample(range(5), k=10))
5. Which cum_weights value is equivalent to weights=[5, 3, 2]?
6. What does timeit(stmt, setup, number=1000) return?
7. What does this print?
from timeit import timeit

data = list(range(100))
try:
    timeit('sum(data)', number=10)
    print('ok')
except NameError:
    print('NameError')
8. What does this print?
_missing = object()

def f(a=_missing):
    return a is _missing

print(f(None), f())
9. Why is def f(x='__no_value__') a weaker sentinel than def f(x=_sentinel) with _sentinel = object()?
10. What does this print?
import argparse

parser = argparse.ArgumentParser(prog='app')
parser.add_argument('n', type=int)
parser.add_argument('--twice', action='store_true')
args = parser.parse_args(['21', '--twice'])
print(args.n * 2 if args.twice else args.n)
11. A script runs parser.parse_args() and the user passes an invalid value. What happens?
12. What does this print? (Python 3.10+)
def kind(x):
    match x:
        case 0:
            return 'zero'
        case 1 | 2 | 3:
            return 'small'
        case _:
            return 'other'

print(kind(2), kind(7))

Coding exercises

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

Exercise 1: A repeatable card deal

Write deal(n, seed=None) that returns a list of n different cards from the 52-card deck DECK.

Requirements: the same seed must always produce the same hand, no card may appear twice, and asking for more than 52 cards must raise ValueError.

Hints (3)
  1. choices picks with replacement. Which function picks without replacement?
  2. Seed the generator at the start of the function so each call with the same seed starts from the same state.
  3. random.sample already raises ValueError when k is larger than the population.
Show a solution
import random

suits = 'CDHS'
ranks = [str(r) for r in range(2, 11)] + list('JQKA')
DECK = [rank + suit for suit in suits for rank in ranks]

def deal(n, seed=None):
    random.seed(seed)
    return random.sample(DECK, k=n)

Exercise 2: A lookup that allows None as a default

Write lookup(mapping, key, default=...) that returns mapping[key] if the key exists.

If the key is missing: return default if the caller passed one (even if it is None), otherwise raise KeyError(key).

Use a private sentinel object, not None, as the parameter's default.

Hints (2)
  1. Create a unique object at module level, for example _sentinel = object(), and make it the default.
  2. Compare with is: if default is _sentinel: is true only when the caller passed nothing.
Show a solution
_sentinel = object()

def lookup(mapping, key, default=_sentinel):
    if key in mapping:
        return mapping[key]
    if default is _sentinel:
        raise KeyError(key)
    return default

Exercise 3: A command line greeter

Write greet(argv) that parses the list argv with argparse and returns a list of greeting lines.

The interface: a required positional name; an option -t/--times (an int, default 1) giving how many lines to return; and a flag --shout that upper-cases the greeting. Each line is 'Hello, <name>!'.

Invalid input (such as -t abc or a missing name) should behave like any argparse error and raise SystemExit.

Hints (3)
  1. add_argument('-t', '--times', type=int, default=1) gives you args.times as an integer.
  2. A flag with no value uses action='store_true'.
  3. [line] * n builds a list with n copies of line.
Show a solution
import argparse

def greet(argv):
    parser = argparse.ArgumentParser(prog='greet.py', description='Greets someone.')
    parser.add_argument('name', help='who to greet')
    parser.add_argument('-t', '--times', type=int, default=1, help='number of greetings')
    parser.add_argument('--shout', action='store_true', help='use capital letters')
    args = parser.parse_args(argv)

    line = f'Hello, {args.name}!'
    if args.shout:
        line = line.upper()
    return [line] * args.times