Docsity

WGU E010 Foundations of Programming (Python) Objective Newest., Exams of Nursing

Partial preview of the text

Download WGU E010 Foundations of Programming (Python) Objective Newest. and more Exams Nursing in PDF only on Docsity!

WGU E010 Foundations of Programming (Python) Objective

Assessment V AND VERIFIED ANSWERS WITH

RATIONALES JUST RELEASED.pdf - 99 Questions with

Answers

Newes

Q1. What is the output of the following code?

x = [1, 2, 3] y = x y.append(4) print(x)

A. [1, 2, 3] B. [1, 2, 3, 4] C. [1, 2, 3, 4, 4] D. Error: x is immutable

Correct Answer: B. [1, 2, 3, 4]

Rationale: In Python, assigning y = x makes y reference the same list object as x. The append method mutates the list in place, so x reflects the change. Thus, x becomes [1, 2, 3, 4].

Why Wrong: A - This would be true only if y were a copy of x, but no copy was made. C - Only one append was performed, so 4 appears once, not twice. D - Lists are mutable; no error occurs.

Reference: Python Documentation: Data Structures (Lists)

Q2. Which of the following best describes the primary purpose of the __init__ method in a Python class?

A. It initializes the class itself when the module is imported. B. It is automatically called when a new instance of the class is created, to initialize the instance's attributes. C. It defines the string representation of an instance for printing. D. It is used to destroy an instance when it is no longer needed.

Correct Answer: B. It is automatically called when a new instance of the class is created, to initialize the instance's attributes.

Rationale: __init__ is the initializer method that runs automatically when an object is instantiated. It sets up instance attributes. The other options describe __new__, __str__, and __del__ respectively.

Why Wrong: A - Module-level initialization is handled by code outside the class, not __init__. C - __str__ returns a string representation; __init__ does not. D - __del__ is the destructor, not __init__.

Reference: Python Official Documentation: Classes

Q5. What is the output of the following code?

def func(a, b=[]): b.append(a) return b

print(func(1)) print(func(2))

A. [1] [2] B. [1] [1, 2] C. [1, 2] [1, 2] D. [1] [2, 1]

Correct Answer: B. [1] [1, 2]

Rationale: Default arguments are evaluated once at function definition. The same list object is used across calls. First call appends 1, second call appends 2 to the same list, resulting in [1, 2].

Why Wrong: A - This would be true if a new list were created each call, but it is not. C - The first call only appends 1, so it prints [1], not [1, 2]. D - The order of appends is 1 then 2, so [2, 1] is incorrect.

Reference: Python Common Pitfalls: Mutable Default Arguments

Q6. Which statement about Python's exception handling is correct?

A. The finally block executes only if no exception occurs. B. The else block executes if no exception occurs in the try block. C. A try block must be followed by at least one except block. D. Exceptions can only be caught if they are subclasses of Exception.

Correct Answer: B. The else block executes if no exception occurs in the try block.

Rationale: The else clause runs if the try block completes without raising an exception. finally always runs. A try can have finally without except. BaseException subclasses like SystemExit can be caught if specified.

Why Wrong: A - finally always executes, regardless of exceptions. C - A try can be followed by finally only, without except.

D - Exceptions like KeyboardInterrupt are not subclasses of Exception but can be caught.

Reference: Python Errors and Exceptions: Handling Exceptions

Q7. What is the result of the following expression?

bool("False")

A. True B. False C. Error D. None

Correct Answer: A. True

Rationale: In Python, non-empty strings are truthy. The string "False" is non-empty, so bool("False") returns True. The content of the string does not affect its truthiness.

Why Wrong: B - This would be the case if the string were empty. C - No error occurs; bool() accepts any object. D - bool() always returns True or False, never None.

Reference: Python Truth Value Testing

Q8. Which of the following code snippets correctly reads a file and ensures it is properly closed even if an error 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

Correct Answer: D. Both B and C

Rationale: Both the with statement (context manager) and the try/finally construct guarantee the file is closed. Option A does not handle exceptions, so the file may remain open if an error occurs.

Why Wrong: A - If an exception occurs during read, close() is not called.

A. [1], [2], [3] - the default is re-evaluated per call B. [1], [1, 2], [1, 2, 3] - the default list is created once at definition time and shared C. [1], [2], [3] - Python copies mutable defaults D. [1], [1, 2], [1, 2, 3] - acc is a global variable

Correct Answer: B. [1], [1, 2], [1, 2, 3] - the default list is created once at definition time and shared

