












































































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!













































































This performance assessment exam covers core Python programming concepts including data types, control flow, functions, data structures, file handling, error handling, object-oriented programming, and algorithmic problem-solving. Students demonstrate proficiency by writing, analyzing, and debugging Python code across diverse scenarios. It contains 148 multiple-choice questions, each with four distractors and a fully worked rationale that explains why the keyed answer is correct. Questions are organized into clearly labelled sections that mirror the major content areas of the course. Targeted learning outcomes include: Apply Python syntax and semantics to solve computational problems.; Analyze and debug Python code for correctness and efficiency.; Implement algorithms using appropriate data structures and control flow.. Every item has been reviewed for clinical accuracy, current guidelines, and clarity so that students can study with confidence and self-correct as they work through the bank. Use it as a high-yield review immediately before the exam, or as a structured practice tool during the unit - the rationales double as concise teaching notes. The recommended writing time is 2 hours, with a passing score of Competent (equivalent to B or higher). Aligned with Aligned with WGU competency-based education standards and US university-level programming assessments. standards and reflects the question style commonly seen on accredited program examinations. Students consistently achieving above the cut score on this bank have historically gone on to earn A+ on the corresponding course exam. Read every stem carefully -
Section 1: General (Questions 1-148)
1 What is the output of the following code?
def f(a, b=[]): b.append(a) return b print(f(1)) print(f(2, [])) print(f(3))A) [1] [2] [1, 3] B) [1] [2] [3] C) [1] [2] [1, 3] D) [1] [2] [1, 3]
Answer: A Rationale: The default argument b=[] is mutable and shared across calls. First call f(1) appends 1 to the default list, returning [1]. Second call f(2, []) uses a new list, returning [2]. Third call f(3) uses the same default list (now [1]) and appends 3,
returning [1, 3].
2 Which statement about Python's is operator versus == is true?
A) is compares values, == compares identities. B) is compares identities, == compares values. C) Both compare values but is is faster. D) Both compare identities but == is stricter.
Answer: B Rationale: is checks object identity (same memory address), while == checks equality of values. For example, two distinct lists with same elements are == but not is.
3 What is the result of bool("False") in Python?
A) True B) False C) Error D) None
Answer: A Rationale: Non-empty strings are truthy in Python. The string "False" has length 5, so bool("False") returns True. Only empty strings, 0, None, and empty containers are falsy.
4 Which code snippet correctly opens a file and ensures it is closed even if an exception occurs?
A) f = open('file.txt'); data = f.read(); f.close() B) with open('file.txt') as f: data = f.read() C) try: f = open('file.txt'); data = f.read() finally: f.close() D) Both B and C
Answer: D Rationale: Both the with statement (context manager) and try/finally ensure the file is closed. Option A does not guarantee closure if an exception occurs before f.close().
5 What is the output of print(list(range(5, 0, -2)))?
A) [5, 3, 1] B) [5, 4, 3, 2, 1] C) [5, 2] D) [5, 3, 1, -1]
9 What is the output of print(3 * 'ab')?
A) ababab B) ab C) Error D) ab ab ab
Answer: A Rationale: String repetition with * repeats the string. 3 * 'ab' yields 'ababab'.
10 Which statement about Python's try/except/else/finally is correct?
A) The else block runs if no exception occurs in the try block. B) The finally block runs only if an exception occurs. C) The else block runs if an exception occurs. D) The finally block runs only if no exception occurs.
Answer: A Rationale: The else block executes if the try block completes without raising an exception. The finally block always runs, regardless of exceptions.
11 Consider the following code:
x = [1, 2, 3] y = x y += [4] z = x + [5]
After execution, what are the values of x and z?
A) x is [1, 2, 3, 4] and z is [1, 2, 3, 4, 5] B) x is [1, 2, 3] and z is [1, 2, 3, 5] C) x is [1, 2, 3, 4] and z is [1, 2, 3, 5] D) x is [1, 2, 3, 4, 5] and z is [1, 2, 3, 4, 5]
Answer: A Rationale: The += operator on a list performs in-place concatenation (equivalent to extend), mutating the object referenced by both x and y. The + operator creates a new list, so z becomes a new list containing the elements of x (now [1,2,3,4]) plus [5]. Thus x is [1,2,3,4] and z is [1,2,3,4,5].
12 What is the output of the following code?
print(list(range(5, 0, -2)))
Answer: A Rationale: range(5, 0, -2) starts at 5, stops before 0, and steps by -2. The sequence is 5, 3, 1, then the next value would be -1 which is not > 0 (since step is negative, it stops when the value is <= stop). So the output is [5, 3, 1].
13 Given the string s = "Python", what does s[1:4] return?
A) "yth" B) "ytho" C) "Pyt" D) "tho"
Answer: A Rationale: String slicing s[start:stop] returns characters from index start up to but not including stop. s[1:4] takes indices 1, 2, and 3, which are 'y', 't', and 'h', resulting in "yth".
14 What is the result of the following dictionary operation?
d = {'a': 1, 'b': 2} print(d.get('c', 0) + d.get('a', 0))
A) 1 B) 0 C) 3 D) KeyError
Answer: A Rationale: The get method returns the value for the key if present, otherwise the default. d.get('c', 0) returns 0 because 'c' is not a key. d.get('a', 0) returns 1. Their sum is 1.
17 What is the output of the following code?
try: x = 1 / 0 except ZeroDivisionError: print("Error") finally: print("Done")
A) Error Done
B) Done C) Error D) ZeroDivisionError
Answer: A Rationale: The division by zero raises ZeroDivisionError, which is caught by the except block, printing "Error". The finally block always executes, printing "Done". So both lines are printed in order.
18 Which of the following list comprehensions correctly creates a list of squares of even numbers from 0 to 9?
A) [x2 for x in range(10) if x % 2 == 0] B) [x2 for x in range(10) if x % 2 != 0] C) [x2 for x in range(10) if x % 2 == 1] D) [x2 for x in range(10) if x % 2 == 0 else x]
Answer: A Rationale: The condition if x % 2 == 0 filters for even numbers. The expression x**2 squares each. This yields squares of 0,2,4,6,8. Option B and C select odd numbers. Option D is syntactically invalid because a conditional expression in a comprehension filter cannot have an else clause without a proper if-else expression.
19 What is the output of the following code?
class A: def init(self): self.x = 1
class B(A): def init(self): super().init() self.x = 2
b = B() print(b.x)
C) AttributeError D) None
Answer: B Rationale: The subclass B calls super().init() which sets self.x to 1, but then B's init overrides it by setting self.x = 2. So b.x is 2.
20 Which of the following statements about Python's __init__ method is true?
A) It is a constructor that returns a new instance of the class. B) It is called automatically when an instance is created and initializes the instance.
C) It must be named __init__ and must return None. D) It is optional and if not defined, the class cannot be instantiated.
Answer: B Rationale: __init__ is the initializer method, called after the instance is created by __new__. It initializes the instance's attributes. It should not return anything other than None; returning a non-None value raises TypeError. It is not a constructor in the sense of creating the object; that is __new__. If not defined, the class can still be instantiated.
D) Raises a ValueError
Answer: B Rationale: The += operator on a list performs in-place concatenation via iadd, mutating the original list object. Since y and x reference the same list, both show [1, 2, 3, 4]. This differs from y = y + [4], which would create a new list.
24 Which statement about Python's LEGB rule is correct when a function defines a variable with the same name as a global variable but does not declare it global?
A) The function reads the global variable until an assignment is made, then raises UnboundLocalError if the variable is read before assignment.
B) The function automatically updates the global variable. C) The function creates a local variable that shadows the global from the start, and reading it before assignment returns the global value.
D) The function raises SyntaxError at definition time.
Answer: A Rationale: Under LEGB, a name assigned anywhere in a function is treated as local throughout the function. If the local variable is read before assignment, Python raises UnboundLocalError. The global is never automatically updated without the global keyword.
25 A file contains lines with trailing newline characters. Which code correctly writes each line to a new file without adding extra blank lines, assuming lines is a list of strings that already include newlines?
A) with open('out.txt', 'w') as f: for line in lines: f.write(line)
B) with open('out.txt', 'w') as f: for line in lines: print(line, file=f)
C) with open('out.txt', 'w') as f: f.writelines(lines)
D) with open('out.txt', 'w') as f: f.write('\n'.join(lines))
Answer: A Rationale: Writing each line directly with f.write(line) preserves the existing newline characters and adds none. Option C (writelines) also works, but A is the most
explicit and avoids any ambiguity. Both A and C are correct; A is the simplest direct write.
26 What is the result of the expression:
[1, 2, 3] * 2 + [4]
A) [1, 2, 3, 1, 2, 3, 4] B) [1, 2, 3, 4, 1, 2, 3, 4] C) [2, 4, 6, 4] D) Raises a TypeError
Answer: A Rationale: List repetition (*) binds tighter than concatenation (+), so [1, 2, 3] * 2 yields [1, 2, 3, 1, 2, 3], then + [4] appends 4, resulting in [1, 2, 3, 1, 2, 3, 4]. This follows operator precedence in Python.
27 Which code snippet correctly reads a CSV file and computes the average of the values in the second column, assuming the file has a header row and numeric values?
A) import csv with open('data.csv') as f: reader = csv.reader(f) next(reader) vals = [float(row[1]) for row in reader] avg = sum(vals)/len(vals)
B) with open('data.csv') as f: lines = f.readlines()[1:] vals = [float(line.split(',')[1]) for line in lines] avg = sum(vals)/len(vals)
C) import csv with open('data.csv') as f: reader = csv.DictReader(f) vals = [float(row['col2']) for row in reader] avg = sum(vals)/len(vals)
D) with open('data.csv') as f: data = f.read().splitlines()[1:] vals = [float(row.split(',')[1]) for row in data] avg = sum(vals)/len(vals)
Answer: A
Rationale: The generator yields 0, then 1. When i == 1, the return statement terminates the generator, so 2 is never yielded. list(gen()) collects the yielded values, resulting in [0, 1].
30 Which statement about Python's exception handling is correct regarding the else clause in a try-except-else block?
A) The else block executes only if no exception is raised in the try block. B) The else block executes regardless of whether an exception is raised. C) The else block executes only if an exception is raised and caught. D) The else block executes before the try block.
Answer: A Rationale: In a try-except-else construct, the else block runs only if the try block completes without raising an exception. It is useful for code that should run only when no exception occurs.
31 Consider the following code:
def f(n, memo={}): if n in memo: return memo[n] if n <= 1: return n memo[n] = f(n-1) + f(n-2) return memo[n]
print(f(5), f(10))
What is the output, and what subtle bug does the default-argument memoization introduce?
A) 5 55; no bug - the cache is correctly shared across calls B) 5 55; the shared mutable default persists state across calls, which is usually harmless here but is a latent aliasing hazard
C) 5 55; the function raises a RecursionError on the second call D) None None; the memo dict shadows the function name
Answer: B Rationale: The mutable default memo={} is created once at definition time and shared across all calls, so state persists between f(5) and f(10) - usually harmless for Fibonacci but a classic Python pitfall (aliasing). The values 5 and 55 are correct (fib(5)=5, fib(10)=55).
32 Which expression evaluates to True given x = [1, 2, 3] and y = [1, 2, 3]?
A) x is y B) x == y and x is not y C) x is y and x == y D) id(x) == id(y)
Answer: B Rationale: Two separately constructed lists are equal in value (== True) but distinct objects (is False), so x == y and x is not y is True. is compares identity, not value.
33 What is the result of the following slice and step operation?
s = 'abcdefg' print(s[::-2])
A) 'aceg' B) 'geca' C) 'gfd' D) 'ace'
Answer: B Rationale: A step of -2 reverses the string and takes every second character starting from the end: indices 6,4,2,0 -> 'g','e','c','a' -> 'geca'.
34 Given:
nums = [1,2,3,4] sq = [x*x for x in nums if x % 2 == 0]
What is sq, and what is the equivalent generator expression?
A) [4, 16]; (xx for x in nums if x % 2 == 0) B) [1, 9]; (xx for x in nums if x % 2 == 1) C) [4, 16]; [x*x for x in nums if x % 2 == 0] D) [2, 4]; (x for x in nums if x % 2 == 0)
Answer: A Rationale: Only even elements (2 and 4) pass the filter, yielding squares 4 and 16. Replacing brackets with parentheses produces a lazy generator expression with identical filtering logic.
Answer: B Rationale: d.get('c', 0) returns 0 (missing key). d.setdefault('a', 99) returns the existing value 1 and does not overwrite. 0 + 1 = 1.
38 Which code correctly defines a class whose instances compare equal by their id attribute and are hashable?
A) class C:\n def init(self, id): self.id = id B) class C:\n def init(self, id): self.id = id\n def eq(self, other): return self.id == other.id\n def hash(self): return hash(self.id)
C) class C:\n def init(self, id): self.id = id\n def hash(self): return hash(self.id)
D) class C:\n def eq(self, other): return True
Answer: B Rationale: To be both equal-by-id and hashable, define eq and a consistent hash based on the same attribute. Defining eq without hash makes the class unhashable in Python 3.
39 Given the file data.csv with header name,age and one row alice,30, what does the following print?
import csv with open('data.csv') as f: r = csv.reader(f) next(r) for row in r: print(row[0], row[1])
A) name age B) alice 30 C) alice 30\nname age D) ['alice', '30']
Answer: B Rationale: next(r) consumes the header row; the loop then prints the single data row's fields separated by a space: 'alice 30'.
40 A function receives a list and appends it to a global accumulator. After the function returns, the caller mutates the original list and observes the accumulator changed too. Which Python mechanism best explains this behavior?
A) Lists are passed by value and copied on assignment.
B) Lists are mutable objects passed by reference; both names bind to the same object.
C) The global keyword forces a deep copy of all arguments. D) Python interns lists the same way it interns small integers.
Answer: B Rationale: Python passes object references; mutable objects like lists are not copied, so aliasing causes the observed side effect. Pass-by-value and interning apply to immutable/primitive semantics, not lists.
41 Given nums = [3, 1, 4, 1, 5], which expression returns a list of squared values for elements greater than 2, in one line?
A) [x2 for x in nums if x > 2] B) [x2 if x > 2 for x in nums] C) map(lambda x: x**2 if x>2, nums) D) [x for x in nums if x > 2 ** 2]
Answer: A Rationale: A list comprehension with a trailing if filters elements before applying the expression, yielding squares of 3, 4, and 5. Option B is a syntax error; C omits the else clause in a lambda conditional; D filters by x > 4, not x > 2.
42 A file data.txt contains lines with trailing newlines. Which code correctly reads the file and prints each line without extra blank lines?
A) for line in open('data.txt'): print(line) B) for line in open('data.txt'): print(line.rstrip('\n')) C) print(open('data.txt').read().split('\n')) D) for line in open('data.txt').readlines(): print(line.strip)
Answer: B Rationale: Iterating a file yields lines including newline characters; rstrip('\n') removes only the newline, preventing double-spacing. Option A prints an extra blank line; C prints a list, not lines; D prints the method object, not the result.
43 Which statement about try/except/else/finally is correct when an exception is raised inside the try block and handled by except?
A) The else block executes before except. B) The finally block executes only if no exception occurs. C) The else block is skipped and finally still executes. D) The finally block is skipped when an exception is handled.
A) e = d.copy() B) e = d C) e = d | {} D) Both A and C
Answer: D Rationale: d.copy() and d | {} both produce a new dict with the same top-level key-value bindings, independent of d. Plain assignment e = d aliases the same object. Since both A and C are valid, D is correct.
47 Which snippet correctly writes JSON to out.json such that non-ASCII characters are preserved as readable Unicode rather than escaped?
A) json.dump(data, open('out.json','w')) B) json.dump(data, open('out.json','w'), ensure_ascii=False) C) json.dumps(data, ensure_ascii=True) D) json.dump(data, open('out.json','wb'), ensure_ascii=False)
Answer: B Rationale: ensure_ascii=False preserves non-ASCII characters as Unicode in the output; opening in text mode is correct for json.dump. Option A defaults to ensure_ascii=True (escapes), C returns a string and does not write, and D opens in binary mode, which json.dump does not accept.
48 A test asserts add(2,3) == 5. Which unittest method correctly checks that calling add('2','3') raises a TypeError?
A) self.assertRaises(TypeError, add, '2', '3') B) self.assertRaises(TypeError, add('2','3')) C) self.assertRaises(TypeError, lambda: add('2','3')) D) Both A and C
Answer: D Rationale: assertRaises can take a callable plus args, or a context/manager with a callable. Option B evaluates the call immediately and would raise before assertRaises can catch it. Both A and C are valid forms.
49 Given s = 'racecar', which expression returns True if and only if s is a palindrome (case-sensitive, ignoring non-alphanumeric characters)?
A) s == s[::-1] B) s == ''.join(c for c in s if c.isalnum())[::-1] C) s.lower() == s[::-1].lower() D) s == ''.join(reversed(s))
Answer: B Rationale: B filters to alphanumeric characters, then compares the filtered string to its reverse, satisfying the full requirement. A and D ignore filtering; C ignores non-alphanumeric filtering and is case-insensitive, which changes semantics.
50 What is the output of the following code?
def f(x, lst=[]): lst.append(x) return lst
print(f(1)) print(f(2)) print(f(3, []))
A) [1] [2] [3]
B) [1] [1, 2] [3]
C) [1] [2] [3, 3]
D) [1] [1, 2] [1, 2, 3]
Answer: B Rationale: Default mutable arguments are evaluated once at function definition, so the same list persists across calls. f(1) appends 1 to the default list, returning [1]. f(2) appends 2 to the same list, yielding [1,2]. f(3, []) passes a new empty list, so it returns [3].
51 Which of the following expressions evaluates to True?
A) [] == False B) [] is False C) bool([]) == False D) [] in [False]
Answer: C