Docsity

WGU D335 INTRODUCTION TO PROGRAMMING IN PYTHON PERFORMANCE ASSESSMENT (PA) 100 CODING PRA, Exams of Computer Science

Toggle sidebar
bg1
Page 1
WGU D335 INTRODUCTION TO PROGRAMMING IN PYTHON -
PERFORMANCE ASSESSMENT (PA) 100 CODING PRACTICE
QUESTIONS WITH VERIFIED SOLUTIONS
129 QUESTIONS
TABLE OF CONTENTS
# TOPIC
1 Write Python code using correct syntax and semantics
2 Trace and predict the output of Python code snippets
3 Apply control flow, data structures, and functions to solve problems
4 Identify and handle runtime errors using exceptions
5 Read from and write to files using Python
6 WGU D335 INTRODUCTION TO PROGRAMMING IN PYTHON
7 PERFORMANCE ASSESSMENT
8 100 CODING PRACTICE QUESTIONS WITH VERIFIED SOLUTIONS
9 Foundations of Computer Science / Python Programming
10 Applied Computer Science / Python Programming
11 Advanced Computer Science / Python Programming
12 Computer Science / Python Programming Review
ABSTRACT
This study document brings together 129 carefully worded exam questions drawn from WGU D335
INTRODUCTION TO PROGRAMMING IN PYTHON - PERFORMANCE ASSESSMENT (PA) 100
CODING PRACTICE QUESTIONS WITH VERIFIED SOLUTIONS, with the strongest emphasis
placed on Write Python code using correct syntax and semantics, Trace and predict the output of
Python code snippets, Apply control flow, data structures and and functions to solve problems.
Every item follows the wording style and level of reasoning you meet in the real paper, and each
one is paired with a clear rationale so the correct choice is never a guess. Work through the set at
your own pace, mark the questions that slow you down, then come back to them until the
reasoning feels automatic. Learners who revise this way walk into the exam room recognising the
pattern behind the questions instead of meeting them for the first time. Keep going - steady, honest
practice is what turns a difficult paper into a comfortable pass.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d

Partial preview of the text

Download WGU D335 INTRODUCTION TO PROGRAMMING IN PYTHON PERFORMANCE ASSESSMENT (PA) 100 CODING PRA and more Exams Computer Science in PDF only on Docsity!

WGU D335 INTRODUCTION TO PROGRAMMING IN PYTHON -

PERFORMANCE ASSESSMENT (PA) 100 CODING PRACTICE

QUESTIONS WITH VERIFIED SOLUTIONS

129 QUESTIONS

TABLE OF CONTENTS

# TOPIC 1 Write Python code using correct syntax and semantics 2 Trace and predict the output of Python code snippets 3 Apply control flow, data structures, and functions to solve problems 4 Identify and handle runtime errors using exceptions 5 Read from and write to files using Python 6 WGU D335 INTRODUCTION TO PROGRAMMING IN PYTHON 7 PERFORMANCE ASSESSMENT 8 100 CODING PRACTICE QUESTIONS WITH VERIFIED SOLUTIONS 9 Foundations of Computer Science / Python Programming 10 Applied Computer Science / Python Programming 11 Advanced Computer Science / Python Programming 12 Computer Science / Python Programming Review

ABSTRACT

This study document brings together 129 carefully worded exam questions drawn from WGU D INTRODUCTION TO PROGRAMMING IN PYTHON - PERFORMANCE ASSESSMENT (PA) 100 CODING PRACTICE QUESTIONS WITH VERIFIED SOLUTIONS, with the strongest emphasis placed on Write Python code using correct syntax and semantics, Trace and predict the output of Python code snippets, Apply control flow, data structures and and functions to solve problems. Every item follows the wording style and level of reasoning you meet in the real paper, and each one is paired with a clear rationale so the correct choice is never a guess. Work through the set at your own pace, mark the questions that slow you down, then come back to them until the reasoning feels automatic. Learners who revise this way walk into the exam room recognising the pattern behind the questions instead of meeting them for the first time. Keep going - steady, honest practice is what turns a difficult paper into a comfortable pass.

Q1 WRITE PYTHON CODE USING CORRECT SYNTAX AND SEMANTICS

What is the output of the following code snippet?

A. [1, 4, 9, 16, 25]

B. [0, 1, 4, 9, 16] CORRECT

C. [1, 4, 9, 16]

D. [0, 1, 4, 9]

RATIONALE: The list comprehension iterates i from 0 to 4, computing i*i for each. Thus, it produces [0, 1, 4, 9, 16]. Options A, C, and D are incorrect because they either miss the initial 0 or include the square of 5.