Rationale: Default argument expressions are evaluated once when the def statement executes, so the same list object persists across calls and accumulates values. This is the classic mutable-default pitfall; the fix is acc=None with in-body initialization.

Why Wrong: A - Defaults are not re-evaluated on each call; they bind at function definition time. C - Python does not copy mutable default arguments; it reuses the same object. D - acc is a local parameter bound to a shared default object, not a global.

Reference: Python Language Reference, 8.6 Function definitions; Lutz, Learning Python, 6th Ed., Ch. 18

Q12. Which expression evaluates True for string s = "racecar" while correctly rejecting s = "ab"?

A. s == s[::1] B. s == s[::-1] C. s.find(s[::-1]) == 0 D. s.sort() == s[::-1]

Correct Answer: B. s == s[::-1]

Rationale: s[::-1] reverses the string via extended slicing, so equality tests palindromicity. s[::1] is the original string, find returns an index (and -1 when absent), and strings have no sort method.

Why Wrong: A - s[::1] is an identity slice, not a reversal, so any string would pass. C - find returns an integer index, not a boolean, and is 0 for any matching prefix. D - Strings are immutable and lack a sort method; this raises AttributeError.

Reference: Python Docs, Sequence Types - Common Sequence Operations; slicing

Q13. What is printed by print(sum([i*i for i in range(5) if i % 2]))?

A. 10 B. 20 C. 30 D. 0

Correct Answer: A. 10

Rationale: Odd i values in range(5) are 1 and 3; squares are 1 and 9, summing to 10. The comprehension filters evens before squaring.

Why Wrong: B - 20 would require including i=4 (16) or miscomputing squares. C - 30 corresponds to summing squares of 1..4 (1+4+9+16), ignoring the filter. D - 0 would result only if the filter excluded all values.

Reference: Python Tutorial, 5.1.3 List Comprehensions

Q14. A program must read a large binary file in fixed 64 KB chunks and process each without loading the file into memory. Which construct is most appropriate?

A. for line in open(path, 'r'): B. with open(path, 'rb') as f: while chunk := f.read(65536): process(chunk) C. data = open(path).readlines() D. for chunk in open(path, 'rb').read().split(b'\n'):

Correct Answer: B. with open(path, 'rb') as f: while chunk := f.read(65536): process(chunk)

Rationale: Binary mode with an explicit read size and the walrus operator streams fixed-size chunks while the with block guarantees closure. This is the idiomatic memory-bounded approach.

Why Wrong: A - Text mode line iteration is inappropriate for binary data and may split on arbitrary newlines. C - readlines() materializes the entire file in memory as a list. D - read() loads the whole file first, defeating the streaming requirement.

Reference: Python Docs, io - Binary I/O; PEP 572 Assignment Expressions

Q15. Given class A: pass and class B(A): pass, which statement about isinstance and issubclass is correct?

A. isinstance(B(), A) is False because B is not A B. issubclass(B, A) is True and isinstance(B(), A) is True C. issubclass(A, B) is True by inheritance symmetry D. isinstance(B(), A) is True only if B overrides init

Correct Answer: B. issubclass(B, A) is True and isinstance(B(), A) is True

Rationale: Inheritance establishes an is-a relationship: B is a subclass of A and its instances are instances of A. Overriding methods is irrelevant to isinstance.

Why Wrong: A - Subclass instances are instances of the base class, so the result is True. C - Inheritance is directional; A is not a subclass of B.

C. def f(args, kwargs): return g(args, kwargs) D. def f(*args, **kwargs): return g(args=args, kwargs=kwargs)

*Correct Answer: B. def f(args, *kwargs): return g(args, kwargs)

Rationale: Unpacking with *args and **kwargs at the call site forwards the original positional and keyword arguments faithfully.

Why Wrong: A - Passes a tuple and dict as single arguments rather than unpacking them. C - Requires exactly two positional arguments and loses variadic behavior. D - Passes args and kwargs as named keyword arguments, changing the call semantics.

Reference: Python Tutorial, 4.9.2 Keyword Arguments; PEP 448

Q19. Which statement about Python's dict and hashing is correct?

A. Keys must be hashable and immutable in practice; lists cannot be keys B. Any object can be a dict key because Python hashes by identity C. Tuples containing lists are valid dict keys D. Dict keys are stored in insertion order and hashing is unnecessary

Correct Answer: A. Keys must be hashable and immutable in practice; lists cannot be keys

Rationale: Dict keys require a stable hash and equality; mutable objects like lists are unhashable. Tuples are hashable only if all their elements are.

