Card type

Programming FAQ

2 cards
  1. 01
    fns = [lambda: i for i in range(3)]
    print([f() for f in fns])
    

    What is printed?

    • A

      [2, 2, 2]

    • B

      [None, None, None]

    • C

      [0, 1, 2]

    • D

      [3, 3, 3]

  2. 02
    def add(item, items):
        items.append(item)
        return items
    
    base = []
    a = add(1, base)
    b = add(2, base)
    print(a is b, base)
    

    What is printed?

    • A

      True [1, 2]

    • B

      True [2]

    • C

      False [1, 2]

    • D

      False []

More Control Flow Tools

3 cards
  1. 03
    def append(item, items=[]):
        items.append(item)
        return items
    
    print(append(1))
    print(append(2))
    

    What is printed?

    • A

      [1] then a TypeError, because the default list is read-only

    • B

      [1, 2] twice, because defaults are shared across all calls before the body runs

    • C

      [1] then [1, 2]

    • D

      [1] then [2]

  2. 04
    for n in [2, 4, 6]:
        if n % 2:
            print("odd")
            break
    else:
        print("all even")
    

    What is printed?

    • A

      A SyntaxError: else cannot follow a for statement

    • B

      all even: the else block runs when the loop finishes without hitting break

    • C

      all even three times, once per iteration that did not break

    • D

      Nothing: else on a loop runs only when the loop body never executed

  3. 05
    def connect(host, /, port, *, timeout):
        ...
    

    Which call is rejected?

    • A

      connect("db", port=5432, timeout=3)

    • B

      connect(host="db", port=5432, timeout=3)

    • C

      connect("db", timeout=3, port=5432)

    • D

      connect("db", 5432, timeout=3)

Data Structures

3 cards
  1. 06
    names = ["b", "a"]
    result = names.sort()
    print(result, names)
    

    What is printed?

    • A

      ['a', 'b'] ['b', 'a']

    • B

      None ['b', 'a']

    • C

      None ['a', 'b']

    • D

      ['a', 'b'] ['a', 'b']

  2. 07
    a = (1)
    b = 1,
    c = ()
    print(type(a).__name__, type(b).__name__, type(c).__name__)
    

    What is printed?

    • A

      int int tuple

    • B

      int tuple tuple

    • C

      tuple int tuple

    • D

      tuple tuple tuple

  3. 08
    x = "outer"
    squares = [x * x for x in range(3)]
    print(x)
    

    What is printed?

    • A

      outer: a comprehension has its own scope, so its x never touches the outer one

    • B

      A NameError: the comprehension deleted x when it finished

    • C

      2: the comprehension's last value of x leaks into the enclosing scope

    • D

      4: the comprehension leaves x bound to its final element

Classes

3 cards
  1. 09
    class Dog:
        tricks = []
    
        def add_trick(self, trick):
            self.tricks.append(trick)
    
    a, b = Dog(), Dog()
    a.add_trick("sit")
    print(b.tricks)
    

    What is printed?

    • A

      An AttributeError: b never had a trick added

    • B

      []

    • C

      None

    • D

      ['sit']

  2. 10
    class Counter:
        count = 0
    
        def hit(self):
            self.count += 1
    
    a, b = Counter(), Counter()
    a.hit()
    a.hit()
    print(a.count, b.count, Counter.count)
    

    What is printed?

    • A

      2 0 0

    • B

      2 0 2

    • C

      2 2 0

    • D

      2 2 2

  3. 11
    class Account:
        def __init__(self):
            self.__balance = 0
    
    acct = Account()
    print(acct.__balance)
    

    What happens?

    • A

      An AttributeError: the name was mangled to _Account__balance, and only that spelling exists on the instance

    • B

      0 is printed, but a DeprecationWarning is emitted for accessing a private name

    • C

      A SyntaxError: attribute names may not start with two underscores outside the class body

    • D

      0 is printed: the double underscore is a naming convention with no effect

Execution Model

