Docsity

WGU D335 Python OA Exam 450+ Practice Questions with Verified Solutions, Code Snippets,, Exams of Computer Science

Toggle sidebar
bg1
WGU D335 Python OA Exam 450+ Practice Questions
with Verified Solutions, Code Snippets, Error Types,
and Test-Taking Strategies for Objective Assessment
Success
part 1: Fundamentals, Variables, and Data Types
1. What is the data type of the variable x after the following assignment?
x = 5 / 2
A. int
B. float
C. string
D. list
Correct Answer: B. float
Rationale: The division operator (/) in Python always returns a floating-point
number, even if the result is a whole number. Therefore, 5 / 2 evaluates to 2.5, which
is a float.
2. What is the purpose of using int(input()) instead of just input()?
A. To prevent syntax errors.
B. To convert the user's input from a string to an integer.
C. To speed up the program's execution.
D. To format the output as a number.
Correct Answer: B. To convert the user's input from a string to an integer.
Rationale: The input() function always returns data as a string. Wrapping it
with int() converts that string into an integer, allowing it to be used in mathematical
operations.
3. Which of the following is a valid variable name in Python?
A. 2nd_place
B. my-var
C. _total
D. global
Correct Answer: C. _total
Rationale: Variable names must start with a letter or an underscore. They cannot
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

Partial preview of the text

Download WGU D335 Python OA Exam 450+ Practice Questions with Verified Solutions, Code Snippets, and more Exams Computer Science in PDF only on Docsity!

WGU D335 Python OA Exam 45 0+ Practice Questions

with Verified Solutions, Code Snippets, Error Types,

and Test-Taking Strategies for Objective Assessment

Success

part 1: Fundamentals, Variables, and Data Types

1. What is the data type of the variable x after the following assignment? x = 5 / 2 A. int B. float C. string D. list Correct Answer: B. float Rationale: The division operator (/) in Python always returns a floating-point number, even if the result is a whole number. Therefore, 5 / 2 evaluates to 2.5, which is a float. 2. What is the purpose of using int(input()) instead of just input()? A. To prevent syntax errors. B. To convert the user's input from a string to an integer. C. To speed up the program's execution. D. To format the output as a number. Correct Answer: B. To convert the user's input from a string to an integer. Rationale: The input() function always returns data as a string. Wrapping it with int() converts that string into an integer, allowing it to be used in mathematical operations. 3. Which of the following is a valid variable name in Python? A. 2nd_place B. my-var C. _total D. global Correct Answer: C. _total Rationale: Variable names must start with a letter or an underscore. They cannot

start with a number (A) or contain hyphens (B). global is a reserved keyword in Python and cannot be used as a variable name (D).

4. Which of the following is NOT a Python data type? A. int B. string C. character D. float Correct Answer: C. character Rationale: Unlike languages such as C or Java, Python does not have a dedicated "character" data type. A single character is simply a string of length 1. 5. What will the following code output? x = "10" y = "20" print(x + y) A. 30 B. 1020 C. TypeError D. 10 20 Correct Answer: B. 1020 Rationale: The + operator acts as a concatenation operator when used with strings. Since both x and y are strings, they are joined together to form "1020". **Part 2: Control Flow and Operators

  1. What is the output of the following code?** print(3 + 4 * 2) A. 14 B. 11 C. 24 D. Error Correct Answer: B. 11 Rationale: According to Python's operator precedence, multiplication (*) has a higher precedence than addition (+). Therefore, 4 * 2 is evaluated first (8), and then 3
  • 8 results in 11. 7. Which operator is used for integer (floor) division in Python? A. / B. // C. % D. \

C. 4

D. 5

Correct Answer: D. 5 Rationale: Negative indexing accesses elements from the end of a list. An index of - 1 always refers to the last element.

