Docsity

WGU E010 FOUNDATIONS OF PROGRAMMING (PYTHON) PRACTICE EXAM: COMPLETE OA QUESTIONS WITH VER, Exams of Programming Methodologies

Partial preview of the text

Download WGU E010 FOUNDATIONS OF PROGRAMMING (PYTHON) PRACTICE EXAM: COMPLETE OA QUESTIONS WITH VER and more Exams Programming Methodologies in PDF only on Docsity!

WGU E010 FOUNDATIONS OF PROGRAMMING (PYTHON) PRACTICE ASSESSMENT FREQUENTLY TESTED QUESTIONS WITH CORRECT ANSWERS BRAND NEW! 129 Questions with Answers and Detailed Rationales 100 PERCE RANTEED PASS INSTANT DOWNLOAD ANSWERS INCLUDED IMPORTANCE OF THIS DOCUMENT This comprehensive examination preparation guide has been meticulously developed to help you succeed in the WGU E010 FOUNDATIONS OF PROGRAMMING (PYTHON) PRACTICE ASSESSMENT FREQUENTLY TESTED QUESTIONS WITH CORRECT ANSWERS BRAND NEW! It contains 129 carefully selected questions that reflect the most current exam content and testing strategies. Each question is accompanied by a correct answer and a detailed rationale that explains the underlying pathophysiology, pharmacology, or clinical reasoning. Self-Assessment — Test your knowledge and Exam Preparation — Familiarize yourself with the identify areas requiring further question format and content study areas Concept Reinforcement — Deepen your Confidence Building — Develop test-taking understanding through strategies and reduce evidence-based exam anxiety rationales Time Management — Practice answering questions under simulated exam conditions Review Summary 129 Questions Foundations - Application - WGU E010 Foundations OF Programming Python Assessment Frequently Tested WITH Correct Brand NEW Computer Science / Python Programming Undergraduate YEAR 2 All answers with rationales Table of Contents Content Area Questions Key Topics WGU E010 Foundations OF 1-22 Print, Python, Output, Return, Append Programming Python Assessment Frequently Tested WITH Correct Brand NEW Computer Science / Python Programming Undergraduate YEAR 2 Print 23-44 Return, Python, Function, Output, Numbers Return 45-66 Python, Print, Result, Output, Class Output 67-88 Python, Print, Return, Class, Yield Class 89-110 Python, Return, Print, Output, Consider Consider 111-129 Output, Print, Python, Result, Function TOTAL 129 All questions include answers and detailed rationales Section A - WGU E010 Foundations OF Programming Python Assessment Frequently Tested WITH Correct Brand NEW Computer Science / Python Programming Undergraduate YEAR 2 A. [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 5] B. [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4, 5) C.[1, 2,3, 5}[1, 2,3, 4] [1, 2,3, 4, 5] D.[1, 2, 3] [1, 2, 3, 4] [1, 2, 3, 5] Correct: A - [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 5] Rationale:y = x makes y refer to the same list as x, so appending to y also modifies x. z = x.copy() creates a shallow copy, so appending to z does not affect x. Thus x and y become [1,2,3,4] and z becomes [1,2,3,5]. Q3. What is the result of the expression? ™ python [1, 2, 3] * 2 + [4] A.[1, 2, 3, 1, 2, 3, 4] B. [2, 4, 6, 4] C. [1, 2, 3, 2, 4] D. TypeError Correct: A - [1, 2, 3, 1, 2, 3, 4] Rationale:In Python, list multiplication repeats the list, and list concatenation joins them. [1,2,3]*2 yields [1,2,3,1,2,3], then +[4] appends 4, resulting in [1,2,3,1,2,3,4]. Q4. What is the output of the following code? “python def foo(x, y=[]): y-append(x) return y print(foo(1)) print(foo(2, [])) print(foo(3)) A. [1], [2], [1, 3] B. [1], [2], [1, 3] C. [1], [2], (1, 3] D. [1], [2], [1, 3] Correct: A - [1], [2], [1, 3] Section A - WGU E010 Foundations OF Programming Python Assessment Frequently Tested WITH Correct Brand NEW Computer Science / Python Programming Undergraduate YEAR 2 Rationale: This is a classic Python gotcha, The default argument y=] is evaluated once at function definition. Thus, the first call modifies the default list to [1], the second call uses a new list so returns [2], and the third call again uses the mutated default list which now contains [1], so retums [1, 3]. Options B, C, and D are duplicates of the correct answer, but the correct one is A. Qs. Which of the following expressions evaluates to True? A. not (1 == 1 and 2 != 3) B. 1 is 1 and ‘a’ is ‘a’ C. 3 in [1, 2] or 4 in [1, 2, 3] D. not (1 < 2) or (3 > 4) Correct: B - 1 is 1 and ‘a’ is ‘a’ Rationale:Option B: In CPython, small integers and interned strings are cached, so 1 is 1 and ‘a’ is 'a' both evaluate to True, and the expression is True. Option A: 1==1 and 2!=3 is True, so not True is False. Option C: 3 is not in [1,2] and 4 is not in [1,2,3], so False or False is False. Option D: not (1<2) is False, and 3>4 is False, so False or False is False. Qé. What is the output of the following code? ™ python def f(x, y=[]): y-append(x) return y print(f(1)) print(f(2, [])) print(f(3)) A. [1], [2], [1, 3] B. [1], [2], [1, 3] C. [1], (21, [1, 3) D. {1}, (2), (1, 3] Correct: A - [1], [2], [1, 3] Rationale:This is the same classic mutable default argument issue. The default list is created once and persists across calls that don't provide a new list. Hence, the first call gives [1], the second with a new list gives [2], and the third uses the default which now contains 1 and then appends 3, resulting in [1,3]. Section A - WGU E010 Foundations OF Programming Python Assessment Frequently Tested WITH Correct Brand NEW Computer Science / Python Programming Undergraduate YEAR 2 b.append(a) return b print(f(t)) print(f(2, 1) print(f(3)) A. [1], [2], [1, 3] B. [1], [2], [1, 3] C. [1], (2, 11, 3] D. [1], (21, [1, 3] Correct: A - [1], [2], [1, 3] Rationale:The default mutable argument is evaluated once at function definition. Therefore, the default list persists across calls that omit the second argument. The first call modifies it to [1], the second call uses a new list and returns [2], and the third call modifies the default list again to [1,3]. Q10. What is the output of the following code? “python for i in range(3): for j in range(2): print(i, j) A.00,01,10,11,20,21 B.00,01,10,11,20,21 C.00,01,10,11,20,21 D.00,01,10,11,20,21 Correct: A-00,01,10,11,20,21 Rationale:The nested loops iterate i from 0 to 2 and j from 0 to 1 for each i, producing the pairs (0,0), (0,1), (1,0), (1,1), (2,0), (2,1). Q11. In a Python program, a mutable default argument is used to accumulate results across calls. Which design pattern correctly avoids the associated aliasing bug while preserving intended behavior? A. Use a list literal as the default and copy it B. Use None as the default and create a at the start of each call new list inside the function if None C. Use a tuple as the default and convert to D. Use a global list and clear it at the end of list inside the function each call Section A - WGU E010 Foundations OF Programming Python Assessment Frequently Tested WITH Correct Brand NEW Computer Science / Python Programming Undergraduate YEAR 2 ‘orrect: B = Use None as the default and create a new list inside the function if None Rationale:The classic Python pitfall is that mutable default arguments are evaluated once at function definition, causing all calls to share the same object. Using None as a sentinel and creating a fresh list inside the function when the argument is None is the canonical fix. Options A and D still share mutable state across calls, and C, while using an immutable tuple, fails if the function needs to mutate the list. Q12. Given the code: class Meta(type): def _new__(cls, name, bases, dct): det['x'] = 42 return super().__new__(cls, name, bases, dct) class MyClass(metaclass=Meta): pass print(MyClass.x) What is printed? A. AttributeError: type object 'MyClass' has no attribute 'x' C. None D. A TypeError because metaclass __ new__ cannot modify dct Correct: B - 42 Rationale:The metaclass __new__ method receives the class namespace as a dictionary (dct). By adding 'x': 42 to det before calling super().__ new__, the attribute is present in the resulting class. Hence MyClass.x evaluates to 42. The other options misrepresent Python's metaclass mechanics. Q13. Consider the following code snippet intended to filter even numbers from a list: nums = [1, 2, 3, 4, 5, 6] evens = list(filter(lambda x: x % 2 == 0, nums)) Which of the following is TRUE about the variable 'evens'? A. evens is a generator object that must be B. evens is a list containing [2, 4, 6] iterated to obtain the list Section A - WGU E010 Foundations OF Programming Python Assessment Frequently Tested WITH Correct Brand NEW Computer Science / Python Programming Undergraduate YEAR 2 Qi16. Which of the following correctly describes the behavior of a Python decorator applied to a function? A. It changes the function's bytecode at B. It is a function that takes another function runtime to improve performance as an argument and returns a new function that typically extends the behavior of the original C. It automatically adds type checking to the D. It converts the function into a class function arguments method that can be called without an instance Correct: B - It is a function that takes another function as an argument and returns a new function that typically extends the behavior of the original Rationale:A decorator is a callable that takes a function (or class) and returns a callable, usually wrapping the original to add functionality. It does not modify bytecode, add type checking, or convert to a class method by default. The @ syntax is syntactic sugar for applying the decorator. Q17. Consider the following code: def outer(): x=10 def inner(): nonlocal x xt=5 return x return inner f = outer() print(f()) print(f()) What is the output? A. 10 10 B. 15 20 C.15 15 D. An UnboundLocalError because x cannot be modified in inner Correct: B - 15 20 Section A - WGU E010 Foundations OF Programming Python Assessment Frequently Tested WITH Correct Brand NEW Computer Science / Python Programming Undergraduate YEAR 2 Rationale: The nonlocal declaration in inner() binds x to the variable in the enclosing scope (outer). Each call to f() increments x by 5 and returns its value. The first call returns 15, the second call returns 20, demonstrating that the closure retains state across calls. Q18. Which of the following statements about Python's Global Interpreter Lock (GIL) is TRUE? A. The GIL prevents multiple threads from B. The GIL is automatically released when a executing Python bytecode simultaneously — thread performs CPU-bound operations, in a single process allowing true parallelism C. The GIL makes Python thread-safe for all D. The GIL is only present in Python 2 and data structures without additional locks was removed in Python 3 Correct: A - The GIL prevents multiple threads from executing Python bytecode simultaneously in a single process Rationale:The GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecode at once. This limits CPU-bound multithreading performance. The GIL is not automatically released for CPU-bound tasks (only for I/O or certain C extensions), does not make all data structures thread-safe, and exists in Python 3. Q19. Which of the following correctly describes the difference between __str__ and __repr__in Python? A. __str__ is used for unambiguous B.__str__ is called by str() and print(), while representation, while __repr__ is for __repr__ is called by repr() and in readable output interactive sessions C. __repr__ must return a string that is valid D.__str__ is inherited from object, while Python code, while __str__ can return any __repr__ must be defined by the user string Correct: B -__str__ is called by str() and print(), while __repr__ is called by repr() and in interactive sessions Rationale:_ str___is intended for human-readable output and is used by str() and print(). __repr__ is intended for unambiguous representation (often for debugging) and is used by repr() and in interactive sessions. The fallback for__str__is__repr__, and__repr__ does not necessarily have to return valid Python code, though it is recommended. Q20. Which of the following best explains why Python uses dynamic typing and duck typing? Section A - WGU E010 Foundations OF Programming Python Assessment Frequently Tested WITH Correct Brand NEW Computer Science / Python Programming Undergraduate YEAR 2 A. Use a deterministic Miller-Rabin test with B. Use trial division up to the square root, a fixed set of bases, because itis always because it is simple and efficient for correct for all integers. arbitrarily large integers. C. Use the sympy.isprime function, which D. Use the Fermat primality test with base 2, employs a combination of trial division and because it is deterministic and never probabilistic tests, offering a good trade-off misclassifies Carmichael numbers. between speed and certainty for large numbers. Correct: C - Use the sympy.isprime function, which employs a combination of trial division and probabilistic tests, offering a good trade-off between speed and certainty for large numbers. Rationale:For large integers, trial division is computationally infeasible. The Fermat test fails for Carmichael numbers. Deterministic Miller-Rabin is only deterministic for numbers below certain thresholds; for arbitrary large numbers, it remains probabilistic unless extended bases are used. sympy.isprime uses a combination of trial division and probabilistic tests (like Miller-Rabin) that is highly reliable and efficient in practice. Section B - Print Q23. Given the following code: def func(a, b=[]): b.append(a) return b print(func(1)) print(func(2)) What is the output and what Python behavior does it illustrate? A. [1] then [2]; each call creates a new list B. [1] then [1, 2]; default arguments are because the default is evaluated at call time. evaluated once at function definition and shared across calls. C. [1] then [1, 2]; because the list is mutable D. Error: default argument cannot be a and passed by reference. mutable object. Correct: B - [1] then [1, 2]; default arguments are evaluated once at function definition and shared across calls. Rationale:In Python, default argument expressions are evaluated once when the function is defined, not each time the function is called. Thus, the list b is created once and reused across Calls, leading to accumulation. This is a classic pitfall; using None and creating a new list inside the function avoids this issue. Q24. Which of the following correctly describes the behavior of the ‘with’ statement in Python when used with a custom context manager that implements “__enter_ and ‘__exit_°? A. The *__exit__~ method is always called, B. The *__exit__* method is only called if no even if an exception occurs, but if it returns exception occurred, to avoid masking errors. True, the exception is suppressed. C. The *__enter__* method must return a D. The ‘with’ statement can only be used value, otherwise the ‘as’ clause is ignored. with built-in context managers like file objects. Correct: A - The “__exit__‘ method is always called, even if an exception occurs, but if it returns True, the exception is suppressed. Section B - Print Rationale: If the list is empty, “len(numbers)' is 0, causing a ZeroDivisionError. If the list contains strings or non-numeric values, the addition or division will raise TypeError. The function does not validate input, so all these issues are potential. A robust implementation should handle empty lists and type validation. Q27. Which of the following statements about Python's Global Interpreter Lock (GIL) is correct? A. The GIL prevents multiple threads from B. The GIL ensures that Python threads are executing Python bytecode simultaneously, truly parallel on multi-core systems. but allows multiple threads to run C extensions concurrently. C. The GIL is a mutex that protects all D. The GIL is present only in CPython, but Python objects, preventing race conditions not in other Python implementations like in multi-threaded programs. Jython or IronPython. Correct: D - The GIL is present only in CPython, but not in other Python implementations like Jython or IronPython. Rationale:The GIL is a mutex in CPython that serializes execution of Python bytecode, preventing multiple native threads from executing Python code simultaneously. However, C extensions can release the GIL to run concurrently. The GIL does not prevent race conditions; programmers must still use synchronization. Other implementations like Jython and IronPython do not have a GIL because they run on the JVM or .NET CLR. Q28. What is the output of the following code? x = [1, 2, 3] y=x x.append(4) z= x.copy() x[0] = 99 print(y, z) A. [99, 2, 3, 4] [1, 2, 3, 4] B. [99, 2, 3, 4] [99, 2, 3, 4] C. [1, 2, 3, 4] [1, 2, 3, 4] D. [99, 2, 3, 4] [1, 2, 3] Correct: A - [99, 2, 3, 4] [1, 2, 3, 4] Rationale:y is a reference to the same list as x, so changes to x are reflected in y. zis a shallow copy, so it gets the appended 4 but not the later change to x[0] because integers are immutable and the copy creates a new list with references to the same integers. Thus y is [99,2,3,4] and z is [1,2,3,4]. Section B - Print Q29. Which of the following is the most appropriate way to handle an exception that occurs inside a generator when using ‘yield’? A. Wrap the generator in a try/except block B. Use ‘throw() method on the generator to when iterating over it. raise an exception at the yield point. C. The generator cannot propagate D. Use ‘return’ inside the generator to raise exceptions; they are always swallowed. a Stoplteration exception. Correct: B - Use ‘throw()’ method on the generator to raise an exception at the yield point. Rationale:Generators can handle exceptions using the ‘throw() method, which raises an exception at the point where the generator is paused. This allows the generator to catch and handle exceptions internally. Alternatively, exceptions raised during iteration can be caught by the caller, but “throw()° is the mechanism for injecting exceptions. ‘return’ in a generator raises Stoplteration, not arbitrary exceptions. Q30. Given the following code, what is the result of the expression ‘list(map(lambda x: x[0], filter(lambda x: x[1] > 2, [(1,2), (3,4), (5,1)])))°? A. [3] B. [1, 3, 5] C. [3, 5] D. [1] Correct: A - [3] Rationale:The filter function keeps tuples where the second element is greater than 2. Only (3,4) satisfies this because 4 > 2. The map function extracts the first element of each remaining tuple, resulting in [3]. The other tuples are filtered out. Q31. A developer writes a function that mutates a list passed as an argument and returns None. In a code review, a colleague insists this violates Python's ‘zen’. Which principle is most directly contradicted, and what is the recommended refactor? A. Explicit is better than implicit; return a B. Flat is better than nested; avoid functions new list instead of mutating. that mutate arguments. C. Special cases aren't special enough to D. Errors should never pass silently; raise break the rules; use a class method. an exception if the list is empty. Correct: A - Explicit is better than implicit; return a new list instead of mutating. Section B - Print A. It is a keyword that refers to the current B. It is an arbitrary name for the first instance. positional argument, conventionally ‘self’. C. It is automatically injected by the D. It holds the class's attributes, not the decorator @classmethod. instance's. Correct: B - It is an arbitrary name for the first positional argument, conventionally ‘self’. Rationale:Python passes the instance as the first argument to instance methods; the name ‘self is a strong convention, not a keyword. Class methods use ‘cls’. Q36. Which of the following code snippets correctly defines a class variable that is shared across all instances? A. class A: def __ init__(self): self.x = 1 B. class A: x = 1 C. class A: def __init__(self): A.x = 1 D. class A: @property def x(self): return 1 Correct: B - class A: x =1 Rationale:Assigning inside the class body creates a class attribute, shared by all instances. self.x creates instance attributes; A.x inside __init__ modifies the class, but it's not the definition. Q37. Which of the following is the correct way to open a file for both reading and writing without truncating it? A. open(‘file.txt’, 'rw') B. open(‘file.txt’, 'w+') C. open(‘file.txt’, ‘r+') D. open(‘file.txt’, 'at') Correct: C - open(‘file.txt’, ‘'r+') Rationale:Mode 'r+' opens for reading and writing, and the file must exist; it does not truncate. 'wt' truncates, 'a+' appends, and 'rw' is invalid. Q38. Which of the following statements about Python's exception hierarchy is true? A. Keyboardinterrupt inherits from B. SystemExit inherits from BaseException. Exception. C. ArithmeticError is a subclass of D. LookupError is a subclass of IndexError. RuntimeError. Correct: B - SystemExit inherits from BaseException. Section B - Print Rationale: SystemExit and Keyboardinterrupt inherit from BaseException, not Exception, to avoid being caught by except Exception. ArithmeticError is a subclass of Exception, and IndexError is a subclass of LookupError. Q39. What is the output of the following code? A. [1, 2, 3, 4] B. [[1, 2], [3, 4]] C.11, 2,3, 4, 5] D. [[1, 21, [3, 41, [51] Correct: D - [[4, 2], [3, 4], [51] Rationale:The list comprehension groups elements into sublists of size 2, using range(1,6) to get 1..5. The last group has one element because the slice [4:6] yields [5]. Q40. A Python module defines a function that uses a global variable and also declares a local variable with the same name. Inside the function, the global variable is accessed before the local assignment. What is the result? A. The global variable's value is used, then B. An UnboundLocalError is raised because the local variable shadows it after the local assignment makes the name local assignment. throughout the function. C. The local variable is automatically treated D. The code runs without error, but the as global due to the name collision. global variable is overwritten by the local assignment. Correct: B - An UnboundLocalError is raised because the local assignment makes the name local throughout the function. Rationale:In Python, if a variable is assigned anywhere in a function, it is considered local to that entire function unless declared global. Accessing it before assignment raises UnboundLocalError, not using the global's value. Option A incorrectly describes a behavior that would require a global declaration or a different scoping rule. Q41. Which of the following best describes the time complexity of accessing an element ina Python set versus a list, and why? A. Both are O(1) on average because B. List access is O(1) via indexing, while set Python optimizes list indexing and set membership is O(1) on average due to membership using hashing. hashing, but the constant factors differ significantly.