



















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




















RATIONALE: y = x makes y an alias; y += [4] mutates the list in place, so x becomes [1,2,3,4]. z = x[:] creates a shallow copy; z += [5] modifies only z, leaving x unchanged. Thus x is [1,2,3,4] and z is [1,2,3,4,5].
A. {'a': 1, 'b': 2} B. {'a': 1, 'b': 2, 'c': 3} CORRECT C. {'x': 9} D. {'a': 1, 'b': 2, 'c': 3, 'x': 9} RATIONALE: The parameter d initially references the caller's dictionary. d['c'] = 3 mutates that object. Reassigning d = {'x': 9} only rebinds the local name, leaving the original dictionary with the added key 'c'. Thus the caller sees {'a':1,'b':2,'c':3}.
D. set() RATIONALE: The ^ operator performs symmetric difference, returning elements in either set but not both. A ^ B = (A | B) - (A & B) = {1,2,3,4,5,6} - {3,4} = {1,2,5,6}. Option B is intersection, C is union, D is empty set.
RATIONALE: This computes the Fibonacci sequence: f(0)=0, f(1)=1, f(2)=1, f(3)=2, f(4)=3, f(5)=5, f(6)=8. Thus f(6)=8. Option B is f(5), C is f(7), D is f(8).
A. Error\nDone CORRECT B. Error C. Done D. 1/ RATIONALE: The try block raises ZeroDivisionError, which is caught by the except block printing 'Error'. The finally block always executes, printing 'Done'. Thus output is 'Error' then 'Done'.
A. f = open('file.txt')\ntry:\n data = f.read()\nfinally:\n f.close() B. with open('file.txt') as f:\n data = f.read() CORRECT C. f = open('file.txt')\ndata = f.read()\nf.close() D. try:\n f = open('file.txt')\n data = f.read()\nexcept:\n f.close() RATIONALE: The with statement (context manager) guarantees the file is closed even if an exception occurs. Option A also works but is more verbose and not idiomatic. Option C lacks exception safety. Option D may fail to close if an exception occurs before f is assigned or if close itself raises.
A. It pauses a function and returns a value, making it a generator. CORRECT B. It returns a value and terminates the function. C. It raises an exception. D. It defines a variable scope. RATIONALE: yield is used in generator functions to produce a sequence of values lazily, pausing execution and resuming on subsequent calls. return terminates the function. raise raises exceptions. yield does not define scope.
RATIONALE: The comprehension filters even x (0,2,4) then squares them: 0,4,16. Option C omits 4 (which is even and <5), B includes odd squares, D squares odd numbers instead.
D. TypeError: 'list' object is not callable RATIONALE: Mutable default arguments persist across calls, so b accumulates: [1], then [1,2], then [1,2,3]. B assumes new list each call, C misorders, D is unrelated.
A. The else block of a try/except/else runs only if no exception occurs in the try block. B. A finally block always executes, even if an exception is not caught. C. You can have multiple except clauses to handle different exception types. D. The except block can catch exceptions raised in the else block. CORRECT RATIONALE: Exceptions raised in the else block are not caught by the preceding except clauses; they propagate. A, B, and C are true statements about try/except/else/finally.
A. True CORRECT B. False C. TypeError D. ValueError RATIONALE: All three are falsy, so bool() returns False for each; False == False == False is True. No type or value errors occur.
A. Returns None; nums becomes [5, 4, 3, 1, 1] CORRECT B. Returns [5, 4, 3, 1, 1]; nums unchanged C. Returns None; nums becomes [1, 1, 3, 4, 5] D. Returns [1, 1, 3, 4, 5]; nums unchanged RATIONALE: list.sort() sorts in place and returns None; reverse=True gives descending order. B and D confuse with sorted(), C ignores reverse=True.
RATIONALE: filter keeps evens 0,2,4; map doubles to 0,4,8. B fails to double, C starts at 2 and misses 0, D incorrectly includes 6 (odd filter would exclude 6? 6 is even but range(6) stops at 5).
A. Reassigning a parameter inside a function always affects the caller's variable. B. Mutating a mutable argument inside a function affects the caller's object. CORRECT C. Immutable arguments are copied before being passed to a function. D. Python uses pass-by-value for all arguments. RATIONALE: Mutation of a mutable object (e.g., list.append) changes the caller's object; reassignment only rebinds local name. A is false, C is false (no copy), D mischaracterizes Python's model.
A. The else block executes before the except block. B. The else block executes only if no exception occurs in the try block. CORRECT C. The else block executes regardless of whether an exception occurs. D. The else block is skipped if a finally block is present. RATIONALE: The else clause of a try statement runs only when the try block completes without raising an exception. It is not executed if an exception is caught, and it executes before finally if no exception occurs. Options A, C, and D misstate control flow.
RATIONALE: Slicing with start=1, stop=4, step=2 selects indices 1 and 3, giving [20, 40]. Option B ignores the step. Option C uses a different start/step. Option D incorrectly includes index 4 (50) despite stop=4 being exclusive.
A. {'apple'} {'banana'} B. {'apple'} {'apple', 'banana'} CORRECT C. {'apple', 'banana'} {'apple', 'banana'} D. TypeError: unhashable type: 'set' RATIONALE: The default set is created once and shared across calls, so the second call mutates the same set, yielding {'apple', 'banana'}. Option A assumes new sets each call. Option C assumes both prints show the final state. Option D is incorrect because sets are mutable but hashable elements are added.
A. 'is' compares values; '==' compares identities. B. 'is' compares identities; '==' compares values. CORRECT C. Both compare values, but 'is' is faster. D. 'is' can only be used with numbers; '==' works with all types. RATIONALE: 'is' checks object identity (same memory address), while '==' checks value equality. Option A reverses them. Option C incorrectly claims both compare values. Option D falsely restricts 'is' to numbers.
C. UnboundLocalError D. None RATIONALE: The nonlocal declaration allows inner to modify x in the enclosing scope, so x becomes 15. Option A ignores the increment. Option C would occur without nonlocal. Option D is incorrect because outer returns x.
A. f = open('data.txt') data = f.read() f.close() B. with open('data.txt') as f: data = f.read() CORRECT C. try: f = open('data.txt') data = f.read() except: pass D. f = open('data.txt') data = f.read()
RATIONALE: The with statement guarantees the file is closed via context manager even if an exception occurs. Option A lacks exception safety. Option C may leave the file open if an exception is caught. Option D falsely assumes automatic closing.
A. To modify or enhance a function's behavior without changing its source code. CORRECT B. To convert a function into a class method. C. To enforce type checking at runtime. D. To automatically generate documentation for a function. RATIONALE: Decorators wrap a function to extend or alter its behavior transparently, preserving the original code. Option B describes @classmethod, a specific decorator, not the general purpose. Option C is not inherent to decorators. Option D describes docstring tools, not decorators.
RATIONALE: The nested comprehension iterates x=0,1,2 and y=0,1,2, skipping pairs where x==y, producing products 01,02,10,12,20,21 = 0,0,2,2,4. Options B and D include excluded diagonal products, and C omits valid pairs.
A. 1000, and it completes successfully. B. Approximately 1000, but it raises RecursionError before returning. CORRECT C. 1, because Python optimizes tail recursion. D. 500, due to halving of the call stack. RATIONALE: CPython's default recursion limit is 1000, and g(1000) requires about 1001 nested frames, so a RecursionError is raised before completion. Python does not perform tail-call optimization, and the stack is not halved.
A. The original exception is preserved and the finally exception is logged. B. The finally block's exception replaces the original, and the original is chained as context. CORRECT C. Both exceptions are raised simultaneously as an ExceptionGroup. D. The finally block is skipped to preserve the original exception. RATIONALE: If a finally block raises, that new exception propagates and the original is attached as context (implicit chaining). It is not automatically grouped, and the finally block is not skipped.
A. try: process(f) finally: f.close() B. with open('data.txt', 'r') as f: process(f) CORRECT C. f = open('data.txt', 'r'); process(f); f.close() D. for line in f: process(line) RATIONALE: The with statement uses the context manager protocol to close the file on both normal and exceptional exit. Option A also closes but requires an explicit finally and is less idiomatic; C leaks on exception; D does not close.