12. What is the output of the following code? x = [1, 2, 3, 4, 5] print(x[1:4]) A. [1, 2, 3] B. [2, 3, 4] C. [1, 2, 3, 4] D. [2, 3, 4, 5] Correct Answer: B. [2, 3, 4] Rationale: Python list slicing x[start:stop] includes the element at index start up to but NOT including the element at index stop. So x[1:4] yields indices 1, 2, and 3, which correspond to the values 2, 3, and 4. 13. Which slicing operation extracts the last three characters of a string s? A. s[3:] B. s[:3] C. s[-3:] D. s[:-3] Correct Answer: C. s[-3:] Rationale: Negative indexing in Python counts from the end of the string. s[- 3:] starts at the third-to-last character and goes to the end, extracting the last three characters. **Part 4: Functions, Modules, and Error Handling

  1. Which of the following correctly defines a function in Python that returns the square of a number?** A. function square(n): return n * n B. def square(n): return n ** 2 C. def square(n) { return n * n; } D. define square(n): return n ^ 2 Correct Answer: B. def square(n): return n ** 2 Rationale: Python uses the def keyword to define functions. The exponentiation operator is . The caret ^ is bitwise XOR, not exponentiation. 15. Which statement correctly imports a module named pigAge?** A. import pigage

B. include pigAge C. from pigAge import * D. import pigAge Correct Answer: D. import pigAge Rationale: Python module names are case-sensitive, so pigAge must be imported exactly as named. The import pigAge statement imports the module correctly.

16. Which keyword is used to handle exceptions in Python? A. catch B. handle C. except D. error Correct Answer: C. except Rationale: Python uses try and except blocks for exception handling. The except keyword specifies how the program should respond when an error occurs. 17. Which exception is raised when you try to divide by zero in Python? A. ValueError B. TypeError C. ZeroDivisionError D. ArithmeticError Correct Answer: C. ZeroDivisionError Rationale: Python raises a ZeroDivisionError specifically for division or modulo by zero. 18. What will this code print? try: print(10 / 0) except ZeroDivisionError: print('Cannot divide by zero') finally: print('Done') A. Cannot divide by zero B. Cannot divide by zero\nDone C. Done D. Error Correct Answer: B. Cannot divide by zero\nDone Rationale: The ZeroDivisionError is caught by the except block, printing the error message. The finally block ALWAYS executes regardless of whether an exception occurred, so 'Done' is printed afterward.

C. empty = [] D. empty = () Correct Answer: B. empty = set() Rationale: Using curly braces {} creates an empty dictionary, not a set. To create an empty set, you must use the set() constructor.

23. What will this code output? my_dict = {"a": 1, "b": 2, "c": 3} for key in my_dict: print(key, end=" ") A. a b c B. 1 2 3 C. ("a",1) ("b",2) ("c",3) D. Error Correct Answer: A. a b c Rationale: Iterating directly over a dictionary with a for loop iterates through its keys by default. To access values, you would use my_dict[key] or the .values() method. 24. What is a key characteristic of elements in a set? A. They are ordered. B. They are mutable. C. They are unique. D. They are indexed. Correct Answer: C. They are unique. Rationale: Sets in Python are unordered collections of unique elements. Duplicate values are automatically removed when a set is created or modified. **Part 7: File Handling

  1. Which mode opens a file for writing, but raises an error if the file already exists?** A. "w" B. "a" C. "x" D. "w+" Correct Answer: C. "x" Rationale: The "x" mode (exclusive creation) creates a new file and opens it for writing. If the file already exists, the operation fails with a FileExistsError, preventing accidental overwrites. 26. What is the correct way to open a file for reading in Python? A. file = open("data.txt", "r")

B. file = open("data.txt", read) C. file = read("data.txt") D. file = open_read("data.txt") Correct Answer: A. file = open("data.txt", "r") Rationale: The built-in open() function takes the filename and the mode as arguments. "r" is the mode for reading, and it's also the default mode if no mode is specified.