Q2 WRITE PYTHON CODE USING CORRECT SYNTAX AND SEMANTICS

Which of the following statements about Python's global and local scope is true?

A. Variables declared inside a function are always global. B. The 'global' keyword is required to read a global variable inside a function. C. A variable defined inside an if block is not accessible outside that block. D. The 'nonlocal' keyword allows a nested function to modify a variable in the enclosing function's scope. CORRECT RATIONALE: The 'nonlocal' keyword is used to bind a variable in a nested function to a variable in the enclosing function's scope, allowing modification. Option A is false because variables inside functions are local by default. Option B is false because reading global variables does not require 'global'. Option C is false because Python has function-level scope, not block-level.

Q5 WRITE PYTHON CODE USING CORRECT SYNTAX AND SEMANTICS

What is the output of the following code?

A. 0

CORRECT

B. 1

C. 0

D. 1

RATIONALE: The while loop starts with i=0 and continues while i < 3. It prints i and increments it. Thus, it prints 0, 1, 2. Option B would be the output if i started at 1. Option C would be the output if the condition were i <= 3. Option D would be the output if i started at 1 and the condition were i < 3.

Q6 WRITE PYTHON CODE USING CORRECT SYNTAX AND SEMANTICS

Which of the following correctly opens a file 'data.txt' for reading and prints each

line after stripping trailing newlines?

A. with open('data.txt', 'r') as f: for line in f: print(line.rstrip()) CORRECT B. with open('data.txt', 'r') as f: for line in f: print(line) C. f = open('data.txt', 'r') for line in f: print(line.strip()) f.close() D. with open('data.txt', 'r') as f: for line in f.readlines(): print(line) RATIONALE: Option A uses a context manager and the rstrip() method to remove trailing newline characters. Option B does not strip newlines. Option C does not use a context manager, which is less safe. Option D does not strip newlines either.

Q7 WRITE PYTHON CODE USING CORRECT SYNTAX AND SEMANTICS

What is the result of evaluating the expression: 2 ** 3 ** 2?

A. 64

B. 512 CORRECT

C. 4096

D. 256

RATIONALE: In Python, exponentiation is right-associative, so 2 ** 3 ** 2 is evaluated as 2 ** ( ** 2) = 2 ** 9 = 512. Option A is (23)2 = 82 = 64. Option C is 212, and Option D is 2**8.

Q9 WRITE PYTHON CODE USING CORRECT SYNTAX AND SEMANTICS

Given the code snippet:

try:

x = int('abc')

except ValueError:

print('ValueError')

except Exception:

print('Exception')

else:

print('No error')

finally:

print('Finally')

What is the output?

A. ValueError Finally CORRECT B. Exception Finally C. ValueError No error Finally D. Exception No error Finally RATIONALE: int('abc') raises a ValueError, which is caught by the first except block. The else block is skipped because an exception occurred. The finally block always executes, printing 'Finally'. Thus, the output is 'ValueError' then 'Finally'. Option B would be correct if a different exception were raised. Options C and D incorrectly include 'No error'.

Q10 WRITE PYTHON CODE USING CORRECT SYNTAX AND SEMANTICS

Which of the following expressions creates a dictionary with keys 'a', 'b', 'c' and

values 1, 2, 3?

A. dict(zip(['a','b','c'], [1,2,3])) B. {'a':1, 'b':2, 'c':3} C. dict(a=1, b=2, c=3) D. All of the above CORRECT RATIONALE: All three methods correctly create the same dictionary. Option A uses zip to pair keys and values, Option B uses a literal, and Option C uses keyword arguments. Therefore, all are valid.

Q11 WRITE PYTHON CODE USING CORRECT SYNTAX AND SEMANTICS

In a Python program, a developer defines a function that uses a variable named

count both as a global and as a local in a nested function. The nested function

includes the statement nonlocal count. If the global count is 10 and the

enclosing function sets count = 5, what is the value of count after calling the

nested function that executes count += 1?

A. 6 CORRECT

B. 11

C. 5

D. NameError RATIONALE: The nonlocal declaration binds count to the variable in the nearest enclosing scope (the enclosing function), not the global. Thus, the increment modifies the enclosing function's variable from 5 to 6. The global count remains 10. If nonlocal were omitted, a new local would be created, but here it correctly targets the enclosing scope.

Q14 TRACE AND PREDICT THE OUTPUT OF PYTHON CODE SNIPPETS

A Python script uses open('data.txt', 'r') to read a file. Which of the following is

