Loading…
Programming · short notes, key points and practice questions.
Core Python as placement tests ask it: data types, mutability, list, dict and set behaviour, slicing, comprehensions, functions, scope, closures, generators, exceptions and classes. Most questions show a short snippet and ask what it prints, so the traps are references versus copies, mutable defaults, late binding and operator precedence.
/ always gives a float (4 / 2 is 2.0); // floors toward −∞, so -7 // 2 is -4% takes the sign of the divisor: -7 % 2 is 1, 7 % -2 is -1** is right-associative and binds tighter than unary minus: 2 ** 3 ** 2 = 512, -2 ** 2 = -40.1 + 0.2 == 0.3 is False; round(2.5) is 2 (round half to even)True + True is 2, and {1: 'a', True: 'b'} has one keyand/or return an operand, not a bool: 0 or 'x' is 'x', [] and 5 is []1 < x < 5 means 1 < x and x < 5; is checks identity, == checks values[a:b:c] never raises IndexError; s[::-1] reverses; a slice of a list is a new (shallow) listb = a is an alias; a[:], list(a) and copy.copy(a) are shallow; copy.deepcopy copies nested objects[[0] * 3] * 3 repeats the same inner list three times – changing one row changes alllist.sort() and append() return None; sorted() returns a new listappend(x) adds one element; extend(x) adds each item; lst += 'ab' extends with 'a', 'b'{} is an empty dict, set() an empty set; (5) is an int, (5,) a tupled.get(k, default) never raises; d[k] raises KeyError for a missing key1 and 1.0 are the same elementglobal and nonlocal let a function rebind an outer namedef time, so def f(x=[]) shares one list across calls – use x=None*args collects a tuple, **kwargs a dict[lambda: i for i in range(3)] all return 2; fix with lambda i=i: iyield returns a generator; it is lazy and can be iterated only oncemap, filter, zip return one-shot iterators in Python 3; zip stops at the shortest inputrange is lazy but reusable – it is not a generatortry → except (if error) → else (only if no error) → finally (always)return in finally overrides any earlier return and swallows the exceptionobj.x = 5 creates an instance attribute that shadows the class onesuper() follows the MRO (C3 linearisation) of the actual object, not just the direct parent__eq__ without __hash__ makes instances unhashable; print uses __str__, falling back to __repr__-7 // 2 to be −3 (that is C's truncation, not Python's floor)b = a copies a list, or that a shallow copy protects nested listsx = x.sort() sets x to Noneprint(type(10 / 5))
Answer: A. <class 'float'>
print(2 ** 3 ** 2)
Answer: C. 512
def f(a, b=2, *c, d=4):
return a + b + sum(c) + d
print(f(1, 3, 5, 7, d=1))Answer: D. 17
def make():
acc = []
for i in range(3):
def f(x, i=i):
return x * i
acc.append(f)
acc.append(lambda x: x + i)
return acc
fs = make()
print([f(10) for f in fs])Answer: A. [0, 12, 10, 12, 20, 12]
Answer: B. tuple