27. What does the following code do? with open("log.txt", "r") as file: content = file.read() A. It reads the entire file into memory as a string. B. It reads the file line by line. C. It opens the file but doesn't automatically close it. D. It raises an error because the syntax is incorrect. Correct Answer: A. It reads the entire file into memory as a string. Rationale: The .read() method reads the entire contents of a file and returns it as a single string. The with statement ensures the file is properly closed after the block executes. 28. Which method reads a file and returns a list of strings, where each string is a line? A. .read() B. .readlines() C. .readline() D. .splitlines() Correct Answer: B. .readlines() Rationale: The .readlines() method reads all lines from a file and returns them as a list, with each line (including the newline character \n) as a separate element. **Part 8: Advanced Functions and Scope

  1. What is the output of the following code?** x = 10 def my_func(): x = 5 print(x, end=" ") my_func() print(x) A. 5 5 B. 10 10 C. 5 10 D. 10 5

Correct Answer: A. 8 Rationale: The function is called with one positional argument (1 for a) and one keyword argument (c=5). Since b is not provided, it uses its default value of 2. The calculation is 1 + 2 + 5 = 8.

34. Which statement about *args and **kwargs is TRUE? A. *args is used to pass a variable number of keyword arguments. B. **kwargs is used to pass a variable number of positional arguments. C. *args collects extra positional arguments into a tuple. D. They can only be used in functions that don't return a value. Correct Answer: C. *args collects extra positional arguments into a tuple. Rationale: In function definitions, *args allows you to pass a variable number of positional arguments, which are then accessible as a tuple inside the function. **kwargs collects keyword arguments into a dictionary. **Part 9: Common Built-in Functions and Methods

  1. What does the** len() function return when applied to a string? A. The memory size of the string in bytes. B. The number of characters in the string. C. The index of the last character. D. The number of words in the string. Correct Answer: B. The number of characters in the string. Rationale: The len() function returns the number of items in an object. For a string, it returns the number of characters, including spaces and special characters. 36. What is the output of type(3.14)? A. B. C. D. Correct Answer: B. Rationale: In Python, numbers with decimal points are of type float. Python doesn't have a separate double type; float is a double-precision floating-point number. 37. What does the .append() method do to a list? A. It adds an element at the beginning of the list. B. It adds an element at the end of the list. C. It removes the last element from the list. D. It extends the list with another list.

Correct Answer: B. It adds an element at the end of the list. Rationale: .append() adds its argument as a single element to the end of a list. If the argument is a list, the entire list is added as one element (nested list), not merged.

38. How do you check if a key "name" exists in a dictionary person? A. person.exists("name") B. "name" in person C. person.has_key("name") D. person.contains("name") Correct Answer: B. "name" in person Rationale: The in operator is the Pythonic way to check for key existence in a dictionary. It returns True if the key exists, False otherwise. 39. What is the result of bool([])? A. True B. False C. None D. Error Correct Answer: B. False Rationale: In Python, empty sequences and collections (like empty lists [], empty strings "", empty tuples (), empty dictionaries {}, and empty sets set()) evaluate to False in a boolean context. Non-empty collections evaluate to True. 40. What does the .split() method return when called on a string without any arguments? A. A list of characters. B. A list of words, splitting on any whitespace. C. A tuple of words. D. The original string unchanged. Correct Answer: B. A list of words, splitting on any whitespace. Rationale: The .split() method, with no arguments, splits a string on any whitespace (spaces, tabs, newlines) and returns a list of the resulting substrings. Multiple consecutive whitespace characters are treated as a single delimiter. **part 10: Advanced Data Structures and Operations

  1. What will be the output of the following code?** list1 = [1, 2, 3] list2 = list list2.append(4) print(list1)

B. Combines two or more iterables into tuples. C. Sorts multiple lists simultaneously. D. Removes duplicate elements from lists. Correct Answer: B. Combines two or more iterables into tuples. Rationale: zip() takes multiple iterables and returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables.