the most appropriate way to ensure the file is closed even if an exception occurs?

A. Using with open('data.txt', 'r') as f: B. Calling f.close() at the end of the script C. Using try: f = open(...) finally: f.close() D. Both A and C CORRECT RATIONALE: The with statement automatically closes the file, and a try-finally block also guarantees closure. Merely calling close at the end (B) does not handle exceptions. Both A and C are correct, so D is the best answer.

Q15 TRACE AND PREDICT THE OUTPUT OF PYTHON CODE SNIPPETS

Which of the following statements about Python's __init__ method is true?

A. It is the first method called when an object is created B. It is optional in a class definition C. It can return a value D. It is called after __new__ CORRECT RATIONALE: __init__ is called after __new__ (which actually creates the instance). It is not the first method called (A); it is optional (B) but that statement is true yet not the best answer? Actually, B is also true, but D is more specific. __init__ cannot return a value (C). D is the most precise.

Q16 TRACE AND PREDICT THE OUTPUT OF PYTHON CODE SNIPPETS

Consider the following code snippet:

```python

def outer():

x = 1

def inner():

return x

return inner

func = outer()

print(func())

```

What is the output?

A. 1 CORRECT

B. None C. Error D. x RATIONALE: Python closures allow inner to access x from the enclosing scope, even after outer has finished. Thus, calling func() returns 1. No error occurs, and the value is an integer, not a string.

Q17 TRACE AND PREDICT THE OUTPUT OF PYTHON CODE SNIPPETS

Which of the following is the correct way to define a class method that can be

called on the class itself without an instance?

A. Using @classmethod decorator CORRECT B. Using @staticmethod decorator C. Using @property decorator D. Defining a method without self RATIONALE: @classmethod takes cls as the first parameter and can be called on the class. @staticmethod also can be called on the class but doesn't receive cls automatically. @property is for instance attributes. Defining without self alone is not sufficient.

Q20 TRACE AND PREDICT THE OUTPUT OF PYTHON CODE SNIPPETS

Consider the following code:

```python

x = [1, 2, 3]

y = x

x += [4]

print(y)

```

What is the output?

A. [1, 2, 3]

B. [1, 2, 3, 4] CORRECT

C. Error D. None RATIONALE: The += operator on a list mutates the list in place, so x and y both reference the same list object. Thus, y also becomes [1, 2, 3, 4]. If you used x = x + [4], it would create a new list, leaving y unchanged.

Q21 TRACE AND PREDICT THE OUTPUT OF PYTHON CODE SNIPPETS

A developer writes a decorator that caches function results. The decorator uses a

dictionary keyed by a tuple of arguments. Which approach correctly handles

functions with keyword arguments while avoiding unintended cache collisions?

A. Use repr(args) + repr(kwargs) as the key, ensuring deterministic string representation. B. Convert kwargs to a frozenset of items and combine with args in a tuple, but only if all values are hashable. CORRECT C. Use a custom object that overrides eq and hash to ignore argument order. D. Use a key based on the function's code.co_varnames to map positional to keyword names. RATIONALE: Option B is correct because it creates a hashable, order-independent key: args as a tuple and kwargs items as a frozenset, which prevents collisions from different keyword orderings. Option A fails because repr strings can collide (e.g., spaces) and are not robust. Option C is over-engineered and can still cause collisions if not carefully implemented. Option D ignores actual argument values and would collide for different arguments.

Q22 TRACE AND PREDICT THE OUTPUT OF PYTHON CODE SNIPPETS

Given the code: x = [1, 2]; y = x; y.append(3); x = x + [4], what are the final values

of x and y?

A. x = [1, 2, 3, 4], y = [1, 2, 3, 4] B. x = [1, 2, 4], y = [1, 2, 3] C. x = [1, 2, 3, 4], y = [1, 2, 3] CORRECT D. x = [1, 2, 4], y = [1, 2, 3, 4] RATIONALE: Initially, x and y reference the same list. y.append(3) mutates that shared list to [1,2,3]. Then x = x + [4] creates a new list [1,2,3,4] and rebinds x, leaving y pointing to the original mutated list. Thus x is [1,2,3,4] and y is [1,2,3].

Q23 APPLY CONTROL FLOW, DATA STRUCTURES, AND FUNCTIONS TO SOLVE PROBLEMS

Which of the following correctly defines a Python function that takes a variable

number of keyword arguments and returns them sorted by value?

