Escrito por estudiantes que aprobaron Inmediatamente disponible después del pago Leer en línea o como PDF ¿Documento equivocado? Cámbialo gratis 4,6 TrustPilot
logo-home
Document preview thumbnail
Vista previa 4 fuera de 49 páginas
Examen

WGU D522 Objective Assessment Exam (New 2026/ 2027 Update) Python for IT Automation | Questions & Answers| Grade A| 100% Correct (Verified Answers)

Document preview thumbnail
Vista previa 4 fuera de 49 páginas

WGU D522 Objective Assessment Exam (New 2026/ 2027 Update) Python for IT Automation | Questions & Answers| Grade A| 100% Correct (Verified Answers) Q. What are the traits of Imperative/procedural programming? ANSWER Focuses on describing a sequence of steps to perform a task Q. What are the traits of Object-Oriented Programming (OOP)? ANSWER Organize code around objects, which encapsulate data and behavior. Q. What are the traits of Functional Programming? ANSWER emphasizes the use of functions and immutable data for computation. Q. What are the traits of Declarative Programming? ANSWER describes what the program should accomplish without specifying how to achieve it. Q. What are the traits of Event-Driven Programming? ANSWER Reacts to events and user actions, triggering corresponding functions. Q. What are the traits of Logic Programming? ANSWER defines a set of logical conditions and lets the system deduce solutions. Q. What does Python syntax refer to? ANSWER The set of rules that dictate the combinations of symbols and keywords that form valid Python programs Q. What is the purpose of indentation in Python? ANSWER To define blocks of code Q. Why might a programmer use comments for 'Preventing Execution'? ANSWER To temporarily disable lines or blocks of code Q. What is the primary use of whitespace in Python? ANSWER To define the structure and hierarchy of the code Q. What does Python use to define the scope of control flow statements and structures like functions and classes? ANSWER Indentation Q. What is the purpose of the input() function in Python? ANSWER To capture user input and store it as a string Q. What does the format() method do in Python? ANSWER It enhances output formatting by embedding variables in strings. (although 'f' strings are easier to read) Q. What is the purpose of the Code Editor in a Python IDE? ANSWER To provide a text editor designed for Python, offering features like syntax highlighting, code completion, and indentation. Q. What does this built in Python function do?: print() ANSWER outputs text or variables to the console Q. What does this built in Python function do?: input() ANSWER reads user input from the console Q. What does this built in Python function do?: len() ANSWER determines the length of a sequence (string, list, tuple) Q. What does this built in Python function do?: type() ANSWER returns the type of an object Q. What does this built in Python function do?: int(), float(), str() ANSWER converts values to integers, floats, or strings; respectively Q. What does this built in Python function do?: max(), min() ANSWER returns the maximum or minimum value from a sequence Q. What does this built in Python function do?: sum() ANSWER calculates the sum of elements in a sequence Q. What does this built in Python function do?: abs() ANSWER returns the absolute value of a number Q. What does this built in Python function do?: range() ANSWER generates a sequence of numbers Q. What does this built in Python function do?: sorted() ANSWER returns a sorted list from an iterable Q. What does this built in Python function do?: any(), all() ANSWER checks if any or all elements in an iterable are true Q. What does this built in Python function do?: map(), filter() ANSWER applies a function to elements or filters elements based on a function Q. What does this built in Python function do?: open(), read(), write() ANSWER handles file I/O operations Q. What does this built in Python function do?: dir() ANSWER lists the names in the current scope or attributes of an object Q. What does this built in Python function do?: help() ANSWER provides help information about an object or Python Q. What is the primary characteristic of Python variables? ANSWER Variables are created as soon as a value is assigned to them. Q. What are the 5 Variable name rules in Python? ANSWER 1. can only contain letters, numbers, or an underscore. 2. MUST start with either a letter or underscore 3. Cannot start with a number 4. Cannot contain special characters. 5. Cannot be a Python keyword (such as: and, as, def, else, etc) Q. What are the 3 common naming conventions used in Python, and what is their format? ANSWER Camel case: each word, except for the first word, starts with a capital letter Pascal case: each word starts with a capital letter Snake case: each word in the variable is separated by an underscore. Q. What happens if the number of variables is not equal to the number of values in a Python assignment statement? ANSWER An error will occur Q. What does unpacking involve in Python? ANSWER Extracting elements from iterable objects and assigning them to individual variables Q. What is the result of using the '+' operator to output multiple Python variables of different types? ANSWER A Python error occurs. (must use variables of the same type) Q. How can multiple Python variables of different types be output using the print() function? ANSWER By separating each variable with a comma Q. What is the scope of a variable that is defined inside a function in Python? ANSWER Local Scope Q. How can a global variable be created inside a function in Python? ANSWER By declaring the variable with the 'global' keyword Q. What is a characteristic of Python as a dynamically-typed language? ANSWER The interpreter determines the type of variable during runtime Q. Which Python data type represents an ordered, mutable sequence? ANSWER 'list' What are the 3 sequence types in Python? what do they represent/look like? list: Ordered, mutable sequence; [1,23] tuple: Ordered, immutable sequence; (1,2,3) range: represents a range of values; e.g. range(5) What are the characteristics of a set? Unordered, mutable collection of unique elements. {1,2,3} what is a dictionary mapping type? an unordered collection of key-value pairs. my_dict = {'key':'value', 'name':'John'} What happens when an operation is performed that involves both an int and a float in Python? the result is automatically promoted to a 'float' What does the 'round(x, n) function do in Python? it rounds 'x' to 'n' decimal places What are the two main escape characters? n : new line t : for a tab What are the 3 components of a string slice? string [start:stop:step] · Start: the index from which the slicing begins (inclusive) · Stop: the index at which the slicing ends (exclusive) · Step (optional): The step or stride between characters. What does the string slicing operation 'text {::-1] do where text = "Hello, Python!"? It reverses the string. The 'step' portion of the slice is negative, indicating the stride between characters is reversed. What does the 'strip()' method do in Python? It removes leading and trailing whitespaces from a string what does the += operator do in Python string manipulation? It is used as a shorthand for concatenation and assignment What are truthy and falsy values in Python? Truthy values are non-zero numbers and non-empty strings. Falsy values are zero, None, and empty strings What is the purpose of the // operator in Python? It performs floor division operation; performs division and rounds down to the nearest whole number and discards the decimal part What is the purpose of the modulus operation '%' in Python? It returns the remainder of the division of two numbers. What does the arithmatic operator **= do? It take the exponent of the value applied to it. Consider the following Python code: colors = ['red', 'blue', 'green'] t(1, 'yellow') What will be the value of colors after executing this code? ['red', 'yellow', 'blue', 'green'] when using the .insert(), it doesn't replace the value in that position, it inserts into that place. When would I use extend() vs append()? extend() is used for adding multiple values from an iterable append() is used for adding a single element to the end (even if it's a list) my_list = [1, 2, 3] my_d([4, 5]) # Appending a list as a single element print(my_list) # Output: [1, 2, 3, [4, 5]] What does the pop() method do? It removes an item at the specified index position. example: devices = ['router1', 'switch2', 'firewall3'] removed_device = (1) This removes 'switch2' from devices since it is in index 1 position, and now it added to "removed_device. What is a 'shallow copy' of a list in Python? A copy of the list where changes to the copied list do not affect the original list. What is the difference between using the '+' operator and the 'extend()' method to concatenate lists in Python? The '+' operator creates a new list, while the 'extend()' method adds elements to the end of the original list. What is a significant advantage of using tuples in Python for storing information about network devices? tuples can be used as keys in dictionaries due to their immutability. How are items in a tuple accessed? By placing the index of the item inside square brackets [] after the tuple name print(10 9) print(10 == 9) print (10 9) Boolean print(bool("Hello")) print(bool("15")) print(bool(x)) Boolean examples of True print(bool(False)) print( ) print(0) Boolean examples of False print(isinstance(x, int)) determine if an object is of a certain data type int( ) casts an integer from an integer literal, float literal, or string literal float( ) casts a float from an integer literal, a float literal, or a string literal str( ) casts a string from strings, integer literals, or a float literals print("text") outputs text to the console print("text", end=" ") print("more text") will end with a space and continue on the same line ("text more text") print("Wage", wage) comma will print both items with a space between them print(variable) prints the value of the variable print("1n2n3") print using newline characters print( ) print a blank line python run a script file random function there is no random function, but there is a random module (import random) for x in "bananas": print(x) strings are arrays, so this will loop through the characters in "bananas" variable=input( ) assign text entered by the user to a variable; input is always a string variable = int(input) convert user input into an integer hourly_wage = int(input("Enter hourly wage: ")) display text prompt (Enter hourly wage) to request input from user and convert to integer print(( )) display a in console in upper case print(( )) display a in console as lower case print(( )) remove whitespace at beginning and end print(ce("H", "J")) replace a string with another string print(("b")) split string at specified character c=a+b print(c) concatenate (combine) two strings a=(f"My name is John, I am {age}") print(a) f-string; { } is the placeholder/modifier a = 85.8756 b = format(a, ".2f") print(b) modifier to format the value to 2 decimal places (85.88) price = 85. b = f"Price: ${price:.2f}" print(b) f-string with placeholder for price and modifier to format value to 2 decimal places (Price: $85.88) What built-in data type is used when you assign text to your variable? str x = "Hello, World!" x = str("Hello, World!") What built-in data type is used when you assign a numeric value to your variable? int x = 20 x = int(20) float x = 20.5 x = float(20.5) complex x = 1j x = complex(1j) What built-in data type is used when you assign a sequence to your variable? list x = ["apple", "banana", "cherry"] x = list(("apple", "banana", "cherry")) tuple x = ("apple", "banana", "cherry") x = tuple(("apple", "banana", "cherry")) range x = range(6) What is the difference between a list and a tuple? list = collection of values tuple = ordered and unchangeable What built-in data type is used when you assign a mapping to your variable? dict x = {"name" : "John", "age" : 36} x = dict(name="John", age=36) What built-in data type is used when you assign a set to your variable? set x = {"apple", "banana", "cherry"} x = set(("apple", "banana", "cherry")) frozenset x = frozenset({"apple", "banana", "cherry"}) x = frozenset(("apple", "banana", "cherry")) What built-in data type is used when you assign a boolean to your variable? bool x = True x = bool(5) What built-in data type is used when you assign binary to your variable? bytes x = b"Hello" x = bytes(5) bytearray x = bytearray(5) memoryview x = memoryview(bytes(5)) What built-in data type is used when you assign the value none to your variable? nonetype x = none What is Syntax Error? contains invalid code that cannot be understood What is Indentation Error? lines of the program are not properly indented What is a Value Error? invalid value is used (e.g., int(three)) What is a Name Error? program tries to use a variable that does not exist What is a Type Error? operation uses incorrect types (e.g. int(5) + string(four)) How do you check which version of Python editor you have? import sys print(on) How do you edit, save, and run a Python file? edit = can edit in a text editor save = save as run = in command prompt, type Can you run Python in the Command Line? type python or py you will see Python version information and when you are finished, type exit( ) What is unique about Python script formatting? relies on indentation (whitespace) to define scope instead of curly brackets Which Python datatypes are used to store arrays? list, tuple, set, and dictionary Which Python datatypes allow arrays with duplicates? list and tuple Which Python datatypes are for ordered arrays? list, tuple, dictionary Which Python datatypes are unchangeable? tuple and set What kind of variable would x = [ ] result in? list How do you determine how many items are in a list? print(len(yourlist)) What are some characteristics of a list? ordered; changeable; allows duplicate values; new values added to the end of the list; indexed (first value if 0, second value is 1, etc.); values can be any datatype (and a mix of datatypes) What are some characteristics of a tuple? ordered; unchangeable; allows duplicate values What are some characteristics of a set? unordered; unchangeable (you can add or remove items, but you cannot change an item); unindexed What are some characteristics of a dictationary? ordered; changeable; no duplicates How do you verify the type of an object? print(type(myobject)) What is an integer? positive or negative whole number of unlimited length What is a float? positive or negative number with a decimal; can also be a scientific number with an e What is a complex number? a number with an imaginary part represented by a j Can you convert a complex number into another number type? no Can you convert a number into a complex number? yes a = complex(x) Can you generate random numbers in Python? no random function, but there is a random module import random print(ange(1,10)) What are the arithmetic operators in Python? + - * / % modulus (remainder) ** exponentiation // floor division (round down to nearest whole number) What is an assignment operator? used to assign values to variables if x = 5 what is x += 3 8 if x = 5 what is x -= 2 3 if x = 5 what is x *= 3 15 if x = 5 what is x /= 3 1.6666 if x = 5 what is x %= 3 2 if x = 5 what is x //= 3 1, which is assigned back to x if x = 5 what is x **= 3 125, which is assigned back to x What does == mean? equal to What does != mean? not equal to What are the comparison operators? == != = = What are the logical operators? and, or, not What are the identity operators? is, is not What are the membership operators? in, not in What are the assignment operators? = += -= *= /= %= //= **= What are the bitwise operators? & | ^ ~ print(6 & 3) bitwise operator AND compare bits and set both bits to 1 if both bits are 1 6 () 3 () 2 () print(6 | 3) bitwise operator OR compare bits and set each bit to 1 if at least one bit is 1 6 () 3 () 7 () print(6 ^ 3) bitwise operator XOR compare bits and set each bit to 1 if only one bit is 1 6 () 3 () 5 () print(~ 3) bitwise operator NOT inverts all the bits 3 () -4 () print(3 2) bitwise operator zero fill left shift shifts left by pushing zeros from the right and letting leftmost bits fall off 3 () 12 () print(8 2) bitwise operator signed right shift shifts right by pushing copies of the leftmost bit in from the left and letting the rightmost bits fall off 8 () 2 () What is operator precedence? parentheses exponentiation ** unary - (the negative value of the operand) multiplication, division, modulus % addition and subtraction left-to-right What is an f-string? allows you to format selected parts of a string; replaced format( ); specified by putting f in front of the string literal e.g. txt = f"The price is 49 dollars" How do you denote a placeholder in an f-string? { } e.g., txt = f"The price is {price} dollars" Can you perform an operation in an f-string? yes, you can perform an operation on numbers or variables; you can also place if...else statements in an f-string Can you execute functions in an f-string? yes, either built-in or custom How can you define your own function? Use def FunctionName(Variable) actions def greet(name): print(f"Hello, {name}!") to execute: greet("Alice") How do you denote a modifier in an f-string placeholder? in placeholder, after name of variable or value, use a : followed by formatting type e.g., txt = f"The price is {95:.2f} dollars" What is the old method of formatting a string? format( ) What modifiers are used to align the result within the available space? : left : right :^ center What modifiers are used to set thousand separators? :, comma :_ underscore Which modifiers are used to show a value's positive or negative sign? := shows negative sign in the left most position :+ shows sign for positive and negative numbers :- shows sign for negative number only :(space) shows sign for negative and an extra space for a positive number What is the modifier to show the value in binary format? :b What is the modifier to show the value in the corresponding Unicode character? :c What is the modifier to show the value in decimal format? :d What is the modifier to show the value in scientific format? :e :E for uppercase E What is the modifier to show the value in fix point number format? if number not specified, shows 6 digits after decimal :f show inf and nan lowercase :F show inf and nan uppercase What is the modifier to show the value in general format? :g :G for uppercase E in scientific notation What is the modifier to show the value in octal format? :o What is the modifier to show the value in hex format? :x lowercase :X uppercase What is the modifier to show the value in number format? :n What is the modifier to show the value in percentage format? If number not specified, will show 6 numbers after decimal; can also use 0 for no decimal :% What characters are allowed in an identifier or name? letters, underscore, and digits What characters are allowed at the beginning of an identifier or name? must start with an underscore or a letter What are reserved words? words that already have a predefined meaning, such as False, None, True (with caps), break, class, continue, return, import What does an interpreter do with objects? creates and manipulates objects as needed to run code; assigns an object to a location somewhere in memory What is garbage collection? the automatic process of deleting unused objects to keep memory of computer less utilized What is name binding? associating names with interpreter objects What are the three properties each object has? value, type, and identity What is an immutable object? modification is limited to inside the function; any modification results in the creation of a new object in the function's local scope; integers and strings are immutable What does the identity of an object tell you? it is a unique numeric identifier that normally refers to the memory address where the object is stored What does e mean in scientific notation? x10 to the value of the next number What is the limit for a floating-point value? max of 1.8x10^308 min of 2.3x10^-308 What is an expression in Python? combination of variables, literals, operators, and parenthesis that evaluates to a value; just because it is an expression in algebra DOES NOT mean it is an expression in Python (for example, having both sides of the equation or having 2x without the * operator) How do you find the absolute value in Python? abs( ) How do you find the square root in Python? import math ( ) How do you request input in Python? default is string variable = float(input()) variable = int(input()) What is a string literal? a string value specified in the source code; 'text' or "text" What is a sequence type? a collection of objects ordered from left to right; the first object is 0; each object's position is its index What is another term for an object's position in a collection? its index What is an implicitly defined range? if code eliminates a range of values, the range that reaches the second line of code is implicitly known if x 0 tells us that numbers that reach the second line of code are = 0 Fastest way to isolate and remove the last digit of an integer % 10 // 10 How to print theater tickets (row numbers, column letters) num_rows = int(input()) num_cols = int(input()) alph_cols = (f"chr(ord('@') + {num_cols}") c = "a" r = 1 if num_cols 0: while r = num_rows: while c = alph_cols: print(f"{r}{()}", end=" ") c = chr(ord(c) + 1) r = r + 1 c = "a" print() How to transform int(input()) into corresponding alpha num_cols = int(input()) alph_cols = (f"chr(ord('@') + {num_cols}") c = "a" while c = alph_cols: print(f"{()}", end=" ") How to print an * rectangle num_rows = int(input()) num_cols = int(input()) for a in range(num_rows): for b in range(num_cols): print('*', end=' ') print() What is a break statement? Causes loop to exit immediately; else statement does not execute What is a continue statement? Causes a loop to immediately jump back to the while or for statement Sort odd and even numbers if(result % 2) != 0 is true, odd number if(result % 2) != 0 is false, even number What is enumerate( )? retrieves the index and value of an element in a list What is unpacking? performs multiple assignments at once, binding comma-separated names to elements (e.g., num1, num2 = [350, 400] would be num1 = 350 and num2 = 400) What is def ( )? begins a function definition in the format of def functionName(parameters): How do you explicitly return a value or object of a function? return How do you call a function? functionName(parameters); if the function is defined inside of a class or module, you can call it with dot notation (e.g., ) What is a docstring? Comments that are added to documentation and are surrounded by three double quotes ("""Keyword arguments""") How do you name a variable versus a constant? variable_name CONSTANT_NAME What is def( )? a function definition; may contain 0 or any number of parameters def print_feet_inch_short(user_feet, user_inches): print(f"{user_feet}' {user_inches}"") user_feet = int(input()) user_inches = int(input()) print_feet_inch_short(user_feet, user_inches) What is a return statement? exits a function and returns to the statement where the function was called What is a parameter? function input(s) specified in a function definition; cannot be an expression def calc_pizza(pizza_diameter, pizza_height) What is an argument? a value provided to a function's parameter during a function call; is an expression calc_pizza(12.0, 0.3) What is a hierarchical or nested function call? a function call residing in a function statement user_input = int(input()) What is a void function? functions can output and/or return a value; if it only outputs and does not return a value (e.g., print( )), it is a void function What does if __name__ == "__main__": do? It separates a section of code from the rest of the code so that you can do unit testing. If the module is the main program, it will run anything designated as __name__ == __main__. If the module was imported into the main program as a regular module (e.g., with "import"), anything designated __name__ == __main__ will NOT run. This is because when importing the module, the file name will be assigned as __name__. What is polymorphism? the behavior of an operator will depend on the type of operands; for example, * between two integers will result in the product of the integers but one string and one integer will result in the string being repeated (integer) times What is dynamic typing? the interpreter determines the type of objects as the program executes; the programmer does not have to define them What is static typing? programmer must define the type of every variable and every function parameter in the source code What is modular development? dividing a program into separate modules that can be developed and tested separately and then integrated into a single program function stubs function definitions whose statements haven't been written yet; at least one statement is required in a user defined function; can use pass keyword (program continues), return -1 (if should have a return value), print("FIXME"), or raise NotImplementedError (program stops) Easy way to print the contents of list (separated by spaces, no brackets) print(*list) To iterate each element of a list for num in numbers: print(num, end=' ') Can add condition: for num in numbers: if number = 8 print(num, end=' ') What is pass-by-assignment? arguments to functions are passed by object reference Calling a variable without using f-string color = input("Enter a color: ") print("Roses are " + color) If you get an "invalid syntax error," what should you check? that you have not forgotten : also check the line before the erroring line to see if you have the : and have closed ) or } as needed During a loop, create a string, and append it? my_string = ' ' my_string += str(letter) reversed( ) my_string = "hello" rev_string = ' ' for rev in reversed(my_string): rev_string += rev return rev_string Calling a function from a function def functionA(inputA):What does read() do? Reads data from a file What does input() do? gets user input from the console/terminal. Returns what's typed as a string What does write() do? Writes data to a file What is 'w' mode? Write What is 'a' mode? Append What does print() do? Displays output to the console/screen. Mainly used for seeing what code is doing or debugging. What should be at the end of a functions definition? Colon What data structure do the brackets indicate in the following example? devices = ["router01", "switch01", "modem01", "gateway01", "printer01"] A List What data structure do the brackets indicate in the following example? devices = ("router01", "switch01", "modem01", "gateway01", "printer01") A Tuple What data structure do the brackets indicate in the following example? devices = {"router": "router01", "switch": "switch01"} A Dictionary What data structure do the brackets indicate in the following example? Also there are no duplicates? devices = {"router01", "switch01", "modem01"} A Set What is this an example of? "Hello" + "World" = "HelloWorld" Concatenate What does a '#' indicate within Python? Creates a comment, which is ignored by Python when the code runs and is only for humans to read Which data structure is ordered and cannot be modified once it's created? (Immutable, Fixed, Permanent, Snapshot) Tuple Which data structure fits the requirements the best? EX: Mutable, Ordered Sequence, Indexed, ability to add, remove or update, dynamic, allows duplicates List Which data structure fits the requirements the best? EX: Key-Value Pairs, Mapping, Associative, Looking up via Name or Label, Descriptive Data not just values, "Associate X with Y", Fast Lookup, Retrieval by Key Dictionary Which data structure fits the requirements the best? EX: Unique Values, No Duplicates, Unordered, No Indexing, Membership Testing, Remove Duplicates Automatically, Mathematical Operations Set Based on the Python list: numbers = [10, 20, 30, 40] What is the index position of the element "40"? numbers[1] numbers[2] numbers[3] numbers[4] 3 2 multiple choice options What is required at the end of "if, else, elif, for, while, def, and class" statements? colon What does a 'while' loop do? Repeats code over and over as long as the condition is true What is 'r' mode? Read What is 'x' mode? Creation What is "f" (formatted) mean in an f-string? Allows you to put variables inside {} What do parenthesis do in an f-string? Marks start and end .supper() is for what? All Uppercase .isalpha() is for what? Checks if string is only letters .isdigit() is for what? Checks if string has only digits Variable Containers to put into string. Used to store data. They are created by assigning a value to a name. Containers to put into string What does Python have built-in as a Module? JSON How is external functionality is brought into a Python script? Import How many spaces per indentation? 4 What's an integer Whole Number What's a float Decimal numbers What's a conditional Code that runs only if certain conditions are true What's a for-loop Code that repeats a specific number of times automatically What's a while-loop Code that repeats while a condition is true What's a function Reusable blocks of code that perform a specific task What's a Class Blueprints for creating objects that have properties and behaviors What's a module Pre-written Python code that adds extra functionality How do you use modules Import What is whitespace Spaces, tabs, and line breaks used to format and organize Python code Which method is used to add an element to the end of a list? Append() What adds multiple elements from an iterable (like another list) to the end of a list Which function is used to remove an item from a list by its index position? pop() Which function is used to remove an item from a list by its value? remove() write() Which function should be used to add data to a file, such as a network configuration file? To define a function with a default greeting Based on the Python code snippet: def greet(name, greeting = "Welcome to WGU"): return f"{greeting}, {name}!" What is the purpose of the first line of code? Add a colon after def multiply_numbers(num1, num2). This Python code snippet returns a syntax error when run: def multiply_numbers(num1, num2) result = num1 * num2 return result num1 = 5 num2 = 8 print(multiply_numbers(num1, num2)) Which code adjustment will resolve the syntax error? List Based on the Python snippet: devices = ["router01", "switch01", "modem01", "gateway01", "printer01"] Which data structure is being used to store the names for various types of devices within devices? Converts the user's input into an integer and sums it Based on the Python snippet: value = input("Enter a number: ") result = int(value) + 10 print(result) What purpose does result = int(value) + 10 serve? Decrease the indentation of the else statement. This Python snippet checks the new processing speed of an updated computer. However, the snippet throws an error when ran. def check_processing_speed(current_speed, threshold_speed): is_fast_processing = current_speed threshold_speed if is_fast_processing: print(f"The processing speed of {current_speed} GHz is fast.") else: print(f"The processing speed of {current_speed} GHz is not fast enough. Consider an upgrade.") current_speed = 4 threshold_speed = 2 check_processing_speed(current_speed, threshold_speed) Which code adjustment will provide the intended response by addressing the error? Tuple A developer is creating a Python script to capture metrics for different network interfaces on a router, with each set of metrics treated as a single, immutable record. The stored record will represent a snapshot of metrics for a specific network interface at a given point in time to capture historical records for future analysis. Which data structure should be used to store the recorded metrics based on the specifications? numbers[3] Based on the Python list: numbers = [10, 20, 30, 40] What is the index position of the element "40"? Ordered and unchangeable Which characteristics are associated with tuples in Python? Missing colons at the end of the if and else lines Based on the Python code snippet: port = input("Secure Web access? Y/N: ") if port == "Y" print("Use port 443.") else print("Use port 80.") Which error is present in the snippet? Greater than b Based on the Python code snippet: import math a = 12 b = (121) if a b: print("Greater than b") elif a b: print("Less than b") else: print("Equal") Which output is provided when the snippet is executed? 5 Based on the Python code snippet: total = 0 count = 0 while total 15: count += 1 total += count How many iterations must be completed for the variable total to equal 15? 20 Based on the Python code snippet: sum = 0 values = [2,4,6,8] for number in values: if sum 20: sum = sum + number print(sum) What is the output of print(sum)? router_id += 5 The Python snippet has a logic error causing an infinite loop. router_id = 100 while router_id = 100: if router_id % 8 == 0: print(f"Router {router_id}: Configuration audit passed. No security vulnerabilities found.") else: print(f"Router {router_id}: Security alert - Action required.") router_id -= 5 Which replacement line of code will fix the logic error while still providing an output? Increase the indentation of the except block to match the try block. The Python snippet is intended to create directories that correspond to the names in a list. import os def automate_system_tasks(directory_names): for name in directory_names: if s(name): print(f"Directory '{name}' already exists.") else: try: irs(name) print(f"Directory '{name}' created successfully.") with open((name, 'router_'), 'w') as file: ("Router configurations.") print(f"Router Config file created in '{name}'.") except OSError as e: print(f"Error creating directory '{name}': {e}") directory_names = ['01_routers_bldg_1010', '02_routers_bldg_2020', '03_routers_bldg_3030'] automate_system_tasks(directory_names) Which code adjustment will provide the expected behavior? check_device_status(device_name, ping_success) Based on the Python code snippet: def check_device_status(device, ping): if ping: print(f"The device {device} is responding to pings. It's operational.") else: print(f"The device {device} is not responding to pings. Investigate the issue.") device_name = input("Enter the name of the network device: ") ping_success = input("Did the device respond to pings? (yes/no): ") == "yes" Which line of code will provide an appropriate device status based on user values? open('', 'x') A network administrator has been asked to create a new configuration file to deploy a device to the network. An error should be raised if the file already exists to avoid overwriting existing information. Which open() function parameter should the network administrator use to create the file? w A network configuration file needs to be updated frequently. Because the device uses a dynamic IP address, the previous content in the file is no longer necessary and should be removed. Which mode of open() achieves this operation? socket Based on the following Python code snippet: def automate_network_task(server, port): try: # Create a socket object. s = t(socket.AF_INET, socket.SOCK_STREAM) # Set a timeout for the connection attempt (in seconds). timeout = 5 meout(timeout) # Attempt to connect to the server and port. ct((server, port)) # If the connection is successful, print a success message. print(f"Connection to {server}:{port} successful!") # Close the socket. () except as e: # If an error occurs during the connection attempt, print an error message. print(f"Connection to {server}:{port} failed. Error: {e}") # Example usage server_to_connect = "" port_to_connect = 80 automate_network_task(server_to_connect, port_to_connect) Which library should be imported for the automate_network_task function to work as expected? from netmiko import ConnectHandler Based on the following Python code snippet: device = { "device_type": "cisco_ios", "ip": "192.168.1.1", "username": "admin", "password": "password", } config_commands = [ "interface GigabitEthernet0/1", "ip address 192.168.1.1 255.255.255.0", "no shutdown", ] with ConnectHandler(**device) as net_connect: net__config_set(config_commands) output = net__command("show interfaces GigabitEthernet0/1") print(output) Which library and package should be imported prior to the first line of code to connect to the remote network device and apply a configuration change? It removes a package from the system, and it will no longer be available for import in Python scripts What happens when you use the pip uninstall package_name command in Python? It provides a wide range of functionalities, including mathematical operations, file I/O, system calls, and even Internet protocols What is the purpose of the Python Standard Library? It allows for importing only the necessary functions or classes, making the code more efficient What is the advantage of using the from ... import ... statement in Python? It returns a list of the module's attributes, including its functions What does the dir() function do when a module is passed as an argument in Python? It renames a module What is the purpose of using the as keyword when importing a module in Python? To allow for code reuse across multiple scripts, improving code organization and readability What is the purpose of creating a Python module? It is a multi-vendor library to simplify Paramiko SSH connections to network devices What is the purpose of the Netmiko package in Python? Python scripts can run on various operating systems Why is Python a popular choice for file automation? It returns a list of all lines in a file What does the ines() function do in Python? When working with text files in Python, it handles the encoding and decoding of the text into a specific character set What is the key difference between handling text files and binary files in Python? It reads a single line from the file What does the readline() method do when working with text files in Python? It creates a reader object for reading CSV files What does the r() function do when working with CSV files in Python? The 'a' mode appends to the end of the file, while the 'w' mode overwrites the file What is the difference between the 'a' and 'w' modes when using the open() function in Python? It frees up system resources that were tied up with the file What is a purpose of closing files in Python? It deletes a file at the specified path What does the e() function do in Python? Runtime error What type of Python programming error is described by the scenario? A Python program is expected to read and process data from a file. However, the program crashes during execution because the file it's trying to read does not exist. To step through the code line by line, inspect variables, and set breakpoints at specific lines of code In the Python debugging process, what is the purpose of the pdb tool? Profiling Which Python debugging technique would be most useful for identifying bottlenecks in the code that may be causing performance issues? Semantic error A developer writes a Python program in an IDE. The program compiles and runs without crashing, but the output is not what the developer expected. What type of error is this? Linters Which Python debugging tool is best suited for identifying potential issues in the code that might lead to errors? for i in range(5) print(i) Which Python code snippet will result in a syntax error? Off-by-one error A developer writes a Python program that includes a loop. The loop is intended to run 5 times, but the developer mistakenly sets it to run 6 times. What type of Python error is this? Incorrect use of assignment operator A developer writes a Python program that includes a conditional statement. The developer intends to check if a variable x is equal to 2, but mistakenly uses the assignment operator (=) instead of the equality operator (==). What type of branching error is this? A loop that modifies the list it is iterating over, causing it to skip elements or go out of range In Python programming, which scenario is an example of a "Modifying a List While Iterating Over It" error? A local or global name is not found in the code Which scenario is an example of a "NameError"? Pattern matching Which input validation method would be most appropriate to ensure that a username only contains letters, numbers, and underscores? A for loop is used for iterating over a sequence or other iterable objects, while a while loop is used when a set of statements needs to be executed until a condition is false Which statement describes the difference between a for loop and a while loop in Python? "Device 192.168.1.1 is down. Device 192.168.1.2 is down. Device 192.168.1.3 is down." "Device 192.168.1.1 is down. Device 192.168.1.2 is down. Device 192.168.1.3 is down." "0 1 2" "Device 192.168.1.1 is up. Device 192.168.1.2 is down. Stopping check." "Device 192.168.1.1 is up. Device 192.168.1.2 is down. Skipping to next device. Device 192.168.1.3 is up." "0 1" "192.168.1.1n192.168.1.2n192.168.1.3" "2 4 6 8" "0 1" "2" To execute one block of code when a specified condition is true, and a different block of code when the condition is false What is the purpose of an if/else statement? "Device is offline. Unable to perform configuration." The code results in a syntax error "x is 30 or more" To specify a block of code that should be executed if the condition(s) in the control structure is not met What is the purpose of the else keyword in control flow structures? If the first condition is False, the second condition will not be checked In Python, what is the behavior of the and keyword in the context of short-circuit evaluation? It does not check the second condition and returns True What is the behavior of the or operator in Python when the first condition is True? "Either x or y is not greater than 5" "Device 192.168.1.1 is down." Python allows administrators to automate repetitive tasks, saving valuable time and reducing the potential for manual errors What is one of the reasons administrators often choose to automate tasks using Python? The send_config_set method is used to send the configuration commands to the device The _pending() function is used to check if any scheduled tasks need to be executed It is used to determine if the code is running as the main file What is the purpose of the if __name__ == "__main__": pattern in Python? The ip_address='192.168.1.1' default parameter is used to specify the IP address for the configuration of the device The device_type and ip_address keyword arguments are used to specify the type of device and its IP address for the configuration The *devices argument is used to accept any number of devices to be added to the network_devices set What is the difference between parameters and arguments in Python functions? Parameters are variables in a function's definition, and arguments are actual values passed to a function The add_device function returns the network_devices set with the 'Load Balancer' added The add_device function is used to add a new device to the network_devices set Dictionaries allow you to associate values with descriptive keys, providing a convenient way to represent relationships between data What is the primary advantage of using dictionaries in Python? devices = {'Router1': '192.168.1.2', 'Switch2': '10.0.0.2'} Which Python code snippet correctly demonstrates the creation of a dictionary with key-value pairs? data_types = {'string_key': [1, 2, 3], (4, 5, 6): 'tuple_key'} Which Python code snippet correctly demonstrates the creation of a dictionary with various data types for both keys and values? d = dict([('key1', 'value1'), ('key2', 'value2')]) Which Python code snippet correctly demonstrates the use of the dictionary constructor, dict()? dict2 = {"keyA": "valueA", "keyB": "valueB"}; value = dict2["keyA"] Which Python code snippet correctly demonstrates how to access an item in a dictionary using its key? devices = {"DeviceA": "192.168.1.1", "DeviceB": "10.0.0.1"}; devices["DeviceA"] = "192.168.1.100" Which Python code snippet correctly demonstrates how to change the value of a specific key in a dictionary? info1 = {"A": "1", "B": "2"}; info2 = {"B": "3", "C": "4"}; e(info2) Which Python code snippet correctly demonstrates the use of the update() method to update a dictionary with the key/value pairs from another dictionary? By directly assigning a value to a new key in the dictionary How can an item be added to a Python dictionary? dict3 = {"keyX": "valueX", "keyY": "valueY"}; del dict3["keyX"] Which Python code snippet correctly demonstrates how to remove an item from a dictionary? It removes all items from the dictionary What does the clear() method do in a Python dictionary? devices = {'Switch', 'Router', 'Firewall'}; new_devices = {'Firewall', 'Load Balancer'}; devices = (new_devices) Which Python code snippet correctly demonstrates the use of a set to maintain a collection of unique items? By placing a comma-separated sequence of items inside curly braces {} or using the set() function How can a set be created in Python? A set created using set() holds an unordered collection of unique items What is the primary characteristic of a set created using the Python set constructor, set()? By using the in keyword How can you check if a specific item is present in a Python set? By using the add() method for a single item and the update() method for multiple items How can items be added to a Python set? It adds items from another set into the current set What does the update() method do in a Python set? The remove() method raises an error if the item does not exist in the set, while the discard() method does not What is the difference between the remove() and discard() methods in a Python set? It empties a set, removing all items What does the clear() method do in Python? A NameError will be raised [0, 2, 4] Consider a list numbers = [0, 1, 2, 3, 4, 5]. What will be the output of numbers[::2]? "ho" Consider a string s = "Python". What will be the output of s[-3:-1]? ip_addresses_list is ['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4'] Consider the Python code: ip_addresses_string = "192.168.1.1,192.168.1.2,192.168.1.3,192.168.1.4" ip_addresses_list = list(ip_addresses_(',')) What is the value of ip_addresses_list? router1 Lists Which Python collection is best suited for storing an ordered sequence of elements that can be changed? False Consider a tuple t = (1, 2, 3, 4, 5). What will be the output of 6 in t? ['apple', 'blueberry', 'cherry'] Consider the Python code: fruits = ['apple', 'banana', 'cherry'] fruits[1] = 'blueberry' What will be the value of fruits after executing this code? [1, 7, 8, 4, 5] Consider the following Python code: numbers = [1, 2, 3, 4, 5] numbers[1:3] = [7, 8] What will be the value of numbers after executing this code? ['red', 'yellow', 'blue', 'green'] Consider the following Python code: colors = ['red', 'blue', 'green'] t(1, 'yellow') What will be the value of colors after executing this code? ['cat', 'dog', 'bird', 'fish'] Consider the following Python code: animals = ['cat', 'dog', 'bird'] d('fish') What will be the value of animals after executing this code? ['a', 'b', 'c', 'd', 'e'] Consider the following Python code: letters = ['a', 'b', 'c'] d(['d', 'e'] What will be the value of letters after executing this code? It means variable types in Python are determined at runtime. What does it mean to say that Python is dynamically typed? It reacts to events and user actions, triggering corresponding functions. What is the primary focus of the Object-Oriented Programming (OOP) paradigm? The set of rules that dictate the combinations of symbols and keywords that form valid Python programs. What does Python syntax refer to? To define blocks of code. What is the purpose of indentation in Python? It is used to start a comment What is the role of the # symbol in Python? To document and clarify code What is the primary purpose of comments in Python? By allowing team members to communicate about the code How can comments facilitate collaboration in a team? To temporarily disable lines or blocks of code Why might a programmer use comments for 'Preventing Execution'? Indentation What does Python use to define the scope of control flow statements and structures like functions and classes? To capture user input and store it as a string What is the purpose of the input() function in Python? It enhances output formatting by embedding variables in strings What does the format() method do in Python? To provide a text editor designed for Python, offering features like syntax highlighting, code completion, and indentation. What is the purpose of the Code Editor in a Python IDE? It involves testing the code with various inputs to ensure it works as expected and debugging is done to identify and fix the issues if the code doesn't work as expected What is the purpose of the Testing and Debugging step in the Four-Step problem-solving process in Python programming? Variables are created as soon as a value is assigned to them What is the primary characteristic of Python variables? switchname_e Which Python variable name is valid? Camel case What is the naming convention where each word in the variable name, except for the first word, starts with a capital letter? An error will occur What happens if the number of variables is not equal to the number of values in a Python assignment statement? Extracting elements from iterable objects and assigning them to individual variables What does unpacking involve in Python? A Python error occurs What is the result of using the + operator to output multiple Python variables of different types? By separating each variable with a comma How can multiple Python variables of different types be output using the print() function? Local scope What is the scope of a variable that is defined inside a function in Python? By declaring the variable with the global keyword How can a global variable be created inside a function in Python? result is 50 Consider the Python expression: result = 2 + 3 4 * 2 What is the value of result? 'banana' in fruits returns True Consider the Python code: fruits = ['apple', 'banana', 'cherry', 'date'] Which statement is correct? x is y returns True Consider the Python code: x = [4, 5, 6] y = x z = [4, 5, 6] Which statement is correct? a = a ** 7 What is the equivalent expression for the operation a **= 7 in Python? It checks if two values are not equal What does the != operator do in Python? 3 What is the result of the floor division operation 17 // 5 in Python? It returns the remainder of the division of two numbers What is the purpose of the modulus operator % in Python? It performs floor division operation What is the purpose of the // operator in Python? The interpreter determines the type of a variable during runtime What is a characteristic of Python as a dynamically-typed language? list Which Python data type represents an ordered, mutable sequence? The result is automatically promoted to a float What happens when an operation is performed that involves both an int and a float in Python? It rounds x to n decimal places What does the round(x, n) function do in Python? 'hello, Python' What is the result of the operation greeting + ", " + language where greeting = 'hello' and language = "Python"? It returns the length of the string What does the len() function do in Python? It checks whether a specific character or phrase exists within the string What does the in keyword do in Python? 1 What is the default value of the step parameter in Python string slicing? It reverses the string What does the string slicing operation text[::-1] do where text = "Hello, Python!"? It counts the occurrences of a substring in the given string What does the count() method do in Python? It removes leading and trailing whitespaces from a string What does the strip() method do in Python? It is used as a shorthand for concatenation and assignment What does the += operator do in Python string manipulation? It concatenates strings from an iterable What does the join() method do in Python string manipulation? It formats strings by replacing placeholders with values What does the format() method do in Python string manipulation? It formats a number to two decimal places with comma as a thousand separator What does the {:,.2f} placeholder do in Python string formatting? It converts a value to a Boolean What does the bool() function do in Python? Truthy values are non-zero numbers and non-empty strings, while falsy values are zero, None, and empty strings What are truthy and falsy values in Python? 'cherry' In Python, if there is a list called fruits with the elements ['apple', 'banana', 'cherry', 'date', 'elderberry'], what will be the output of print(fruits[-3])? devices = ['router1', 'firewall3'], removed_device = 'switch2' Consider the following Python code: devices = ['router1', 'switch2', 'firewall3'] removed_device = (1) What will be the value of devices and removed_device after executing this code? 'router1' ['router1', 'server4'] Consider the Python code: devices = ['router1', 'switch2', 'firewall3', 'server4'] del devices[1:3] What will be the value of devices after executing this code? [ ] Consider the following Python code used in network automation: devices = ['router1', 'switch2', 'firewall3', 'server4'] () What will be the value of devices after executing this code? ["10.0.0.1", "10.0.0.2", "10.0.0.3"] Consider the following Python code: ip_addresses = ["10.0.0.2", "10.0.0.1", "10.0.0.3"] ip_(key=lambda ip: tuple(map(int, ('.')))) What will be the value of ip_addresses after executing this code? ip_(reverse=True) In a network automation script written in Python, a list of IP addresses is sorted in descending order using the sort() method. Which of the line of code correctly achieves this? It defines the sorting criteria by applying a function to each element in the list In Python, what is the purpose of the key parameter in the sort() method and the sorted() function? By setting the key parameter to a function that converts each item to lowercase before comparison How can a case-insensitive sort be performed in Python using the sort() method or the sorted() function? It modifies the original list to reverse the order of items and does not return any value What is the effect of the reverse() method on a list in Python? A new list is created from the original list What is the result of using the copy() method or the list() constructor on a list in Python? A copy of the list where changes to the copied list do not affect the original list What is a 'shallow copy' of a list in Python? The + operator creates a new list, while the extend() method adds elements to the end of the original list What is the difference between using the + operator and the extend() method to concatenate lists in Python? A new list is created, and changes to this list will not affect the original lists What happens to the original lists when they are concatenated using the + operator in Python? Tuples can be used as keys in dictionaries due to their immutability What is a significant advantage of using tuples in Python for storing information about network devices? By using the built-in len() function How can you determine the number of items in a tuple? By placing a single value inside parentheses () and following it with a comma How is a tuple with a single item created in Python? It converts an iterable into a tuple What is the purpose of the tuple() constructor? By placing the index of the item inside square brackets [] after the tuple name How are items in a tuple accessed? By specifying a start index and an end index separated by a colon : inside square brackets [] How is a range of indexes specified in a tuple using slicing? Negative indexing starts from the end of the sequence, with the last item at index -1 How does negative indexing work for tuples? in Which keyword is used to check if a specific item exists in a tuple? Convert the tuple into a list, modify the list, convert the list back into a tuple What is the correct sequence of steps to modify a tuple? t = (1, 2, 3); t = t + (4,) Which of the following Python code snippets correctly demonstrates the workaround to add an item to a tuple? t = (1, 2, 3); t = list(t); e(2); t = tuple(t) Which of the following Python code snippets correctly demonstrates the workaround to remove an item from a tuple? does stuff return resultA def functionB(resultA): does stuff return resultB inputA = input( ) subAnswer = functionA(inputA) ultimateAnswer = functionB(resultA) print(ultimateAnswer) What is a mutable object? in-place modification of the object can occur outside the scope of the function; e.g., adding elements to a container or sorting a list; this will affect other variables in the program that reference that object How can you avoid making unwanted changes to a mutabl