2 cards
  1. 12
    total = 0
    
    def bump():
        total += 1
    
    bump()
    

    What happens?

    • A

      total becomes 1

    • B

      Nothing: the function creates a local total equal to 1 and discards it

    • C

      A NameError: functions cannot see module-level variables without global

    • D

      An UnboundLocalError: assigning to total anywhere in bump makes it local for the whole function, so the read before assignment finds nothing

  2. 13
    class Config:
        factor = 2
        values = [factor * i for i in range(3)]
    

    What happens when this class body runs?

    • A

      A NameError for factor: a comprehension in a class body cannot see the class's own names

    • B

      A SyntaxError: comprehensions are not allowed in class bodies

    • C

      values is [0, 2, 4]

    • D

      values is [0, 1, 2], because factor is read as 1 inside the comprehension

Expressions

6 cards
  1. 14
    print(1 < 2 == True)
    

    What is printed?

    • A

      1

    • B

      True

    • C

      False

    • D

      A TypeError: bool and int cannot be chained in one comparison

  2. 15
    print(-2 ** 2, (-2) ** 2)
    

    What is printed?

    • A

      -4 4

    • B

      4 -4

    • C

      -4 -4

    • D

      4 4

  3. 16
    print(0 or "default", 2 and 3, None or 0)
    

    What is printed?

    • A

      True True False

    • B

      default 3 0

    • C

      default True 0

    • D

      False True None

  4. 17
    a = 1000
    b = 1000
    print(a is b)
    

    What does the language guarantee about the output?

    • A

      True: equal integers are always the same object

    • B

      Nothing: is compares object identity, and whether two equal integers share one object is an implementation detail; compare numbers with ==

    • C

      True for values below 256 and False above, as defined by the language

    • D

      False: every integer literal creates a new object

  5. 18
    nan = float("nan")
    print(nan == nan, nan in [nan])
    

    What is printed?

    • A

      False False

    • B

      True False

    • C

      False True

    • D

      True True

  6. 19
    def numbers():
        print("start")
        yield 1
    
    g = numbers()
    print("created")
    next(g)
    

    In what order are the two messages printed?

    • A

      Only start: a generator function's print before yield runs at call time and created is skipped

    • B

      created then start: calling a generator function only builds the generator, and the body runs on the first next

    • C

      Only created: next returns 1 without printing

    • D

      start then created: the function body runs when it is called

Simple Statements

2 cards
  1. 20
    t = ([],)
    try:
        t[0] += [1]
    except TypeError:
        pass
    print(t)
    

    What is printed?

    • A

      ([],): the tuple rejected the assignment, so nothing changed

    • B

      ([],), and no TypeError is raised because the list was modified in place

    • C

      ([1],): the list was extended in place before the tuple refused to store the result

    • D

      ([1, 1],): the list was extended twice, once before and once after the error

  2. 21
    a = [1]
    b = a
    a += [2]
    a = a + [3]
    print(b)
    

    What is printed?

    • A

      [1]

    • B

      [1, 3]

    • C

      [1, 2, 3]

    • D

      [1, 2]

Data Model

3 cards
  1. 22
    class Point:
        def __init__(self, x, y):
            self.x, self.y = x, y
    
        def __eq__(self, other):
            return (self.x, self.y) == (other.x, other.y)
    
    print({Point(1, 2)})
    

    What happens?

    • A

      A set with one point is printed

    • B

      A TypeError: defining __eq__ without __hash__ sets __hash__ to None, making the class unhashable

    • C

      A TypeError: user-defined classes are never hashable

    • D

      A set with one point is printed, hashed by identity as usual

  2. 23
    class Bag:
        def __init__(self):
            self.items = []
    
        def __len__(self):
            return len(self.items)
    
    if Bag():
        print("full")
    else:
        print("empty")
    

    What is printed?

    • A

      empty: with no __bool__, truth testing falls back to __len__, and a length of 0 is false

    • B

      full: __len__ only affects len(), not truth testing

    • C

      full: every object is truthy unless it defines __bool__

    • D

      A TypeError: objects without __bool__ cannot be used in a condition

  3. 24
    class Evens:
        def __iter__(self):
            return iter([0, 2, 4])
    
    print(4 in Evens())
    

    What happens?

    • A

      A TypeError: __iter__ must return self for the object to be usable with in

    • B

      True: with no __contains__, the membership test iterates the object and compares each element

    • C

      False: in on an object without __contains__ compares against its attributes

    • D

      A TypeError: in requires a __contains__ method