A. def sort_kwargs(kwargs): return sorted(kwargs.values()) CORRECT** B. def sort_kwargs(args): return sorted(args, key=lambda x: x[1]) C. def sort_kwargs(kwargs): return sorted(kwargs.items(), key=lambda x: x[0]) D. def sort_kwargs(*kwargs): return sorted(kwargs.keys()) RATIONALE: Option A uses **kwargs to collect keyword arguments and returns a sorted list of their values. Option B uses *args, which collects positional arguments, not keyword. Option C sorts by key, not value. Option D returns sorted keys, not values.

Q26 APPLY CONTROL FLOW, DATA STRUCTURES, AND FUNCTIONS TO SOLVE PROBLEMS

Given the code def gen(): yield 1; yield 2; return 3, what is the result of

list(gen())?

A. [1, 2, 3]

B. [1, 2] CORRECT

C. Raises StopIteration with value 3 D. [3] RATIONALE: A generator function yields values until it returns. The return 3 stops the generator and the value is not included in iteration; it is stored as the StopIteration value. Thus list(gen()) yields [1, 2]. Option A is incorrect because the return value is not yielded. Option C is incorrect because StopIteration is not raised when iterating normally. Option D is incorrect.

Q27 APPLY CONTROL FLOW, DATA STRUCTURES, AND FUNCTIONS TO SOLVE PROBLEMS

What is the output of the following code?

```python

class A:

def init(self):

self.x = 1

def get(self):

return self.x

class B(A):

def init(self):

super().init()

self.x = 2

def get(self):

return self.x * 2

a = A()

b = B()

print(a.get(), b.get())

```

A. 1 4 CORRECT

B. 1 2

C. 2 4

D. 1 1

RATIONALE: Class A's get returns self.x, so a.get() returns 1. Class B overrides init to set self.x = 2 and overrides get to return self.x * 2, so b.get() returns 4. The super().init() call sets x to 1 but then B's init sets it to 2. Thus output is '1 4'.

Q29 APPLY CONTROL FLOW, DATA STRUCTURES, AND FUNCTIONS TO SOLVE PROBLEMS

Given the code:

```python

import copy

original = [[1, 2], [3, 4]]

shallow = copy.copy(original)

deep = copy.deepcopy(original)

shallow[0].append(99)

deep[0].append(100)

print(original)

```

What is the output?

A. [[1, 2, 99], [3, 4]] CORRECT

B. [[1, 2, 100], [3, 4]]

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

D. [[1, 2, 99, 100], [3, 4]]

RATIONALE: Shallow copy shares the inner lists, so modifying shallow[0] also affects original[0], adding 99. Deep copy creates independent inner lists, so modifying deep[0] does not affect original. Thus original becomes [[1, 2, 99], [3, 4]]. Option B would be true if original had been modified by deep copy, which it isn't. Option C ignores the shallow copy effect. Option D incorrectly combines both modifications.

Q30 APPLY CONTROL FLOW, DATA STRUCTURES, AND FUNCTIONS TO SOLVE PROBLEMS

Which of the following correctly demonstrates the use of functools.partial to

create a function that adds 5 to its argument?

A. add5 = partial(lambda x, y: x + y, 5) CORRECT B. add5 = partial(lambda x: x + 5) C. add5 = partial(lambda x, y: x + y, y=5) D. add5 = partial(lambda x, y: x + y, x=5) RATIONALE: Option A uses partial to fix the first argument of a two-argument lambda to 5, leaving the second argument to be supplied. Option B is just a lambda with one argument and partial is not needed; also partial with one arg would not work correctly. Option C fixes y=5, so calling add5(3) would result in an error because x is missing. Option D fixes x=5, so calling add5(3) would also error because y is missing. Thus A is correct.

Q31 APPLY CONTROL FLOW, DATA STRUCTURES, AND FUNCTIONS TO SOLVE PROBLEMS

In a Python class, you define slots = ('x', 'y'). Which of the following is TRUE

about instances of this class?

A. They cannot have a dict attribute and attempts to assign an undeclared attribute raise AttributeError. CORRECT B. They can still have attributes added dynamically if the class defines getattr. C. They automatically become immutable, preventing any changes to x and y after initialization. D. They consume more memory than instances without slots because each slot stores a separate descriptor. RATIONALE: Defining slots prevents the creation of a per-instance dict, so only the listed attributes can be set. Assigning an undeclared attribute raises AttributeError, making A correct. B is false because getattr is only called for missing attributes, and with slots missing attributes still raise AttributeError unless getattr defines them, but the attribute is not stored. C is incorrect because slots does not make instances immutable. D is wrong because slots typically reduces memory overhead.