Programming FAQ
2 cards- 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]
- A
- 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 []
- A
More Control Flow Tools
3 cards- 03
def append(item, items=[]): items.append(item) return items print(append(1)) print(append(2))What is printed?
- A
[1]then aTypeError, 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]
- A
- 04
for n in [2, 4, 6]: if n % 2: print("odd") break else: print("all even")What is printed?
- A
A
SyntaxError:elsecannot follow aforstatement - B
all even: theelseblock runs when the loop finishes without hittingbreak - C
all eventhree times, once per iteration that did notbreak - D
Nothing:
elseon a loop runs only when the loop body never executed
- A
- 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)
- A
Data Structures
3 cards- 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']
- A
- 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
- A
- 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 itsxnever touches the outer one - B
A
NameError: the comprehension deletedxwhen it finished - C
2: the comprehension's last value ofxleaks into the enclosing scope - D
4: the comprehension leavesxbound to its final element
- A
Classes
3 cards- 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:bnever had a trick added - B
[] - C
None - D
['sit']
- A
- 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
- A
- 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
0is printed, but aDeprecationWarningis emitted for accessing a private name - C
A
SyntaxError: attribute names may not start with two underscores outside the class body - D
0is printed: the double underscore is a naming convention with no effect
- A
Execution Model
2 cards- 12
total = 0 def bump(): total += 1 bump()What happens?
- A
totalbecomes1 - B
Nothing: the function creates a local
totalequal to1and discards it - C
A
NameError: functions cannot see module-level variables withoutglobal - D
An
UnboundLocalError: assigning tototalanywhere inbumpmakes it local for the whole function, so the read before assignment finds nothing
- A
- 13
class Config: factor = 2 values = [factor * i for i in range(3)]What happens when this class body runs?
- A
A
NameErrorforfactor: a comprehension in a class body cannot see the class's own names - B
A
SyntaxError: comprehensions are not allowed in class bodies - C
valuesis[0, 2, 4] - D
valuesis[0, 1, 2], becausefactoris read as1inside the comprehension
- A
Expressions
6 cards- 14
print(1 < 2 == True)What is printed?
- A
1 - B
True - C
False - D
A
TypeError:boolandintcannot be chained in one comparison
- A
- 15
print(-2 ** 2, (-2) ** 2)What is printed?
- A
-4 4 - B
4 -4 - C
-4 -4 - D
4 4
- A
- 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
- A
- 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:
iscompares object identity, and whether two equal integers share one object is an implementation detail; compare numbers with== - C
Truefor values below 256 andFalseabove, as defined by the language - D
False: every integer literal creates a new object
- A
- 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
- A
- 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'sprintbeforeyieldruns at call time andcreatedis skipped - B
createdthenstart: calling a generator function only builds the generator, and the body runs on the firstnext - C
Only
created:nextreturns1without printing - D
startthencreated: the function body runs when it is called
- A
Simple Statements
2 cards- 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 noTypeErroris 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
- A
- 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]
- A
Data Model
3 cards- 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__toNone, 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
- A
- 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 of0is false - B
full:__len__only affectslen(), 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
- A
- 24
class Evens: def __iter__(self): return iter([0, 2, 4]) print(4 in Evens())What happens?
- A
A
TypeError:__iter__must returnselffor the object to be usable within - B
True: with no__contains__, the membership test iterates the object and compares each element - C
False:inon an object without__contains__compares against its attributes - D
A
TypeError:inrequires a__contains__method
- A
Compound Statements
3 cards- 25
def f(): try: return "try" finally: return "finally" print(f())What is printed?
- A
finally - B
try finally - C
try - D
A
SyntaxError: afinallyblock may not containreturn
- A
- 26
try: 1 / 0 except ZeroDivisionError as e: pass print(e)What happens?
- A
An
UnboundLocalError, sinceeis only assigned conditionally - B
division by zerois printed - C
A
NameError: the name bound byas eis deleted when theexceptblock ends - D
Noneis printed, becauseeis reset after the handler
- A
- 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 thematchblock - B
A
SyntaxError: a bare name in acaseis a capture pattern that matches anything, so Python rejects it for making the later cases unreachable - C
redis printed:REDcaptures"blue"and the first case wins at runtime - D
otheris printed
- A
Built-in Functions
3 cards- 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
- A
- 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 withNone - C
A
ValueError: the iterables have different lengths - D
[(1, 'a'), (2, 'b')]:zipstops at the shortest iterable
- A
- 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
- A
Built-in Types
4 cards- 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]]
- A
- 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']
- A
- 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'
- A
- 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
- A
copy: Shallow and deep copy operations
1 card- 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]]
- A
Glossary
1 card- 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
- A
Built-in Exceptions
2 cards- 37
import sys try: sys.exit(1) except Exception: print("caught")What happens?
- A
The program exits:
SystemExitderives fromBaseException, notException, so the handler does not match - B
caughtis printed and the program continues - C
caughtis printed, then the program exits anyway - D
A
TypeError:sys.exitcannot be called insidetry
- A
- 38
def first_two(it): yield next(it) yield next(it) print(list(first_two(iter([1]))))What happens?
- A
A
RuntimeError: aStopIterationescaping a generator body is converted, so it cannot be mistaken for the generator finishing - B
[1, None]is printed: an exhausted iterator yieldsNone - C
A
StopIterationpropagates to the caller as a normal exception - D
[1]is printed: the innerStopIterationends the generator cleanly
- A
dataclasses
2 cards- 39
from dataclasses import dataclass @dataclass class Team: members: list = []What happens?
- A
A
ValueErrorat class creation: a mutable default is rejected, andfield(default_factory=list)is required instead - B
The class is created and each
Teamgets a fresh empty list - C
The class is created and every
Teamshares onememberslist - D
A
TypeErrorat the firstTeam()call, because the field has no type annotation
- A
- 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__; useobject.__setattr__(self, "norm", ...) - B
A
Pointwithnormequal to0.0, because__post_init__runs before the defaults - C
A
Pointwithnormequal to5.0 - D
A
TypeError: frozen dataclasses may not define__post_init__
- A
Floating-Point Arithmetic
1 card- 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
- A
typing
1 card- 42
def total(items: list[int]) -> int: return sum(items) print(total([1.5, 2.5]))What happens?
- A
A
TypeError: the return value4.0does not match-> int - B
4.0is printed: annotations are stored, not enforced, and nothing checks them at runtime - C
4is printed: the annotation converts the elements toint - D
A
TypeError: the list contains floats, not ints
- A
asyncio: Coroutines and Tasks
2 cards- 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,
fetchingnever appears, and aRuntimeWarningsays the coroutine was never awaited - B
A
TypeError: a coroutine must be awaited before it can be assigned to a variable - C
1is printed: calling anasync defruns it to completion synchronously - D
fetchingthen1are printed
- A
- 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.sleepblocks the whole event loop, so the coroutines run one after another - C
About 1 second:
time.sleepis automatically converted toasyncio.sleepinside a coroutine - D
About 1 second:
gatherruns the three coroutines concurrently
- A
Modules
1 card- 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.pyprints what?- A
loading countertwice, then0 - B
loading counteronce, then1 - C
loading counteronce, then0 - D
loading countertwice, then1
- A
End of deck · 45 cards