









































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!










































WGU E010 Foundations of Programming (Python) OA 2026-2027 QUESTIONS AND ANSWERS ALREADY GRADED A+. 100% Verified Solutions | Updated Per Latest Guidelines | Graded A+ This comprehensive exam preparation document is meticulously designed for students enrolled in the WGU E010 Foundations of Programming (Python) course. It contains 100 verified objective assessment questions that mirror the actual exam's format and difficulty. Each question is accompanied by a correct answer and a detailed rationale, ensuring a deep understanding of core programming concepts. This study guide is an essential resource for achieving a high score on the 2026/2027 OA.
Key Features: Python syntax and semantics Control flow and loops Data structures and collections Functions and modular programming File handling and exceptions Object-oriented programming basics
Updates for 2026:
Abstract: This objective assessment testbank for WGU E010 Foundations of Programming (Python) is a meticulously curated collection of 100 practice questions, each with verified answers and detailed rationales. The questions are designed to assess a student's proficiency in fundamental Python programming concepts, including syntax, control structures, data types, functions, and error handling. The document serves as a comprehensive study aid, enabling students to identify their strengths and weaknesses, and to familiarize themselves with the exam's structure and question types. By engaging with this material, students can enhance their problem-solving skills and build confidence for the actual assessment. The rationales provided for each answer offer insight into the reasoning behind correct responses, promoting a deeper conceptual understanding. This testbank is an invaluable tool for any student aiming to excel in the WGU E010 course and pass the objective assessment with a superior grade.
Keywords: WGU E010, Foundations of Programming, Python, Objective Assessment, Testbank, Practice Questions, Study Guide, 2026/
Answer Format: Each question is followed by the correct answer and a comprehensive rationale explaining why it is correct, as well as why the other options are incorrect. The rationales are detailed to reinforce learning and clarify common misconceptions, ensuring a thorough understanding of the underlying concepts.
Compliance Checklist: 100 verified questions aligned with WGU E010 exam objectives
Detailed rationales for every answer Updated to 2026/2027 curriculum standards Formatted for easy study and review Includes a variety of question types (multiple choice, fill-in-the-blank, etc.) Suitable for self-assessment and exam simulation
Content Area Overview:
Content Area Questions Key Topics Weight Python Fundamentals and Syntax
1-20 variables, data types, operators, input/output, basic syntax
20%
Control Flow and Loops 21-40 if-else, for loops, while loops, break/continue, nested loops
20%
Data Structures and Collections 41-60 lists, tuples, dictionaries, sets, list comprehensions
20%
Functions and Modular Programming
61-75 function definition, parameters, return values, scope, lambda functions
15%
File Handling and Exceptions 76-90 file I/O, reading/writing files, exception handling, try-except
15%
Object-Oriented Programming 91-100 classes, objects, methods, inheritance, encapsulation
10%
Reference: Downey, A. (2015). Think Python, 2nd Ed., O'Reilly Media, Ch. 5.
Q3. What is the output of the following code?
nums = [1, 2, 3, 4, 5] result = [n2 for n in nums if n % 2 == 0] print(result)**
A. [4, 16] B. [1, 9, 25] C. [2, 4] D. [4, 16, 36]
Correct Answer: A. [4, 16]
Rationale: The list comprehension iterates over nums, filters for even numbers (2 and 4), and squares them, yielding [4, 16].
Why Wrong: B - Incorrect because these are squares of odd numbers, not even. C - Incorrect because the operation squares the numbers, not just selects them. D - Incorrect because 6 is not in the original list.
Reference: Guttag, J. (2016). Introduction to Computation and Programming Using Python, 2nd Ed., MIT Press, Ch. 5.
Q4. Which of the following statements about Python's try/except blocks is TRUE?
A. An except block can catch multiple exception types by listing them in a tuple. B. The finally block is executed only if no exception occurs. C. An else block in a try statement is executed if an exception is raised. D. A try block must have at least one except block; finally alone is not allowed.
Correct Answer: A. An except block can catch multiple exception types by listing them in a tuple.
Rationale: Python allows except (TypeError, ValueError): to catch multiple exception types. The finally block always runs, the else block runs only if no exception occurs, and a try can have only finally.
Why Wrong: B - Incorrect because finally runs regardless of whether an exception occurred. C - Incorrect because else runs only when no exception is raised. D - Incorrect because try...finally is valid.
Reference: Python Documentation (2026). Errors and Exceptions, https://docs.python.org/3/tutorial/errors.html.
Q5. Given the code:
class A: def init(self, x): self.x = x def add(self, other): return self.x + other.x * 2
obj1 = A(3) obj2 = A(4) print(obj1 + obj2)
A. 11 B. 7 C. 14 D. TypeError
Correct Answer: A. 11
Rationale: The __add__ method is called, computing self.x + other.x * 2 = 3 + 4*2 = 11.
Why Wrong: B - Incorrect because this would be simple addition without the multiplication. C - Incorrect because this would be (3+4)*2, which is not the operator precedence used. D - Incorrect because __add__ is defined, so no TypeError occurs.
Reference: Lutz, M. (2013). Learning Python, 5th Ed., O'Reilly Media, Ch. 29.
Q6. What is the result of the following code?
s = "Hello, World!" print(s[::-1])
A. !dlroW ,olleH B. Hello, World! C. H D. SyntaxError
Correct Answer: A. !dlroW ,olleH
Rationale: The slice [::-1] reverses the string because the step is -1, iterating from the end to the beginning.
Why Wrong: B - Incorrect because this is the original string, not reversed. C - Incorrect because this would be the first character only, not the full reverse.
Correct Answer: A. 0 0 1 0 1 1 2 0 2 1 2 2
Rationale: The inner loop breaks when j > i, so for i=0, it prints only j=0; for i=1, prints j=0,1; for i=2, prints j=0,1,2. The output matches option A.
Why Wrong: B - Incorrect because this would be output without the break condition. C - Incorrect because this would be output if the inner loop only ran when i==j. D - Incorrect because this includes j values greater than i.
Reference: Zelle, J. (2016). Python Programming: An Introduction to Computer Science, 3rd Ed., Franklin Beedle, Ch. 8.
Q9. Which of the following code snippets correctly reads all lines from a file named 'data.txt' and prints each line without a trailing newline?
A. with open('data.txt') as f: for line in f: print(line, end='') B. with open('data.txt') as f: for line in f.readlines(): print(line) C. f = open('data.txt') for line in f: print(line)
f.close() D. with open('data.txt') as f: contents = f.read() print(contents)
Correct Answer: A. with open('data.txt') as f: for line in f: print(line, end='')
Rationale: Using print(line, end='') avoids adding an extra newline, and iterating over the file object yields lines with their original newlines. The other options add extra newlines or do not strip them.
Why Wrong: B - Incorrect because print(line) adds an extra newline. C - Incorrect because it also adds an extra newline and does not use a context manager. D - Incorrect because it prints the entire contents as one string, not line by line.
Reference: Python Documentation (2026). Reading and Writing Files, https://docs.python.org/3/tutorial/inputoutput.html.
Q10. Given the dictionary d = {'a': 1, 'b': 2, 'c': 3}, which expression returns a list of tuples sorted by value in descending order?
A. sorted(d.items(), key=lambda x: x[1], reverse=True) B. sorted(d.items(), key=lambda x: x[0], reverse=True) C. sorted(d.values(), reverse=True) D. sorted(d, key=lambda x: d[x], reverse=True)
Correct Answer: A. sorted(d.items(), key=lambda x: x[1], reverse=True)
Rationale: d.items() returns (key, value) pairs. Sorting with key=lambda x: x[1] sorts by value, and reverse=True gives descending order.
Why Wrong: B - Incorrect because this sorts by key, not value. C - Incorrect because this returns a list of values, not tuples. D - Incorrect because this returns a list of keys, not tuples.
Reference: Lutz, M. (2013). Learning Python, 5th Ed., O'Reilly Media, Ch. 8.
Q11. In Python, which of the following code snippets correctly creates a shallow copy of a list 'original' and then modifies an element in the nested list without affecting the original?
A. copy = original.copy(); copy[0][0] = 99 B. import copy; copy = copy.copy(original); copy[0][0] = 99 C. copy = original[:]; copy[0][0] = 99
C. O(n) for both due to hash collisions D. O(log n) for set, O(1) for list
Correct Answer: A. O(1) for both, but set has higher constant overhead
Rationale: Both sets and lists provide O(1) average-case access: sets via hash table, lists via index. However, sets have higher constant factors due to hashing and potential collision resolution.
Why Wrong: B - List access by index is O(1), not O(n). C - Average-case remains O(1) for sets; collisions are rare. D - Sets do not use trees; they use hash tables.
Reference: Cormen, T. et al. (2022). Introduction to Algorithms, 4th Ed., Ch. 11.
Q14. Given the following code:
x = [1, 2, 3] y = x x.append(4)
What is the value of y?
A. [1, 2, 3] B. [1, 2, 3, 4] C. None because y is a reference D. An error occurs
Correct Answer: B. [1, 2, 3, 4]
Rationale: In Python, assignment of a list to another variable creates a reference, not a copy. Modifying the list through x also affects y, so y reflects the appended element.
Why Wrong: A - Would be true if a copy were made, but assignment does not copy. C - y is a reference, but it still refers to the same list object. D - No error occurs; this is standard behavior.
Reference: Lutz, M. (2021). Learning Python, 5th Ed., Ch. 6.
Q15. Which of the following Python constructs correctly defines a decorator that measures execution time of a function?
A. def timer(f): def wrapper(*args, **kwargs): import time start = time.time()
result = f(*args, **kwargs) print(time.time()-start) return result return wrapper B. def timer(f): def wrapper(): import time start = time.time() f() print(time.time()-start) return wrapper C. @timer def foo(): pass D. def timer(f): import time start = time.time() return f
*Correct Answer: A. def timer(f): def wrapper(args, *kwargs): import time start = time.time() result = f(args, kwargs) print(time.time()-start) return result return wrapper
Rationale: A proper decorator returns a wrapper that accepts *args and **kwargs, calls the original function, measures time, and returns the result. Option A is the only one that preserves arguments and return value.
Why Wrong: B - Does not accept or forward arguments, breaking function signatures. C - This is usage, not definition. D - Measures time at definition, not at call, and does not wrap.
Reference: Beazley, D. (2024). Python Cookbook, 4th Ed., Recipe 9.1.
Q16. What is the output of the following code?
print(list(map(lambda x: x2, filter(lambda x: x%2==0, range(10)))))**
A. [0, 4, 16, 36, 64] B. [1, 9, 25, 49, 81]
Rationale: All three forms are valid: A catches multiple exceptions with one handler, B catches each separately, and C catches all exceptions (though bare except is discouraged). The question asks for a correct way, and all are syntactically valid.
Why Wrong: A - This is correct, so not wrong. B - This is correct, so not wrong. C - This is correct, so not wrong.
Reference: Python.org. (2026). Python Tutorial, Errors and Exceptions.
Q19. What is the result of the following expression?
'Hello, {}!'.format('World')
A. 'Hello, World!' B. 'Hello, {}!' C. An error because format requires more arguments D. 'Hello, World!' but with a deprecation warning
Correct Answer: A. 'Hello, World!'
Rationale: The format method replaces the placeholder {} with the argument 'World', producing 'Hello, World!'. It is a standard string formatting method.
Why Wrong: B - The placeholder is replaced, not kept. C - No error; one argument is provided. D - No deprecation warning; format is still supported.
Reference: Python.org. (2026). Python Standard Library, String Methods.
Q20. Which of the following is the most efficient way to check if a key exists in a Python dictionary?
A. if key in dict: B. try: dict[key] except KeyError: C. if dict.get(key) is not None: D. if key in dict.keys():
Correct Answer: A. if key in dict:
Rationale: The 'in' operator performs a direct hash lookup and is the most idiomatic and efficient method. It does not create a view or handle exceptions.
Why Wrong: B - This works but is less readable and slower due to exception handling. C - get() returns None for missing keys, but this fails if the value is None. D - dict.keys() creates a view, but 'in' on the dict is equivalent and faster.
Reference: Python.org. (2026). Python Tutorial, Dictionaries.
Q21. In Python, which of the following expressions would you use to determine the memory address of an object?
A. id(obj) B. memoryview(obj) C. hash(obj) D. repr(obj)
Correct Answer: A. id(obj)
Rationale: The built-in function id() returns the unique integer identifier (memory address) for an object in CPython. memoryview() exposes buffer protocol, hash() returns a hash value, and repr() returns a string representation. Thus, id() is the correct choice.
Why Wrong: B - memoryview() exposes the buffer interface, not the memory address. C - hash() returns a hash value, which is not guaranteed to be the memory address. D - repr() returns a string representation, not the memory address.
Reference: Lutz, M. (2021). Learning Python, 5th Ed., Ch. 6.
Q22. Given the code: x = [1, 2, 3]; y = x; y.append(4), what is the value of x?
A. [1, 2, 3] B. [1, 2, 3, 4] C. [4, 1, 2, 3] D. Raises an error
Correct Answer: B. [1, 2, 3, 4]
Rationale: In Python, lists are mutable objects. The assignment y = x creates a reference to the same list object, not a copy. Therefore, mutating y with append also mutates x. Hence, x becomes [1, 2, 3, 4].
Why Wrong: A - This would be true if y = x created a copy, but it does not. C - append adds to the end, not the beginning. D - No error is raised; the operation is valid.
Reference: Lutz, M. (2021). Learning Python, 5th Ed., Ch. 6.
Q23. What does the with statement do in Python?
A. Ensures that resources are properly cleaned up after use B. Creates a new scope for variables C. Imports modules lazily D. Handles exceptions in a block
Rationale: async and await are keywords in Python 3.5+ for asynchronous programming. nonlocal is a keyword used to declare variables in an enclosing scope. ensure is not a Python keyword; it might be confused with assert or try, but it is not reserved.
Why Wrong: A - async is a valid keyword for coroutines. B - await is a valid keyword for awaiting coroutines. D - nonlocal is a valid keyword for nested function scopes.
Reference: Python Documentation (2026). Keywords.
Q26. What is the time complexity of the in operator when used on a Python list vs. a Python set?
A. O(n) for list, O(1) average for set B. O(1) for both C. O(n) for both D. O(log n) for list, O(1) for set
Correct Answer: A. O(n) for list, O(1) average for set
Rationale: Lists are implemented as dynamic arrays; membership testing requires a linear scan, so in is O(n). Sets are implemented as hash tables, providing average-case O(1) membership testing. This difference is crucial for performance in large data sets.
Why Wrong: B - Lists are not hash-based; they require linear search. C - Sets use hashing, not linear search. D - Lists do not support binary search without sorting; the in operator is linear.
Reference: Lutz, M. (2021). Learning Python, 5th Ed., Ch. 8.
Q27. Which of the following is the correct way to open a file for both reading and writing without truncating it?
A. open('file.txt', 'r+') B. open('file.txt', 'w+') C. open('file.txt', 'a+') D. open('file.txt', 'rw')
Correct Answer: A. open('file.txt', 'r+')
Rationale: The mode 'r+' opens the file for both reading and writing without truncating it, preserving existing content. 'w+' truncates the file to zero length upon opening. 'a+' appends for writing and reads from the beginning. 'rw' is not a valid mode in Python.
Why Wrong: B - 'w+' truncates the file, losing existing data.
C - 'a+' forces writes to append at the end, not at the current position. D - 'rw' is not a recognized mode string.
Reference: Lutz, M. (2021). Learning Python, 5th Ed., Ch. 36.
Q28. Given the code: try: x = int('abc') except ValueError: print('Invalid') else: print('Valid') finally: print('Done'), what is the output?
A. Invalid Done B. Valid Done C. Invalid D. Done
Correct Answer: A. Invalid Done
Rationale: The int('abc') raises a ValueError, which is caught by the except block, printing 'Invalid'. The else block is skipped because an exception occurred. The finally block always executes, printing 'Done'. Thus, the output is 'Invalid Done'.
Why Wrong: B - The else block only runs if no exception is raised. C - The finally block always executes, so 'Done' is printed. D - The except block prints 'Invalid' before 'Done'.
Reference: Lutz, M. (2021). Learning Python, 5th Ed., Ch. 33.
Q29. Which of the following is the best way to create a constant in Python?
A. Using a class with only static members B. Using a tuple to store constant values C. Using a variable named in ALL_CAPS with no enforcement D. Using the const keyword
Correct Answer: C. Using a variable named in ALL_CAPS with no enforcement
Rationale: Python does not have a built-in constant type. By convention, names in ALL_CAPS are treated as constants, but they are still mutable. Using a class with static members or a tuple does not prevent reassignment of the variable itself. There is no const keyword in Python.
Why Wrong: A - Static members can still be reassigned unless the class is designed to prevent it, but it's not a standard approach. B - A tuple is immutable, but the variable referencing it can be reassigned. D - const is not a Python keyword.
Reference: PEP 8 (2026). Style Guide for Python Code.
Q30. What is the primary purpose of the if __name__ == '__main__': statement?
B. s.lower() == s.lower()[::-1] C. re.sub(r'[^a-zA-Z0-9]', '', s).lower() == re.sub(r'[^a-zA-Z0-9]', '', s).lower()[::-1] D. s.replace(' ', '').lower() == s.replace(' ', '').lower()[::-1]
Correct Answer: C. re.sub(r'[^a-zA-Z0-9]', '', s).lower() == re.sub(r'[^a-zA-Z0-9]', '', s).lower()[::-1]
Rationale: Option C uses the 're' module to remove all non-alphanumeric characters and then lowercases, ensuring that spaces and punctuation are ignored. Option A fails for case and punctuation. Option B ignores punctuation but not spaces. Option D only removes spaces, not punctuation.
Why Wrong: A - Ignores case and punctuation. B - Ignores punctuation but not spaces. D - Only removes spaces, not punctuation.
Reference: WGU E010, String Manipulation and Regular Expressions
Q33. Consider the following Python class definition. What will be the output when the code is executed?
A. 10 B. 20 C. 30 D. Error
Correct Answer: B. 20
Rationale: The class attribute 'x' is accessed via 'self.x' in the method. Since the instance does not have an attribute 'x', Python looks up the class attribute, which is 20. The method prints 20.
Why Wrong: A - Incorrectly assumes the instance attribute overrides. C - Incorrectly sums class and instance attributes. D - Incorrectly assumes an AttributeError.
Reference: WGU E010, Object-Oriented Programming in Python
Q34. Which of the following statements correctly describes the behavior of the 'with' statement in Python when managing file resources?
A. It only works with files and automatically closes them after the block. B. It requires an explicit call to close() at the end of the block. C. It uses context managers to ensure that resources are properly released even if an exception occurs. D. It is equivalent to a try-finally block but only for file objects.
Correct Answer: C. It uses context managers to ensure that resources are properly released even if an exception occurs.
Rationale: The 'with' statement works with any object that implements the context manager protocol (enter and exit), not just files. It guarantees cleanup of resources, such as closing files, even if an exception is raised. Option A is too narrow, B is incorrect because no explicit close is needed, D is incorrect because it applies to more than just files.
Why Wrong: A - It is not limited to files; it works with any context manager. B - The 'with' statement automatically handles cleanup without explicit close. D - It is not equivalent to a try-finally and applies to more than files.
Reference: WGU E010, Context Managers and Resource Management
Q35. Given the following code, what will be the output of the print statement?
A. 1 B. 2 C. 3 D. 4
Correct Answer: B. 2
Rationale: The lambda function captures the variable 'i' from the loop. However, due to late binding, all lambdas refer to the final value of 'i', which is 2. Thus, the first lambda returns 2. The output is 2.
Why Wrong: A - Incorrectly assumes early binding. C - Incorrectly assumes the loop runs a different number of times. D - Incorrectly assumes the lambda captures the value at definition time.
Reference: WGU E010, Closures and Late Binding
Q36. Which of the following Python code snippets correctly implements a decorator that logs the execution time of a function?
A. def timer(func): def wrapper(*args, *kwargs): import time start = time.time() result = func(args, **kwargs) print(time.time() - start) return result return wrapper B. def timer(func):