Why Wrong: B - Default hashing exists, but mutable objects are explicitly unhashable. C - A tuple containing a list is unhashable because its elements are. D - Insertion order is preserved since 3.7, but hashing still underpins lookups.

Reference: Python Docs, Data Model - hash and dictionary

Q20. Which comparison of Python's range and a list is most accurate?

A. range is a lazy sequence supporting O(1) membership and slicing B. range stores all integers eagerly like a list C. range supports in-place mutation of its elements D. range is an iterator that is exhausted after one pass

Correct Answer: A. range is a lazy sequence supporting O(1) membership and slicing

Rationale: range is an immutable sequence computing values on demand, so membership and indexing are O(1) and slicing returns a new range. It is re-iterable, not a one-shot iterator.

Why Wrong: B - range is lazy and does not materialize its elements.

C - range is immutable; elements cannot be assigned. D - range is iterable and re-iterable, not an exhausted iterator.

Reference: Python Docs, Built-in Types - range; Sequence Protocol

Q21. A function is defined as def f(x, bag=[]): bag.append(x); return bag. Three calls f(1), f(2), f(3) are made without passing bag. What does the final call return, and why?

A. [3], because a fresh list is created on each call B. [1, 2, 3], because the default list is created once at definition time and shared across calls C. [1, 2, 3], because Python deduplicates identical list literals globally D. [3], because the list is rebound to the argument each call

Correct Answer: B. [1, 2, 3], because the default list is created once at definition time and shared across calls

Rationale: Default argument values are evaluated once when the def statement executes, so the same mutable list object persists and accumulates across calls. The other options incorrectly assume per-call creation or global literal deduplication, neither of which occurs.

Why Wrong: A - A new list is not created per call; the default is bound once at function definition. C - Python does not deduplicate list literals globally; the behavior stems from default-argument evaluation timing. D - The list is not rebound; the same object is mutated via append.

Reference: Lutz, M. ( ). Learning Python, 6th Ed., Ch. 18 (Arguments)

Q22. Which expression evaluates to True given s = 'Python3' and demonstrates correct use of slicing with a negative step?

A. s[::-1] == '3nohtyP' B. s[-1:0:-1] == '3nohtyP' C. s[::-1][0] == 'P' D. s[0:-1:-1] == '3nohtyP'

Correct Answer: A. s[::-1] == '3nohtyP'

Rationale: s[::-1] reverses the entire string, yielding '3nohtyP', so the equality holds. Option B omits the first character because the stop index 0 is exclusive, and option D starts at index 0 with a negative step, producing an empty string.

Why Wrong: B - s[-1:0:-1] stops before index 0, producing '3nohty' without the final 'P'. C - s[::-1][0] is '3', not 'P'. D - s[0:-1:-1] returns an empty string because the start precedes the stop with a

Reference: Python Software Foundation. ( ). Built-in Functions: sorted

Q25. A class defines __init__ to set self._balance. A subclass overrides a method that reads self._balance. Which statement best explains why name mangling does NOT apply to _balance?

A. Single leading underscores trigger mangling only inside classes B. Name mangling applies only to identifiers with two leading underscores and at most one trailing underscore C. Name mangling applies only to module-level names D. Name mangling applies to any identifier containing an underscore

Correct Answer: B. Name mangling applies only to identifiers with two leading underscores and at most one trailing underscore

Rationale: Python mangles identifiers of the form __name (two leading underscores, at most one trailing underscore) by prefixing the class name. A single underscore is merely a convention indicating non-public API and is not mangled, so _balance remains accessible.

Why Wrong: A - A single leading underscore never triggers mangling, inside or outside classes. C - Mangling occurs within class bodies, not at module level. D - Mangling is specific to double-underscore names, not all names with underscores.

Reference: Python Software Foundation. ( ). Python Tutorial: Private Variables

Q26. Which code fragment correctly uses a list comprehension with a conditional to produce only even squares from range(10)?

A. [xx for x in range(10) if x % 2 == 0] B. [xx if x % 2 == 0 for x in range(10)] C. [for x in range(10) if x % 2 == 0: xx] D. [xx for x in range(10) if x % 2]

Correct Answer: A. [xx for x in range(10) if x % 2 == 0]*

Rationale: The filter clause if x % 2 == 0 follows the iteration clause and includes only even x, whose squares are computed. Option B misplaces the if before the for, option C uses invalid syntax, and option D filters odd numbers.

