Docsity

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

Partial preview of the text

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

Question 1

What is the output of the following code?

def f(a, b=[]): b.append(a) return b print(f(1)) print(f(2, [])) print(f(3))

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

Correct Answer: A - [1] [2] [1, 3]

RATIONALE The default argument b=[] is mutable and shared across calls. First call f(1) appends 1 to the default list, returning [1]. Second call f(2, []) uses a new list, returning [2]. Third call f(3) uses the same default list (now [1]) and appends 3, returning [1, 3].

Question 2

Which statement about Python's is operator versus == is true?

A. is compares values, == compares identities. B. is compares identities, == compares values. C. Both compare values but is is faster. D. Both compare identities but == is stricter.

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().

Question 5

What is the output of print(list(range(5, 0, -2)))?

A. [5, 3, 1] B. [5, 4, 3, 2, 1] C. [5, 2] D. [5, 3, 1, -1]

Correct Answer: 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.

Question 6

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 Answer: 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.

Question 7

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. [4] D. Error

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

RATIONALE Assignment y = x makes both variables refer to the same list object. Modifying y also modifies x, so x becomes [1, 2, 3, 4].

Question 8

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

values 1, 2?

A. d = {'a': 1, 'b': 2} B. d = dict('a'=1, 'b'=2) C. d = dict([('a', 1), ('b', 2)]) D. Both A and C

Correct Answer: D - Both A and C

Question 11

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 Answer: 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].

Question 12

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 Answer: 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].

Question 13

Given the string s = "Python", what does s[1:4] return?

A. "yth" B. "ytho" C. "Pyt" D. "tho"

Correct Answer: 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".

Question 14

What is the result of the following dictionary operation?

d = {'a': 1, 'b': 2}

print(d.get('c', 0) + d.get('a', 0))

A. 1 B. 0 C. 3 D. KeyError

Correct Answer: A - 1

Question 16

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 Answer: 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.

Question 17

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 Answer: 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.

Question 18

Which of the following list comprehensions correctly creates a list of squares

of even numbers from 0 to 9?

A. [x2 for x in range(10) if x % 2 == 0] B. [x2 for x in range(10) if x % 2 != 0] C. [x2 for x in range(10) if x % 2 == 1] D. [x2 for x in range(10) if x % 2 == 0 else x]

Correct Answer: 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.

D. It is optional and if not defined, the class cannot be instantiated.

Correct Answer: B - It is called automatically when an instance is

created and initializes the instance.

RATIONALE __init__ is the initializer method, called after the instance is created by __new__. It initializes the instance's attributes. It should not return anything other than None; returning a non-None value raises TypeError. It is not a constructor in the sense of creating the object; that is __new__. If not defined, the class can still be instantiated.

Question 21

Consider the function:

def f(n, acc=[]):

acc.append(n) return acc

What is the value of f(2) after the two calls f(1) then f(2)?

A. [2] B. [1, 2] C. [1] D. Raises a TypeError

Correct Answer: 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.

Question 22

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 Answer: 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.

Question 23

What is the output of the following code?

x = [1, 2, 3]

y = x

y += [4]

print(x, y)

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 Answer: B - [1, 2, 3, 4] [1, 2, 3, 4]

for line in lines: f.write(line) B. with open('out.txt', 'w') as f: for line in lines: print(line, file=f) C. with open('out.txt', 'w') as f: f.writelines(lines) D. with open('out.txt', 'w') as f: f.write('\n'.join(lines))

Correct Answer: A - with open('out.txt', 'w') as f:

for line in lines:

f.write(line)

RATIONALE Writing each line directly with f.write(line) preserves the existing newline characters and adds none. Option C (writelines) also works, but A is the most explicit and avoids any ambiguity. Both A and C are correct; A is the simplest direct write.

Question 26

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 Answer: 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.

Question 27

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 Answer: A - import csv

with open('data.csv') as f:

reader = csv.reader(f)

Question 29

Consider the function:

def gen():

for i in range(3): yield i if i == 1: return

What is the output of list(gen())?

A. [0, 1, 2] B. [0, 1] C. [0, 1, 2, 0, 1, 2] D. Raises a StopIteration error

Correct Answer: B - [0, 1]

RATIONALE The generator yields 0, then 1. When i == 1, the return statement terminates the generator, so 2 is never yielded. list(gen()) collects the yielded values, resulting in [0, 1].

Question 30

Which statement about Python's exception handling is correct regarding the

else clause in a try-except-else block?

A. The else block executes only if no exception is raised in the try block. B. The else block executes regardless of whether an exception is raised. C. The else block executes only if an exception is raised and caught. D. The else block executes before the try block.

Correct Answer: A - The else block executes only if no exception

is raised in the try block.

RATIONALE In a try-except-else construct, the else block runs only if the try block completes without raising an exception. It is useful for code that should run only when no exception occurs.

Question 31

Consider the following code:

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 Answer: B - 5 55; the shared mutable default persists

state across calls, which is usually harmless here but is a latent

aliasing hazard