Vista previa del contenido

WGU D522 Objective Assessment Exam (New 2026/ 2027
Update) Python for IT Automation | Questions & Answers|
Grade A| 100% Correct (Verified Answers)

Q. What are the traits of Imperative/procedural programming?
ANSWER
Focuses on describing a sequence of steps to perform a task



Q. What are the traits of Object-Oriented Programming (OOP)?
ANSWER
Organize code around objects, which encapsulate data and behavior.



Q. What are the traits of Functional Programming?
ANSWER
emphasizes the use of functions and immutable data for computation.



Q. What are the traits of Declarative Programming?
ANSWER
describes what the program should accomplish without specifying how to achieve it.



Q. What are the traits of Event-Driven Programming?
ANSWER
Reacts to events and user actions, triggering corresponding functions.



Q. What are the traits of Logic Programming?
ANSWER
defines a set of logical conditions and lets the system deduce solutions.




1

,Q. What does Python syntax refer to?
ANSWER
The set of rules that dictate the combinations of symbols and keywords that form valid Python programs



Q. What is the purpose of indentation in Python?
ANSWER
To define blocks of code



Q. Why might a programmer use comments for 'Preventing Execution'?
ANSWER
To temporarily disable lines or blocks of code




Q. What is the primary use of whitespace in Python?
ANSWER
To define the structure and hierarchy of the code