46. What will this code output? names = ["Alice", "Bob", "Charlie"] scores = [85, 92, 78] for name, score in zip(names, scores): print(f"{name}: {score}") A. Alice Bob Charlie: 85 92 78 B. A list of tuples C. Alice: 85 Bob: 92 Charlie: 78 (each on a new line) D. Error Correct Answer: C. Alice: 85 Bob: 92 Charlie: 78 (each on a new line) Rationale: zip(names, scores) pairs each name with its corresponding score. The loop unpacks each tuple into name and score variables, then prints them in the formatted string. **Part 11: Lambda Functions and Map/Filter

  1. What is a lambda function in Python?** A. A named function defined with def B. An anonymous, single-expression function C. A function that can only be used once D. A built-in function for mathematical operations Correct Answer: B. An anonymous, single-expression function Rationale: Lambda functions are small, anonymous functions defined with the lambda keyword. They can take any number of arguments but can only contain a single expression, which is evaluated and returned. 48. What does the following code return? list(map(lambda x: x**2, [1, 2, 3, 4])) A. [1, 4, 9, 16] B. [2, 4, 6, 8] C. [1, 2, 3, 4] D. Error Correct Answer: A. [1, 4, 9, 16] Rationale: map() applies the lambda function to each element of the list. The lambda

function lambda x: x**2 squares its input, resulting in a new map object which is converted to a list containing [1, 4, 9, 16].

49. What will filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6]) return? A. [1, 3, 5] B. [2, 4, 6] C. [True, False, True, False, True, False] D. Error Correct Answer: B. [2, 4, 6] Rationale: filter() keeps only elements for which the function returns True. The lambda checks if a number is even (x % 2 == 0), so only the even numbers are returned. **Part 12: String Formatting and f-strings

  1. Which of the following is a valid f-string?** A. f"Hello, {name}!" B. "fHello, {name}!" C. f(Hello, {name}!) D. F"Hello, name!" Correct Answer: A. f"Hello, {name}!" Rationale: f-strings (formatted string literals) are created by prefixing a string with f or F. Variables or expressions to be evaluated are placed inside curly braces {}. 51. What is the output? name = "World" print(f"Hello, {name.upper()}!") A. Hello, World! B. Hello, WORLD! C. Hello, {name.upper()}! D. Error Correct Answer: B. Hello, WORLD! Rationale: Inside an f-string, you can call methods on variables. name.upper() converts the string to uppercase before it's inserted into the string. 52. How would you format a float to show only 2 decimal places in an f-string? A. f"{pi:.2}" B. f"{pi:2f}" C. f"{pi:.2f}" D. f"{pi:2}"

Part 14: Modules and Packages

56. Which of the following is a valid way to import only the sqrt function from the math module? A. import math.sqrt B. from math import sqrt C. import sqrt from math D. include math.sqrt Correct Answer: B. from math import sqrt Rationale: The from module import item syntax allows you to import specific functions or attributes from a module directly into your namespace. 57. After executing from math import * , what can you do? A. Use any function from the math module without the math. prefix. B. Only use functions that start with an underscore. C. Nothing; this syntax is invalid. D. Use math functions only within a with block. Correct Answer: A. Use any function from the math module without the math. prefix. Rationale: The * imports all public names from a module into the current namespace. While convenient, it's generally discouraged because it can lead to naming conflicts and makes code less readable. 58. What is the name variable in a Python script? A. The name of the script file. B. The name of the currently running function. C. A special variable set to "main" when the script is run directly. D. The name of the Python interpreter. Correct Answer: C. A special variable set to "main" when the script is run directly. Rationale: name is a built-in variable. When a Python file is executed directly, name is set to "main". When it's imported as a module, name is set to the module's name. This is commonly used in the if name == "main": block to separate executable code from importable code. **Part 15: Tricky Scenarios and Edge Cases

  1. What is the output?** a = [1, 2, 3] b = a a = [4, 5, 6] print(b) A. [1, 2, 3]

