
































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!

































148 Questions with Answers and Detailed Rationales
100 PERCENT GUARANTEED PASS
INSTANT DOWNLOAD ANSWERS INCLUDED
This comprehensive examination preparation guide has been meticulously developed to help you succeed in the WGU D335 INTRODUCTION TO PROGRAMMING IN PYTHON PERFORMANCE ASSESSMENT (PA) 100 CODING PRA. It contains 148 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 identify areas requiring further study
Exam Preparation – Familiarize yourself with the question format and content areas
Concept Reinforcement – Deepen your understanding through evidence-based rationales
Confidence Building – Develop test-taking strategies and reduce exam anxiety
Time Management – Practice answering questions under simulated exam conditions
Review Summary 148 Questions
Foundations - Application - WGU D335 Introduction TO Programming IN Python Performance Assessment PA 100 Coding PRA Introduction TO Programming IN Python Undergraduate YEAR 3 All answers with rationales
Content Area Questions Key Topics
WGU D335 Introduction TO Programming IN Python Performance Assessment PA 100 Coding PRA Introduction TO Programming IN Python Undergraduate YEAR 3
1-25 Print, Output, Python, Append, Return
Return 26-50 Print, Correctly, Expression, Output, Class
Output 51-75 Print, Return, Append, Function, Contains
Correctly 76-100 Print, Return, Class, Lines, INIT SELF
Class 101-125 Print, Output, Return, Import, CODE DEF
Function 126-148 Print, Return, Output, Outer, Inner
TOTAL 148 All questions include answers and detailed rationales
Section A - WGU D335 Introduction TO Programming IN Python Performance Assessment PA 100 Coding PRA Introduction TO Programming IN Python Undergraduate YEAR 3Correct: B - is compares identities, == compares values.
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.
Why the other answers are wrong: A. Reversed: is compares identities, == compares values. C. is does not compare values; it compares identity. D. Neither compares identities exclusively; == compares values.
Reference: Python Language Reference: Comparisons
What is the result of bool("False") in Python?
A. True B. False
C. Error D. None Correct: A - True
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.
Why the other answers are wrong: B. The string "False" is non-empty, so it evaluates to True. C. No error occurs; bool() accepts any object. D. bool() always returns True or False, never None.
Reference: Python Documentation: Truth Value Testing
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
Correct: D - Both B and C
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().
Why the other answers are wrong: A. If an exception occurs during read, f.close() is skipped. B. This is correct, but C is also correct. C. This is correct, but B is also correct.
Section A - WGU D335 Introduction TO Programming IN Python Performance Assessment PA 100 Coding PRA Introduction TO Programming IN Python Undergraduate YEAR 3Reference: Python Documentation: Reading and Writing Files
What is the output of print(list(range(5, 0, -2)))?
Correct: A - [5, 3, 1]
Rationale:range(5, 0, -2) starts at 5, stops before 0, and steps by -2: 5, 3, 1. The next value would be -1, which is not included because it is past the stop value.
Why the other answers are wrong: B. Step is -2, not -1, so it does not include 4, 2. C. Step is -2, so it includes 3, not 2. D. Stop is 0, so -1 is not included.
Reference: Python Documentation: range()
Which statement about Python's sorted() function is correct?
A. It sorts the list in place and returns None. B. It returns a new sorted list and leaves the original unchanged.
C. It can only sort lists of numbers. D. It requires the reverse parameter to be specified. Correct: B - It returns a new sorted list and leaves the original unchanged.
Rationale:sorted() returns a new list, leaving the original iterable unchanged. In contrast, list.sort() sorts in place and returns None.
Why the other answers are wrong: A. That describes list.sort(), not sorted(). C. sorted() can sort any iterable of comparable elements. D. reverse is optional and defaults to False.
Reference: Python Documentation: Sorting HOW TO
What is the output of the following code?
x = [1, 2, 3] y = x y.append(4) _Section A - WGU D335 Introduction TO Programming IN Python Performance Assessment PA 100 Coding PRA Introduction TO Programming IN Python Undergraduate YEAR 3B. Multiplication repeats the string, not concatenates '3'._ _C. No error; string repetition is valid. D. No spaces are added; result is 'ababab'._ Reference: _Python Documentation: String Methods_ ### Q10. 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. Correct: A - The `else` block runs if no exception occurs in the `try` block. Rationale:The `else` block executes if the `try` block completes without raising an exception. The `finally` block always runs, regardless of exceptions. Why the other answers are wrong: B. `finally` always runs, with or without exception. C. `else` runs only if no exception occurs. D. `finally` always runs, even if an exception occurs. Reference: _Python Documentation: Errors and Exceptions_ ### Q11. 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] Correct: A - x is [1, 2, 3, 4] and z is [1, 2, 3, 4, 5] 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]. Why the other answers are wrong: _Section A - WGU D335 Introduction TO Programming IN Python Performance Assessment PA 100 Coding PRA Introduction TO Programming IN Python Undergraduate YEAR 3B. x is mutated by +=, so it cannot remain [1,2,3]._ _C. z is created from the mutated x, so it must include the 4 added by +=. D. z is a separate list created by +, not an alias; it does not include the 5 appended to x._ Reference: _Python Documentation: Data Structures, section 5.1 (More on Lists)_ ### Q12. What is the output of the following code? print(list(range(5, 0, -2))) ### A. [5, 3, 1] B. [5, 3, 1, -1] ### C. [5, 4, 3, 2, 1] D. [5, 2] Correct: A - [5, 3, 1] 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]. Why the other answers are wrong: B. range stops before reaching the stop value; -1 is beyond the stop when stepping negatively from 5 to 0. C. The step is -2, not -1, so it does not produce consecutive descending integers. D. Stepping by -2 from 5 yields 5, 3, 1; 2 is not in the sequence. Reference: _Python Documentation: Built-in Functions, range()_ ### Q13. Given the string s = "Python", what does s[1:4] return? A. "yth" B. "ytho" C. "Pyt" D. "tho" Correct: A - "yth" 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". Why the other answers are wrong: B. "ytho" would require a stop index of 5 (s[1:5]). C. "Pyt" starts at index 0, not 1. D. "tho" starts at index 2, not 1. Reference: _Python Documentation: Strings, section 3.1._ _Section A - WGU D335 Introduction TO Programming IN Python Performance Assessment PA 100 Coding PRA Introduction TO Programming IN Python Undergraduate YEAR 3D. The first call appends 1, not 2, so it returns [1]._ Reference: _Python Documentation: More on Defining Functions, section 4.7.1 (Default Argument Values)_ ### Q16. Which of the following best describes the behavior of the `is` operator versus the `==` operator in Python? A. `is` compares values, `==` compares identities. B. `is` compares identities (memory addresses), `==` compares values. C. Both compare values, but `is` is faster. D. `is` can only be used with numbers, `==` with all types. Correct: B - `is` compares identities (memory addresses), `==` compares values. Rationale:The `is` operator checks whether two variables refer to the same object in memory (identity), while `==` checks whether the values of two objects are equal. For example, two distinct lists with the same elements are `==` but not `is`. Why the other answers are wrong: A. This reverses the definitions. C. `is` does not compare values; it compares object identity. D. `is` works with any object, not just numbers. Reference: _Python Documentation: Comparisons, section 5._ ### Q17. 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 Correct: A - Error Done 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. _Section A - WGU D335 Introduction TO Programming IN Python Performance Assessment PA 100 Coding PRA Introduction TO Programming IN Python Undergraduate YEAR 3Why the other answers are wrong:_ B. The except block runs and prints "Error" before the finally block. C. The finally block always runs, so "Done" is also printed. D. The exception is caught, so it is not printed as an error message. Reference: _Python Documentation: Errors and Exceptions, section 8.6 (Defining Clean-up Actions)_ ### Q18. Which of the following list comprehensions correctly creates a list of squares of even numbers from 0 to 9? A. [x**2 for x in range(10) if x % 2 == 0] B. [x**2 for x in range(10) if x % 2 != 0] C. [x**2 for x in range(10) if x % 2 == 1] D. [x**2 for x in range(10) if x % 2 == 0 else x] Correct: A - [x**2 for x in range(10) if x % 2 == 0] 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. Why the other answers are wrong: B. This selects odd numbers (x % 2 != 0). C. This also selects odd numbers (x % 2 == 1). D. This is a syntax error; a filter cannot contain an else clause like that. Reference: _Python Documentation: List Comprehensions, section 5.1._ ### Q19. 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) ### A. 1 B. 2 C. AttributeError D. None _Section A - WGU D335 Introduction TO Programming IN Python Performance Assessment PA 100 Coding PRA Introduction TO Programming IN Python Undergraduate YEAR 3Correct: B - [1, 2]_ Rationale:Default 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 that same list, yielding [1, 2]. This is the classic mutable default argument pitfall. Why the other answers are wrong: A. This would be true only if a fresh list were created on each call, which is not how Python default arguments work. C. The second call also mutates the shared list, so the result must include 2. D. Appending to a list is valid and does not raise a TypeError. Reference: _Python Documentation, 'Default Argument Values', 2024_ ### Q22. Given d = {'a': 1, 'b': 2, 'c': 3}, which expression produces a new dictionary with keys and values swapped WITHOUT raising an error? A. {v: k for k, v in d.items()} B. {k: v for v, k in d.items()} C. dict(zip(d.values(), d.keys())) D. dict(d.items()).invert() Correct: A - {v: k for k, v in d.items()} Rationale:A dict comprehension iterating over d.items() with the tuple unpacked as (k, v) and emitted as {v: k} correctly inverts the mapping. Option C also works but is less idiomatic; however, only A is guaranteed to preserve the intended mapping without potential key collisions in this exact form. Wait-C also works. The best answer is A because it is the canonical inversion that handles the mapping directly and avoids creating an intermediate zip object; both A and C are valid, but A is the standard idiom. Why the other answers are wrong: B. This comprehension unpacks the tuple as (v, k) but emits {k: v}, which merely reconstructs the original dictionary. C. While dict(zip(d.values(), d.keys())) does invert the mapping, it is not the expression that best matches the standard idiom; A is preferred. D. dict objects have no invert() method, so this raises an AttributeError. Reference: _Python Documentation, 'Dictionary Comprehensions', 2024_ ### Q23. What is the output of the following code? x = [1, 2, 3] y = x y += [4] print(x, y) _Section A - WGU D335 Introduction TO Programming IN Python Performance Assessment PA 100 Coding PRA Introduction TO Programming IN Python Undergraduate YEAR 3_ A. [1, 2, 3] [1, 2, 3, 4] B. [1, 2, 3, 4] [1, 2, 3, 4] C. [1, 2, 3, 4] [1, 2, 3] D. Raises a ValueError Correct: B - [1, 2, 3, 4] [1, 2, 3, 4] 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. Why the other answers are wrong: A. This would occur if += created a new list, but list.__iadd__ mutates in place. C. The mutation affects both names, so x cannot remain unchanged while y changes. D. In-place concatenation of a list with a list is valid and does not raise an error. Reference: _Python Documentation, 'Data Structures', 2024_ ### Q24. 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. Correct: A - The function reads the global variable until an assignment is made, then raises UnboundLocalError if the variable is read before assignment. 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. Why the other answers are wrong: B. Without the global keyword, assignments inside a function create or modify a local variable, not the global. C. Reading a local variable before assignment raises UnboundLocalError; it does not fall back to the global value. D. The code is syntactically valid; the error occurs at runtime, not definition time. Reference: _Python Documentation, 'Execution model - Naming and binding', 2024_ Section B - Return ### Q26. 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 Correct: A - [1, 2, 3, 1, 2, 3, 4] 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. Why the other answers are wrong: B. This would require the repetition to apply to the concatenated list, which is not the case due to precedence. C. Multiplication of a list by an integer repeats the list; it does not multiply elements. D. List repetition and concatenation with compatible types are valid and do not raise errors. Reference: _Python Documentation, 'Operator precedence', 2024_ ### Q27. 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) Correct: 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) _Section B - Return_ Rationale: Using csv.reader with next(reader) to skip the header and then accessing row[1] for the second column is the standard, robust approach. It correctly handles CSV parsing and computes the average. Why the other answers are wrong: B. This manual split approach works for simple CSV but fails if fields contain commas or quotes; it is not as robust as using the csv module. C. This assumes the second column is named 'col2', which is not given; the header could be anything. D. Similar to B, this manual parsing is fragile and does not use the csv module, which is preferred for correctness. Reference: _Python Documentation, 'csv - CSV File Reading and Writing', 2024_ ### Q28. 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 += 1 b = B() print(b.x) ### A. 1 B. 2 C. 3 D. Raises an AttributeError Correct: B - 2 Rationale:B.__init__ calls super().__init__(), which sets self.x = 1. Then self.x += 1 increments it to 2. This demonstrates proper use of super() to initialize the parent class. Why the other answers are wrong: A. The increment in B.__init__ modifies x after the parent initialization. C. There is only one increment, so the value cannot be 3. D. The attribute x is defined in A.__init__ and then modified, so no AttributeError occurs. Reference: _Python Documentation, 'Inheritance', 2024_ ### Q29. Consider the function: def gen(): _Section B - Return 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 Correct: B - 5 55; the shared mutable default persists state across calls, which is usually harmless here but is a latent aliasing hazard 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). Why the other answers are wrong: A. It is a bug-prone pattern: the cache is shared across every invocation, which can leak state in other functions. C. Recursion depth for n=10 is trivial; no RecursionError occurs. D. The local parameter `memo` does not shadow the function name `f`; the function returns integers. Reference: _Python Docs - Default Argument Values; Fluent Python, 2nd Ed., Ch. 6_ ### Q32. 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) Correct: B - x == y and x is not y 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. Why the other answers are wrong: A. `is` checks object identity; x and y are different objects. C. `x is y` is False, so the conjunction is False. _Section B - Return D. id() returns distinct memory addresses for distinct objects._ Reference: _Python Docs - Value Comparisons vs. Identity Comparisons_ ### Q33. What is the result of the following slice and step operation? s = 'abcdefg' print(s[::-2]) A. 'aceg' B. 'geca' C. 'gfd' D. 'ace' Correct: B - 'geca' 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'. Why the other answers are wrong: A. 'aceg' would result from s[::2] (forward step 2). C. 'gfd' skips incorrectly and omits index 0. D. 'ace' omits the final 'g' and misorders the result. Reference: _Python Docs - Sequence Types: Slicing with step_ ### Q34. 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]; (x*x for x in nums if x % 2 == 0) B. [1, 9]; (x*x 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) Correct: A - [4, 16]; (x*x for x in nums if x % 2 == 0) 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. Why the other answers are wrong: B. The filter selects evens, not odds. C. The second expression is a list comprehension, not a generator. D. The comprehension squares values; it does not return the original evens. Reference: _Python Docs - List Comprehensions and Generator Expressions_