Q. What does Python use to define the scope of control flow statements and structures like functions and
classes?

ANSWER
Indentation



Q. What is the purpose of the input() function in Python?
ANSWER
To capture user input and store it as a string



Q. What does the format() method do in Python?
ANSWER
It enhances output formatting by embedding variables in strings. (although 'f' strings are easier to read)




2

,Q. What is the purpose of the Code Editor in a Python IDE?
ANSWER
To provide a text editor designed for Python, offering features like syntax highlighting, code completion, and
indentation.



Q. What does this built in Python function do?: print()
ANSWER
outputs text or variables to the console



Q. What does this built in Python function do?: input()
ANSWER
reads user input from the console



Q. What does this built in Python function do?: len()
ANSWER
determines the length of a sequence (string, list, tuple)



Q. What does this built in Python function do?: type()
ANSWER
returns the type of an object



Q. What does this built in Python function do?: int(), float(), str()
ANSWER
converts values to integers, floats, or strings; respectively



Q. What does this built in Python function do?: max(), min()
ANSWER
returns the maximum or minimum value from a sequence




3

, Q. What does this built in Python function do?: sum()
ANSWER
calculates the sum of elements in a sequence



Q. What does this built in Python function do?: abs()
ANSWER
returns the absolute value of a number



Q. What does this built in Python function do?: range()
ANSWER
generates a sequence of numbers