B. [4, 5, 6]

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

D. Error Correct Answer: A. [1, 2, 3] Rationale: This is different from question 41. Here, a is reassigned to a completely new list object. The variable b still points to the original list [1, 2, 3]. Reassignment changes what a references, but doesn't affect b.

60. What will this code print? def func(x, y=[]): y.append(x) return y print(func(1)) print(func(2)) print(func(3)) A. [1] [2] [3] B. [1] [1, 2] [1, 2, 3] C. Error D. [1] [1] [1] Correct Answer: B. [1] [1, 2] [1, 2, 3] Rationale: This demonstrates a common pitfall: default argument values are evaluated only once when the function is defined, not each time the function is called. The default list y=[] is the same list object across all function calls. Each call appends to the same list, causing it to grow. 61. What is the output of bool(0.0)? A. True B. False C. None D. Error Correct Answer: B. False Rationale: In Python, zero values (integer 0, float 0.0, complex 0j) are considered False in a boolean context. Any non-zero number is True. 62. What will print("Hello", "World", sep="-", end="!") output? A. Hello-World! B. Hello-World! C. Hello-World! (with a newline) D. Hello World! Correct Answer: A or B (both represent the same output) - "Hello-World!" Rationale: The sep parameter changes the separator between printed items from a space to a hyphen. The end parameter changes the ending from a newline (\n) to an exclamation mark. The output is Hello-World! without a trailing newline.

the file when the block exits, even if an exception occurs. This is the recommended way to handle files.

67. What will this code print? x = 5 def change_x(): global x x = 10 change_x() print(x) A. 5 B. 10 C. None D. Error Correct Answer: B. 10 Rationale: The global keyword inside the function tells Python to use the global variable x rather than creating a local one. The function modifies the global x from 5 to 10. 68. What is the difference between .remove() and .pop() for lists? A. They are the same method. B. .remove() deletes by index, .pop() deletes by value. C. .remove() deletes by value, .pop() deletes by index and returns the value. D. .remove() returns the removed value, .pop() does not. Correct Answer: C. .remove() deletes by value, .pop() deletes by index and returns the value. Rationale: list.remove(x) removes the first occurrence of the value x. list.pop(i) removes the item at index i and returns it. If no index is provided to pop(), it removes and returns the last item. 69. What will print(not True and False or True) output? A. True B. False C. None D. Error Correct Answer: A. True Rationale: Follow operator precedence: not is evaluated first: not True is False. So the expression becomes False and False or True. and is evaluated next: False and False is False. Finally, False or True evaluates to True. 70. What does the .join() method do? A. Splits a string into a list. B. Joins list elements into a string using a separator.

C. Joins two strings together. D. Concatenates multiple lists. Correct Answer: B. Joins list elements into a string using a separator. Rationale: The string .join(iterable) method takes an iterable of strings and concatenates them, using the string it's called on as the separator. For example: "- ".join(["a", "b", "c"]) returns "a-b-c" Part 16: Advanced Function Concepts and Decorators

71. What is a closure in Python? A. A function that has access to variables from its enclosing scope even after the outer function has finished executing B. A method that closes a file automatically C. A way to prevent variable modification D. A special type of loop Correct Answer: A. A function that has access to variables from its enclosing scope even after the outer function has finished executing Rationale: A closure occurs when a nested function references variables from its enclosing scope. The nested function "closes over" those variables, preserving them even after the outer function returns. This is a fundamental concept in functional programming. 72. What will this code output? python def outer(x): def inner(y): return x + y return inner add_five = outer( 5 ) print(add_five( 3 )) A. 5 B. 3 C. 8 D. Error Correct Answer: C. 8 Rationale: This is a closure. outer(5) returns the inner function with x bound to 5.