Compound Statements

3 cards
  1. 25
    def f():
        try:
            return "try"
        finally:
            return "finally"
    
    print(f())
    

    What is printed?

    • A

      finally

    • B

      try finally

    • C

      try

    • D

      A SyntaxError: a finally block may not contain return

  2. 26
    try:
        1 / 0
    except ZeroDivisionError as e:
        pass
    
    print(e)
    

    What happens?

    • A

      An UnboundLocalError, since e is only assigned conditionally

    • B

      division by zero is printed

    • C

      A NameError: the name bound by as e is deleted when the except block ends

    • D

      None is printed, because e is reset after the handler

  3. 27
    RED = "red"
    
    def describe(color):
        match color:
            case RED:
                return "red"
            case _:
                return "other"
    
    print(describe("blue"))
    

    What happens?

    • A

      A NameError: constants must be declared inside the match block

    • B

      A SyntaxError: a bare name in a case is a capture pattern that matches anything, so Python rejects it for making the later cases unreachable

    • C

      red is printed: RED captures "blue" and the first case wins at runtime

    • D

      other is printed

Built-in Functions

3 cards
  1. 28
    print(round(0.5), round(1.5), round(2.5))
    

    What is printed?

    • A

      0 1 2

    • B

      0 2 2

    • C

      1 2 3

    • D

      1 2 2

  2. 29
    print(list(zip([1, 2, 3], "ab")))
    

    What is printed?

    • A

      [(1, 'a'), (2, 'b'), (3, 'a')]: the shorter iterable is cycled

    • B

      [(1, 'a'), (2, 'b'), (3, None)]: missing values are padded with None

    • C

      A ValueError: the iterables have different lengths

    • D

      [(1, 'a'), (2, 'b')]: zip stops at the shortest iterable

  3. 30
    print(isinstance(True, int), True + True, sum([True, False, True]))
    

    What is printed?

    • A

      True True 2

    • B

      False 2 2

    • C

      A TypeError: booleans do not support arithmetic

    • D

      True 2 2

Built-in Types

4 cards
  1. 31
    grid = [[0] * 2] * 3
    grid[0][0] = 1
    print(grid)
    

    What is printed?

    • A

      [[1, 0], [1, 0], [0, 0]]

    • B

      [[1, 1], [0, 0], [0, 0]]

    • C

      [[1, 0], [1, 0], [1, 0]]

    • D

      [[1, 0], [0, 0], [0, 0]]

  2. 32
    print("a  b".split(), "a  b".split(" "))
    

    What is printed?

    • A

      ['a', '', 'b'] ['a', '', 'b']

    • B

      ['a', 'b'] ['a', '', 'b']

    • C

      ['a', 'b'] ['a', 'b']

    • D

      ['a', '', 'b'] ['a', 'b']

  3. 33
    data = b"abc"
    print(data[0], data[0:1])
    

    What is printed?

    • A

      97 b'a'

    • B

      97 97

    • C

      b'a' b'a'

    • D

      'a' 'a'

  4. 34
    d1 = {"a": 1, "b": 2}
    d2 = {"b": 2, "a": 1}
    print(d1 == d2, list(d1) == list(d2))
    

    What is printed?

    • A

      False False

    • B

      False True

    • C

      True True

    • D

      True False

copy: Shallow and deep copy operations

1 card
  1. 35
    a = [[1], [2]]
    b = a[:]
    b[0].append(9)
    b.append([3])
    print(a)
    

    What is printed?

    • A

      [[1, 9], [2]]

    • B

      [[1], [2]]

    • C

      [[1, 9], [2], [3]]

    • D

      [[1], [2], [3]]

Glossary

1 card
  1. 36
    evens = (n for n in range(6) if n % 2 == 0)
    print(sum(evens), list(evens))
    

    What is printed?

    • A

      A TypeError: a generator cannot be consumed twice

    • B

      6 [0, 2, 4]

    • C

      6 []

    • D

      6 [0, 2, 4], but only in Python 3.12 and later

Built-in Exceptions