Why Wrong: B - The conditional must follow the for clause; placing it before is a syntax error in a comprehension. C - List comprehensions do not use a colon or a leading for in that form. D - if x % 2 selects odd values, not even ones.

Reference: Downey, A. ( ). Think Python, 3rd Ed., Ch. 19 (Comprehensions)

Q27. A recursive function computes Fibonacci numbers with return fib(n-1) + fib(n-2). What is the dominant reason its runtime grows exponentially rather than linearly?

A. Python lacks tail-call optimization B. Overlapping subproblems are recomputed because results are not memoized C. The recursion depth exceeds the default limit D. Integer addition becomes slower as n grows

Correct Answer: B. Overlapping subproblems are recomputed because results are not memoized

Rationale: The naive recursion recomputes the same subproblems many times, producing roughly O(2^n) calls. Memoization or dynamic programming collapses this to linear time; the other choices describe real but non-dominant factors.

Why Wrong: A - Lack of tail-call optimization affects stack usage, not the exponential call count. C - Recursion depth is O(n), not the source of exponential time. D - Big-integer addition cost is negligible compared with redundant calls.

Reference: Cormen, T.H. et al. ( ). Introduction to Algorithms, 4th Ed., Ch. 15 (Dynamic Programming)

Q28. Given d = {'a': 1, 'b': 2}, which statement about d.get('c', 0) versus d['c'] is correct?

A. Both raise KeyError for a missing key B. get returns the default 0 without raising, while d['c'] raises KeyError C. get inserts 'c': 0 into the dictionary D. d['c'] returns None for a missing key

Correct Answer: B. get returns the default 0 without raising, while d['c'] raises KeyError

Rationale: dict.get returns the provided default when the key is absent and does not modify the dictionary, whereas subscript access raises KeyError. Options A, C, and D misstate these behaviors.

Why Wrong: A - Only d['c'] raises KeyError; get returns the default. C - get does not insert the key; the dictionary is unchanged. D - Subscript access raises KeyError rather than returning None.

Reference: Python Software Foundation. ( ). Mapping Types - dict

Q29. A test asserts round(2.675, 2) == 2.68 but the assertion fails. Which explanation is most accurate?

B. [2, 4]

C. [0, 1, 2, 3, 4]

D. [1, 3]

Correct Answer: A. [0, 2, 4]

Rationale: The list comprehension iterates x from 0 to 4 and includes only those where x % 2 == 0, yielding 0, 2, and 4. The condition filters out odd numbers, and range(5) includes 0 but excludes 5.

Why Wrong: B - Omits 0, which satisfies x % 2 == 0. C - Includes all numbers without applying the filter. D - Selects odd numbers instead of even ones.

Reference: Python Documentation: List Comprehensions, https://docs.python.org/3/tutorial/datastructures.html

**Q32. What is the output of the following code?

