


























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!



























Course Title: Python for IT Automation (D522) Institution: Western Governors University (WGU) Exam Type: Objective Assessment (OA) – Practice Version Total Questions: 120 Time Limit: 180 minutes (3 hours) Domains Covered: Domain Description Approximate Coverage Domain I Python Fundamentals – Syntax, Variables, Data Types, Operators, and Control Flow 15% Domain II Data Structures – Lists, Tuples, Dictionaries, Sets, and String Manipulation 20% Domain III Functions and Modular Programming – Definition, Parameters, Scope, and Recursion 10% Domain IV File Handling and I/O Operations – Reading, Writing, and Managing Files 10% Domain V Automation Techniques – Scripting, Scheduling, and Automation Libraries 15% Domain VI Error Handling and Debugging – Exceptions, Logging, and Troubleshooting 10% Domain VII APIs and Data Serialization – Working with JSON, REST APIs, and Web Interactions 10%
Domain Description Approximate Coverage Domain VIII Regular Expressions and Text Processing – Pattern Matching and Data Extraction 10% Scoring: Each question is worth one point. A passing score is 80% (96 correct answers). Instructions: Select the best answer for each multiple-choice question. The correct answer is indicated with ✓ and accompanied by a detailed rationale.
Question 1: What does Python syntax refer to? A. The runtime environment for executing Python code B. The set of rules that dictate the combinations of symbols and keywords that form valid Python programs ✓ C. The process of converting Python code into machine language D. The standard library of built-in modules included with Python Rationale: Python syntax encompasses the grammar rules that define how symbols, keywords, and operators can be combined to create valid Python programs. Syntax rules govern everything from variable naming conventions to statement structure, ensuring the interpreter can correctly parse and execute the code. Question 2: What is the primary purpose of indentation in Python? A. To enhance visual appearance without affecting execution B. To define blocks of code ✓ C. To separate different modules D. To indicate the end of a program Rationale: Unlike many other programming languages that use braces {} to define code blocks, Python uses indentation (spaces or tabs at the start of a line) to define blocks of code. Consistent indentation is required for structures like if statements, loops, and function definitions, making code blocks visually distinct and enforcing a standard coding style. Question 3: Which of the following best describes Python as a programming language? A. A compiled language with static typing B. An interpreted language known for its simplicity, readability, and versatility ✓
Rationale: The + operator performs string concatenation when used with string operands, joining them end-to-end. The expression "Hello" + " " + "World" creates the string "Hello World". Attempting to concatenate a string with a non-string (e.g., "Hello" + 5) would raise a TypeError. Question 8: Which of the following correctly creates a multi-line comment in Python? A. /* This is a comment */ B. // This is a comment C. """This is a multi-line comment""" ✓ D. Rationale: Python does not have native multi-line comment syntax, but triple-quoted strings (""" ... """ or ''' ... ''') that are not assigned to a variable are ignored by the interpreter and effectively serve as multi-line comments. For single-line comments, the # symbol is used. Question 9: What is the purpose of the format() method in Python? A. To convert numbers to different bases B. To enhance output formatting by embedding variables in strings ✓ C. To format dates and times D. To resize image files Rationale: The format() method provides a flexible way to format strings by inserting values into placeholders defined by curly braces {}. While f-strings (formatted string literals) have become the preferred approach for many developers due to their readability, format() remains a powerful tool for complex formatting scenarios. Question 10: What is a variable in Python? A. A fixed value that cannot change during program execution B. A named reference to a value stored in memory ✓ C. A function that returns multiple values D. A constant that is automatically typed Rationale: A variable in Python is a named identifier that references a value stored in memory. Variables are created simply by assigning a value to a name using the = operator. Python variables are dynamically typed, meaning a variable can reference values of different types during program execution. Question 11: Which of the following are the basic built-in data types in Python? A. Integer, Float, String, Boolean, and NoneType ✓ B. Array, Structure, Union, and Pointer C. Byte, Character, Long, and Double D. List, Map, Set, and Queue Rationale: Python's core built-in data types include integers (int) for whole numbers, floating-point numbers (float) for decimals, strings (str) for text sequences, booleans
(bool) for truth values (True/False), and NoneType (the special None value) indicating absence of a value. Question 12: What is the primary use of whitespace in Python? A. To separate keywords from variables B. To define the structure and hierarchy of the code ✓ C. To enhance execution speed D. To mark the end of statements Rationale: In Python, whitespace—particularly indentation—is syntactically significant and defines the structure and hierarchy of code. Control flow statements, loops, functions, and classes use indentation to denote their code blocks, eliminating the need for explicit block delimiters like braces. Question 13: What is the result of 10 // 3 in Python? A. 3.333... B. 3 ✓ C. 3. D. 4 Rationale: The floor division operator // divides the left operand by the right operand and returns the largest integer less than or equal to the result. Since 10 / 3 = 3.333..., the floor is 3. This operation always returns an integer, regardless of whether the operands are integers or floats. Question 14: What does the type() function do in Python? A. Converts one data type to another B. Checks an object's data type ✓ C. Creates a new variable D. Allocates memory for an object Rationale: The built-in type() function returns the data type of an object passed as an argument. For example, type(42) returns , indicating the object is an integer. This function is essential for debugging and ensuring type compatibility in dynamic code. Question 15: Which function converts a numeric value to a string? A. int() B. float() C. str() ✓ D. char() Rationale: The str() function converts its argument to a string representation. For example, str(123) returns the string "123". This conversion is often necessary when concatenating numeric values with strings or when preparing data for output to files or network streams.
Question 20: What is the result of not (5 > 3)? A. True B. False ✓ C. 5 > 3 D. TypeError Rationale: The not operator negates the boolean value of its operand. The expression 5 > 3 evaluates to True, so not True returns False. The not operator is commonly used to invert conditions in if statements or loop control. Question 21: What happens when you try to concatenate a string with an integer using the + operator? A. The integer is automatically converted to a string B. A TypeError is raised ✓ C. The integer is ignored D. The operation succeeds with a warning Rationale: In Python, the + operator is overloaded for both numeric addition and string concatenation, but it cannot be used between different types. Attempting to concatenate a string with an integer (e.g., "Value: " + 42) raises a TypeError. Use str() conversion or f-strings (e.g., f"Value: {42}") instead. Question 22: Which escape sequence represents a newline character? A. \t B. \n ✓ C. \r D. \b Rationale: The escape sequence \n represents the newline character, which moves the cursor to the beginning of the next line when output. This escape sequence is essential for creating multi-line strings and formatted text output. The \t sequence represents a tab character, while \r represents a carriage return. Question 23: How can you include a double quote character inside a double-quoted string? A. " (It will work automatically) B. " ✓ C. \" D. "" Rationale: To include a double quote character within a string delimited by double quotes, you must escape it using a backslash: ". Alternatively, you can delimit the string with single quotes ('This "quote" is fine') to avoid escaping. Escape sequences provide a way to include special characters that would otherwise be interpreted as part of the string syntax.
Question 24: Which of the following is a valid variable name in Python? A. 2var B. my-variable C. _my_variable ✓ D. class Rationale: Variable names in Python must start with a letter or underscore, followed by letters, digits, or underscores. The underscore is the only special character allowed. 2var is invalid because it starts with a digit. my-variable contains a hyphen, which is not allowed. class is a reserved keyword. _my_variable follows all naming rules. Question 25: What does the float() function do when applied to a string containing a decimal number? A. Converts the string to a floating-point number ✓ B. Converts the string to an integer C. Returns the string unchanged D. Raises a ValueError Rationale: The float() function converts its argument to a floating-point number. When applied to a string like "3.14", it returns 3.14. If the string cannot be converted to a valid floating-point number (e.g., float("hello")), a ValueError is raised. This function is essential for processing numeric input from files or user input. Question 26: What is the purpose of using comments for Preventing Execution? A. To document the code for other programmers B. To temporarily disable lines or blocks of code during debugging ✓ C. To mark the end of a program D. To separate different sections of a module Rationale: Comments are primarily used to add explanatory notes in code, but they also serve the practical purpose of temporarily disabling lines or blocks of code during debugging and testing. By commenting out problematic code, developers can isolate issues and test alternative implementations without deleting code. Question 27: Which operator is used for exponentiation in Python? A. ^ B. ** ✓ C. pow() D. exp() Rationale: The ** operator performs exponentiation (power) in Python. For example, 2 ** 3 calculates 2 raised to the third power, resulting in 8. While the pow() built-in function provides similar functionality, the ** operator is the standard arithmetic operator for exponentiation.
C. They only store numeric data D. They consume less memory than lists Rationale: Dictionaries store data as key–value pairs, enabling meaningful and readable data labeling. Values are accessed using descriptive keys rather than numeric indexes, making dictionaries ideal for representing relationships such as device names and IP addresses. Their structure improves code clarity and maintainability in automation tasks. Question 32: What is the difference between remove() and discard() in a Python set? A. They behave identically B. remove() raises an error if the item is missing ✓ C. discard() raises an error D. Only discard() removes items Rationale: The remove() method raises a KeyError if the specified element does not exist in the set. In contrast, discard() silently fails (does nothing) when the item is missing. This makes discard() safer when membership is uncertain, while remove() is appropriate when the element is expected to exist. Question 33: Which of the following correctly creates a Python set? A. set = [1, 2, 3] B. set = (1, 2, 3) C. set = {1, 2, 3} ✓ D. set = "1,2,3" Rationale: A Python set is created by placing a comma-separated sequence of items inside curly braces {} or by using the set() constructor. Unlike lists (created with []) and tuples (created with ()), sets contain unordered, unique elements and support mathematical set operations like union and intersection. Question 34: Which property is true about Python sets? A. Sets allow duplicate values B. Sets are indexed C. Sets are unordered and do not allow duplicate values ✓ D. Sets maintain insertion order Rationale: Python sets are unordered collections of unique items. They do not allow duplicate values, and elements cannot be accessed by index because the order is not guaranteed. Sets are primarily used for membership testing and mathematical set operations where the existence of an element matters more than order or frequency. Question 35: How can you add an item to an existing Python set? A. set.append(item) B. set.insert(item) C. set.add(item) ✓ D. set.extend(item)
Rationale: The add() method adds a single element to a set. If the element already exists in the set, the operation has no effect because sets do not allow duplicates. The update() method can be used to add multiple elements at once from another iterable. Lists use append(), but sets use add(). Question 36: Which Python code snippet correctly demonstrates the creation of a dictionary with key-value pairs? A. dict = {1, 2, 3, 4} B. dict = {"name": "server1", "ip": "192.168.1.1"} ✓ C. dict = ["name", "server1", "ip", "192.168.1.1"] D. dict = ("name", "server1", "ip", "192.168.1.1") Rationale: Dictionaries in Python are created using curly braces {} with key-value pairs separated by colons :, and pairs separated by commas. Each key must be immutable (typically strings or numbers) and unique within the dictionary. The example {"name": "server1", "ip": "192.168.1.1"} creates a dictionary with two key-value pairs. Question 37: What is a Python list? A. An immutable sequence of elements B. An ordered, mutable collection that can contain mixed data types ✓ C. A key-value mapping structure D. An unordered collection of unique items Rationale: A list in Python is an ordered, mutable (modifiable) sequence that can contain elements of different data types. Lists are defined using square brackets [] and support operations such as indexing, slicing, appending, and inserting. Unlike tuples, lists can be changed after creation. Question 38: How can you access the last element of a list named my_list? A. my_list[0] B. my_list[end] C. my_list[-1] ✓ D. my_list.last() Rationale: Python supports negative indexing, where - 1 refers to the last element, - 2 refers to the second-to-last, and so on. This feature allows convenient access to elements from the end of a sequence without needing to know the list's length. For example, my_list[-1] returns the final element of my_list. Question 39: Which method adds an element to the end of a Python list? A. list.add(item) B. list.insert(item) C. list.append(item) ✓ D. list.extend(item)
Rationale: The built-in len() function returns the number of items in a container (list, tuple, string, dictionary, set). For the list [10, 20, 30, 40], which contains four elements, len() returns 4. This function is essential for iterating over sequences and validating data sizes. Question 44: How do you check if a key exists in a dictionary without causing an error? A. dict.has_key(key) B. key in dict ✓ C. dict.exists(key) D. dict.contains(key) Rationale: The membership operator in can be used to test whether a key exists in a dictionary. For example, if 'name' in my_dict: returns True if the key 'name' is present. This approach avoids raising a KeyError and is the preferred Pythonic way to check key existence before access. Question 45: What is the result of "Hello, World".split(",")? A. ['Hello', ' World'] ✓ B. 'Hello, World' C. ['Hello, World'] D. ('Hello', 'World') Rationale: The split() method divides a string into a list of substrings based on a specified delimiter. When called with "," as the delimiter, the string "Hello, World" is split into two parts: everything before the comma ("Hello") and everything after the comma (" World"), returned as a list ['Hello', ' World']. The space before "World" is preserved. Question 46: Which method removes and returns the last element from a list? A. list.remove() B. list.pop() ✓ C. list.delete() D. list.discard() Rationale: The pop() method removes and returns the last element of a list when called without an argument. With an optional index argument, pop(i) removes and returns the element at that index. This method is useful for stack-like operations (LIFO). The remove() method removes the first occurrence of a specified value, not by index. Question 47: What is the difference between a list and a tuple? A. Lists are immutable, tuples are mutable B. Lists are mutable, tuples are immutable ✓ C. Lists use parentheses, tuples use brackets D. Lists cannot be changed after creation
Rationale: The primary difference between lists and tuples is mutability: lists are mutable (can be modified after creation) while tuples are immutable (cannot be changed). Lists are defined with square brackets [], while tuples use parentheses (). This immutability makes tuples suitable for data that should remain constant and allows them to be used as dictionary keys. Question 48: How do you merge two dictionaries in Python? A. dict1 + dict B. dict1.update(dict2) ✓ C. dict1.append(dict2) D. dict1.extend(dict2) Rationale: The update() method merges key-value pairs from one dictionary into another. If keys overlap, values from the second dictionary overwrite those in the first. In Python 3.9+, the union operator | and the |= augmented assignment operator can also be used for dictionary merging. This operation is common when combining configuration settings. Question 49: What is the output of list(range(5))? A. [0, 1, 2, 3, 4] ✓ B. [1, 2, 3, 4, 5] C. [0, 1, 2, 3, 4, 5] D. range(0, 5) Rationale: The range() function generates a sequence of numbers. range(5) produces the numbers 0, 1, 2, 3, 4 (starting at 0 and stopping before 5). When passed to list(), these numbers are converted into a list. This is a common pattern for creating numeric lists in Python, especially useful in automation loops. Question 50: What does the string method upper() do? A. Converts all characters in a string to uppercase ✓ B. Converts all characters to lowercase C. Capitalizes the first character D. Reverses the string Rationale: The upper() method returns a new string with all alphabetic characters converted to uppercase. Original strings are immutable, so the method creates and returns a new string rather than modifying the original. This method is frequently used in IT automation for case-insensitive comparisons and data normalization. Question 51: Which list method sorts the list in place? A. sorted(list) B. list.sort() ✓ C. list.order() D. list.sorted()
Rationale: The strip() method removes leading and trailing whitespace (spaces, tabs, newlines) from a string. In this example, the leading and trailing spaces are removed, returning "Hello". The lstrip() method removes only leading whitespace, and rstrip() removes only trailing whitespace. This is essential for cleaning user input and file data. Question 56: Which of the following creates an empty dictionary? A. {} ✓ B. [] C. () D. set() Rationale: Curly braces {} create an empty dictionary. Empty lists are created with [], empty tuples with (), and empty sets require the set() constructor because {} is reserved for dictionaries. This distinction is important when choosing the appropriate data structure for different automation tasks. Question 57: What is the result of "Hello" * 3? A. "HelloHelloHello" ✓ B. "Hello3" C. TypeError D. "Hello Hello Hello" Rationale: The multiplication operator * when used with a string and an integer repeats the string the specified number of times. "Hello" * 3 returns "HelloHelloHello". This operator can be useful for generating repeated patterns, creating separators (e.g., "-" * 40 ), or formatting output in automation scripts. Question 58: How do you create a shallow copy of a list? A. new_list = old_list B. new_list = old_list.copy() ✓ C. new_list = list(old_list) (also valid) D. Both B and C are correct ✓ Rationale: Multiple methods create shallow copies of a list: the copy() method (old_list.copy()), the list() constructor (list(old_list)), and slicing (old_list[:]). A shallow copy creates a new list object with references to the same elements as the original. For nested structures, changes to mutable elements may affect both lists, requiring deepcopy() from the copy module. Question 59: What does the count() method do for a list? A. Counts the total number of elements in the list B. Returns the number of occurrences of a specified value ✓ C. Counts the number of unique elements D. Returns the index of a specified value
Rationale: The count() method returns the number of times a specified element appears in a list. For example, [1, 2, 2, 3, 2].count(2) returns 3. This method is distinct from len(), which returns the total number of elements. count() is useful for frequency analysis and data validation in automation scripts. Question 60: What is the output of list("Python")? A. "Python" B. ['P', 'y', 't', 'h', 'o', 'n'] ✓ C. ('P', 'y', 't', 'h', 'o', 'n') D. {'P', 'y', 't', 'h', 'o', 'n'} Rationale: The list() constructor can convert any iterable into a list. When applied to a string, it returns a list containing each character of the string as a separate element. This is useful for processing strings character by character in automation scripts where indexing or mutable operations on individual characters are needed.
Question 61: What is a function in Python? A. A built-in operator for mathematical calculations B. A named block of reusable code that performs a specific task ✓ C. A variable that stores multiple values D. An error-handling mechanism Rationale: A function is a named, reusable block of code designed to perform a specific task. Functions enhance code modularity, readability, and reusability by encapsulating logic that can be called multiple times throughout a program. They can accept input parameters and optionally return results. Question 62: What keyword is used to define a function in Python? A. function B. def ✓ C. func D. define Rationale: The def keyword is used to define a function in Python, followed by the function name, parentheses containing optional parameters, and a colon. The function body is indented beneath the definition. This syntax is fundamental to Python's function definition mechanism. Question 63: What are parameters in a function? A. Values returned by the function
C. A value that changes each time the function runs D. A value that cannot be overridden Rationale: Default parameter values are specified in the function definition using the = operator (e.g., def greet(name="User")). If the caller does not provide an argument for that parameter, the default value is used. This feature makes some parameters optional and allows functions to have flexible calling signatures. Question 68: What are arbitrary arguments (args) used for? A. To force the function to accept exactly one argument B. To allow a function to accept any number of positional arguments ✓ C. To pass keyword arguments D. To return multiple values Rationale: The args parameter (the asterisk is what matters; args is conventional) allows a function to accept any number of positional arguments, which are collected into a tuple. This is useful when the number of inputs is unknown or variable, such as summing an arbitrary number of numbers or processing a variable-length list of items. Question 69: What are arbitrary keyword arguments (kwargs) used for? A. To accept any number of keyword arguments as a dictionary ✓ B. To force keyword-only parameters C. To define default values D. To return a dictionary Rationale: The **kwargs parameter (double asterisk) allows a function to accept any number of keyword arguments, which are collected into a dictionary where keys are the argument names and values are the argument values. This is useful for handling configuration options or passing through arguments to other functions. Question 70: What is function recursion? A. A function that calls another function B. A process in which a function calls itself as a subroutine ✓ C. A function with multiple return statements D. A function that cannot be reused Rationale: Recursion occurs when a function calls itself, either directly or indirectly. Each recursive call typically works on a smaller or simpler version of the problem, with a base case that terminates the recursion. Recursion is particularly elegant for problems with recursive structures like tree traversal or factorial calculation. Question 71: What is variable scope in Python? A. The physical location of the variable in memory B. The region of a program where a variable is accessible ✓ C. The data type of the variable D. The value stored in the variable
Rationale: Scope defines the region of a program where a variable name is valid and can be referenced. Python has local scope (within a function), enclosing scope (for nested functions), global scope (module level), and built-in scope. Understanding scope is essential for avoiding unintended variable conflicts and debugging name resolution issues. Question 72: How do you make a variable global inside a function? A. Define it outside the function B. Use the global keyword ✓ C. Use the nonlocal keyword D. Assign it with an asterisk Rationale: The global keyword allows a function to modify a variable defined in the global (module) scope rather than creating a new local variable. Without global, assignment to a name within a function creates a local variable by default. This keyword should be used sparingly as it can make code harder to understand and maintain. Question 73: What is a lambda function? A. A named function defined with def B. A small anonymous function defined with the lambda keyword ✓ C. A recursive function D. A function that returns multiple values Rationale: Lambda functions are small, anonymous functions defined using the lambda keyword. They can contain only a single expression (not statements) and implicitly return the result of that expression. Lambdas are typically used for short, throwaway functions in contexts like map(), filter(), and sorted() where a full function definition would be verbose. Question 74: What is the purpose of the help() function in Python? A. To execute help documentation for modules, functions, classes, and methods ✓ B. To fix errors in the code C. To optimize program performance D. To create user manuals Rationale: The built-in help() function provides interactive documentation for any Python object, including modules, functions, classes, and methods. When the D exam references modules like json or socket, using help(json) or help(json.dumps) provides comprehensive information about their functionality, parameters, and usage examples. Question 75: What does the following function definition do? def calculate(x, y=10): return x + y A. Calculates the sum of x and y, where y defaults to 10 if not provided ✓ B. Calculates the product of x and y