2 cards
  1. 37
    import sys
    
    try:
        sys.exit(1)
    except Exception:
        print("caught")
    

    What happens?

    • A

      The program exits: SystemExit derives from BaseException, not Exception, so the handler does not match

    • B

      caught is printed and the program continues

    • C

      caught is printed, then the program exits anyway

    • D

      A TypeError: sys.exit cannot be called inside try

  2. 38
    def first_two(it):
        yield next(it)
        yield next(it)
    
    print(list(first_two(iter([1]))))
    

    What happens?

    • A

      A RuntimeError: a StopIteration escaping a generator body is converted, so it cannot be mistaken for the generator finishing

    • B

      [1, None] is printed: an exhausted iterator yields None

    • C

      A StopIteration propagates to the caller as a normal exception

    • D

      [1] is printed: the inner StopIteration ends the generator cleanly

dataclasses

2 cards
  1. 39
    from dataclasses import dataclass
    
    @dataclass
    class Team:
        members: list = []
    

    What happens?

    • A

      A ValueError at class creation: a mutable default is rejected, and field(default_factory=list) is required instead

    • B

      The class is created and each Team gets a fresh empty list

    • C

      The class is created and every Team shares one members list

    • D

      A TypeError at the first Team() call, because the field has no type annotation

  2. 40
    from dataclasses import dataclass
    
    @dataclass(frozen=True)
    class Point:
        x: float
        y: float
        norm: float = 0.0
    
        def __post_init__(self):
            self.norm = (self.x ** 2 + self.y ** 2) ** 0.5
    
    Point(3, 4)
    

    What happens?

    • A

      A FrozenInstanceError: assignment is blocked even inside __post_init__; use object.__setattr__(self, "norm", ...)

    • B

      A Point with norm equal to 0.0, because __post_init__ runs before the defaults

    • C

      A Point with norm equal to 5.0

    • D

      A TypeError: frozen dataclasses may not define __post_init__

Floating-Point Arithmetic

1 card
  1. 41
    print(0.1 + 0.2 == 0.3, round(2.675, 2))
    

    What is printed?

    • A

      False 2.68

    • B

      False 2.67

    • C

      True 2.68

    • D

      True 2.67

typing

1 card
  1. 42
    def total(items: list[int]) -> int:
        return sum(items)
    
    print(total([1.5, 2.5]))
    

    What happens?

    • A

      A TypeError: the return value 4.0 does not match -> int

    • B

      4.0 is printed: annotations are stored, not enforced, and nothing checks them at runtime

    • C

      4 is printed: the annotation converts the elements to int

    • D

      A TypeError: the list contains floats, not ints

asyncio: Coroutines and Tasks

2 cards
  1. 43
    import asyncio
    
    async def fetch():
        print("fetching")
        return 1
    
    async def main():
        result = fetch()
        print(result)
    
    asyncio.run(main())
    

    What happens?

    • A

      A coroutine object is printed, fetching never appears, and a RuntimeWarning says the coroutine was never awaited

    • B

      A TypeError: a coroutine must be awaited before it can be assigned to a variable

    • C

      1 is printed: calling an async def runs it to completion synchronously

    • D

      fetching then 1 are printed

  2. 44
    import asyncio, time
    
    async def slow():
        time.sleep(1)
        return "done"
    
    async def main():
        await asyncio.gather(slow(), slow(), slow())
    
    asyncio.run(main())
    

    Roughly how long does this take, and why?

    • A

      It never finishes: blocking inside a coroutine deadlocks the loop

    • B

      About 3 seconds: time.sleep blocks the whole event loop, so the coroutines run one after another

    • C

      About 1 second: time.sleep is automatically converted to asyncio.sleep inside a coroutine

    • D

      About 1 second: gather runs the three coroutines concurrently

Modules

1 card
  1. 45
    # counter.py
    print("loading counter")
    count = 0
    
    # main.py
    import counter
    import counter
    counter.count += 1
    from counter import count
    print(count)
    

    Running main.py prints what?

    • A

      loading counter twice, then 0

    • B

      loading counter once, then 1

    • C

      loading counter once, then 0

    • D

      loading counter twice, then 1

End of deck · 45 cards

Save