def f(a, b=[]): b.append(a) return b print(f(1)) print(f(2)) ```** A. [1] then [2] B. [1] then [1, 2] C. [1, 2] then [1, 2] D. [1] then [1] **Correct Answer: B. [1] then [1, 2]** **_Rationale:_** _Default mutable arguments are evaluated once at function definition, so the same list object persists across calls. The first call appends 1, the second appends 2 to the same list, resulting in [1] then [1, 2]._ **_Why Wrong:_** A - Assumes a new list is created each call, which is false for mutable defaults. C - Incorrectly assumes both calls share the same list from the start. D - Ignores the persistence of the default list across calls. **_Reference:_** _Python Documentation: Default Argument Values, https://docs.python.org/3/tutorial/controlflow.html#default-argument-values_ **Q33. Which statement about Python's `range()` function is correct?** A. `range(5)` returns a list of integers from 0 to 5. B. `range(1, 5, 2)` produces 1 and 3. C. `range(5, 1, -1)` produces 5, 4, 3, 2, 1. D. `range(0, 5, 2)` produces 0, 2, 4, 5. **Correct Answer: B. `range(1, 5, 2)` produces 1 and 3.** **_Rationale:_** _range(1, 5, 2) starts at 1, stops before 5, and steps by 2, yielding 1 and 3. range does not include the stop value, and negative steps count down but exclude the stop._ **_Why Wrong:_** A - range(5) is an iterable, not a list, and excludes 5. C - range(5, 1, -1) stops before 1, yielding 5,4,3,2. D - range(0, 5, 2) yields 0,2,4, not 5. **_Reference:_** _Python Documentation: range(), https://docs.python.org/3/library/stdtypes.html#range_ **Q34. What is the result of `3 * 'ab' + 'c'`?** A. 'abababc' B. 'abababc' C. 'abababc' D. 'abababc' **Correct Answer: A. 'abababc'** **_Rationale:_** _String repetition `3 * 'ab'` yields 'ababab', and concatenation with 'c' gives 'abababc'. All options are identical due to a typo; the intended correct answer is 'abababc'._ **_Why Wrong:_** B - Same as correct but listed as distractor due to formatting error. C - Same as correct but listed as distractor due to formatting error. D - Same as correct but listed as distractor due to formatting error. **_Reference:_** _Python Documentation: String Operations, https://docs.python.org/3/library/stdtypes.html#string-methods_ **Q35. Which of the following best describes the difference between a list and a tuple in Python?** A. Lists are immutable; tuples are mutable. B. Tuples can contain only numbers; lists can contain any type. C. Lists are mutable; tuples are immutable. D. Tuples are defined with square brackets; lists with parentheses. **Correct Answer: C. Lists are mutable; tuples are immutable.** **_Rationale:_** _Lists are mutable sequences, allowing item assignment, while tuples are immutable and cannot be changed after creation. This mutability difference is the primary_ **_Rationale:_** ___init__ is the initializer method invoked automatically after an instance is created, to set up initial state. It should not return a value other than None._ **_Why Wrong:_** B - __init__ should return None, not the object. C - Object destruction is handled by __del__, not __init__. D - While optional, omitting it may leave objects without necessary initialization. **_Reference:_** _Python Documentation: Classes, https://docs.python.org/3/tutorial/classes.html_ **Q38. What is the value of `expression` after: `expression = 5 if 3 > 2 else 10`?** A. 5 B. 10 C. True D. None **Correct Answer: A. 5** **_Rationale:_** _The conditional expression evaluates the condition 3 > 2, which is True, so it returns the first value, 5. Otherwise it would return 10._ **_Why Wrong:_** B - 10 is returned only if the condition is False. C - The expression returns a value, not a boolean. D - None is not produced by this expression. **_Reference:_** _Python Documentation: Conditional Expressions, https://docs.python.org/3/reference/expressions.html#conditional-expressions_ **Q39. Which method is used to add an item to the end of a list?** A. append() B. insert() C. extend() D. add() **Correct Answer: A. append()** **_Rationale:_** _append() adds a single element to the end of a list. insert() adds at a specific index, extend() adds multiple elements, and add() is for sets._ **_Why Wrong:_** B - insert() requires an index and adds at that position. C - extend() appends multiple elements from an iterable. D - add() is a set method, not a list method. **_Reference:_** _Python Documentation: More on Lists, https://docs.python.org/3/tutorial/datastructures.html#more-on-lists_ **Q40. What is the output of `print(type(3.0))`?** A. B. C. D. **Correct Answer: B. ** **_Rationale:_** _In Python, 3.0 is a floating-point number, so type() returns . Python does not have a separate double type; float is double-precision._ **_Why Wrong:_** A - int is for integers like 3, not 3.0. C - Python does not have a 'double' type; float covers that. D - There is no 'number' type in Python's built-in types. **_Reference:_** _Python Documentation: Built-in Types, https://docs.python.org/3/library/stdtyp es.html#numeric-types-int-float-complex_ **Q41. Consider `nums = [10, 20, 30, 40, 50]`. What does `nums[1:4][::-1]` evaluate to?** A. [40, 30, 20] B. [20, 30, 40] C. [50, 40, 30] D. [30, 20, 10] **Correct Answer: A. [40, 30, 20]** **_Rationale:_** _The slice `nums[1:4]` yields `[20, 30, 40]`; applying `[::-1]` reverses that intermediate list to `[40, 30, 20]`. Slices create new lists, so the reversal operates only on the extracted sublist, not the original._ **_Why Wrong:_** B - This is the un-reversed slice `nums[1:4]`, ignoring the `[::-1]` step. C - This reflects reversing the whole list (`nums[::-1][:3]`), not the sub-slice. D - This reverses `nums[0:3]` rather than the slice `nums[1:4]`. **_Reference:_** _Downey, A. ( ). Think Python, 3rd Ed., Ch. 10 (Lists) - slice semantics._ **Q42. A function is defined as `def f(a, b=2, *args, **kwargs):`. Which call raises a `TypeError` at definition or call time?** A. f(1, 3, 4, 5, x=6) B. f(1, b=3, x=6) C. f(a=1, 3) D. f(1, 3, x=6, y=7) **Correct Answer: C. f(a=1, 3)**