Q. What does this built in Python function do?: sorted()
ANSWER
returns a sorted list from an iterable



Q. What does this built in Python function do?: any(), all()
ANSWER
checks if any or all elements in an iterable are true



Q. What does this built in Python function do?: map(), filter()
ANSWER
applies a function to elements or filters elements based on a function



Q. What does this built in Python function do?: open(), read(), write()
ANSWER
handles file I/O operations




4

Información del documento

Subido en
8 de abril de 2026
Número de páginas
49
Escrito en
2025/2026
Tipo
Examen
Contiene
Preguntas y respuestas
$12.49

¿Documento equivocado? Cámbialo gratis Dentro de los 14 días posteriores a la compra y antes de descargarlo, puedes elegir otro documento. Puedes gastar el importe de nuevo.
Escrito por estudiantes que aprobaron
Inmediatamente disponible después del pago
Leer en línea o como PDF

Vendido
4
Seguidores
0
Artículos
387
Última venta
2 meses hace



Por qué los estudiantes eligen Stuvia

Creado por compañeros estudiantes, verificado por reseñas

Calidad en la que puedes confiar: escrito por estudiantes que aprobaron y evaluado por otros que han usado estos resúmenes.

¿No estás satisfecho? Elige otro documento

¡No te preocupes! Puedes elegir directamente otro documento que se ajuste mejor a lo que buscas.

Paga como quieras, empieza a estudiar al instante

Sin suscripción, sin compromisos. Paga como estés acostumbrado con tarjeta de crédito y descarga tu documento PDF inmediatamente.

Student with book image

“Comprado, descargado y aprobado. Así de fácil puede ser.”

Alisha Student

Preguntas frecuentes