Python PCAP Certification

Ace your homework & exams now with Quizwiz!

#50. Which of the following expressions evaluate to True? (Choose two.) A. 'dcb' not in 'abcde'[::-1] B. 'True' not in 'False' C. str(1-1) in '0123456789'[:2] D. 'phd' in 'alpha'

Explanation The correct answers are: B: 'True' not in 'False' This checks if the substring 'True' is not in 'False'. 'True' is indeed not a part of 'False'. Therefore, 'True' not in 'False' is True. C: str(1-1) in '0123456789'[:2] 1 - 1 evaluates to 0, and str(0) is '0'. '0123456789'[:2] takes the first two characters of '0123456789', resulting in '01'. Checking if '0' is in '01': '0' is indeed in '01'. Therefore, str(1-1) in '0123456789'[:2] is True. The incorrect answers are: A: 'dcb' not in 'abcde'[::-1] 'abcde'[::-1] reverses the string 'abcde', resulting in 'edcba'. Checking if 'dcb' is not in 'edcba': 'dcb' is a substring of 'edcba'. Therefore, 'dcb' not in 'abcde'[::-1] is False. D: 'phd' in 'alpha' Checking if 'phd' is a substring of 'alpha': 'phd' is not in 'alpha'. Therefore, 'phd' in 'alpha' is False.

#68. What is the expected output of the following snippet? class Upper: def method(self): return 'upper' class Lower(Upper): def method(self): return 'lower' Object = Upper() print(isinstance(Object, Lower), end=' ') print(Object.method()) A. False upper B. True upper C. False lower D. True lower

Explanation Step-by-Step Breakdown Class Definitions: Upper defines a method that returns 'upper'. Lower inherits from Upper but overrides method to return 'lower'. Object Initialization: Object = Upper() creates an instance of the Upper class. isinstance(Object, Lower): Object is an instance of Upper. Lower is a subclass of Upper, but Object is not an instance of Lower. Therefore, isinstance(Object, Lower) evaluates to False. Object.method(): Object is an instance of Upper, so it calls the method defined in Upper. This method returns 'upper'. Correct answer: A

#70. What is the expected behavior of the following code? my_list = [i for i in range(5)] m = [my_list[i] for i in range(5) if my_list[i] % 2 != 0] print(m) A. the code is erroneus and it will not execute B. it outputs [0, 2, 4] C. it outputs [0, 1, 2, 3, 4] D. it outputs [1, 3]

Explanation Step-by-Step Breakdown First List Comprehension: my_list = [i for i in range(5)]] This creates a list with numbers from 0 to 4. Result: my_list = [0, 1, 2, 3, 4] Second List Comprehension: m = [my_list[i] for i in range(5) if my_list[i] % 2 != 0] Iterates over indices i from 0 to 4 (range(5)). Includes my_list[i] in the result only if my_list[i] % 2 != 0 (i.e., the value is odd). Evaluation for each I: i = 0: my_list[0] = 0 (not odd, skipped). i = 1: my_list[1] = 1 (odd, included). i = 2: my_list[2] = 2 (not odd, skipped). i = 3: my_list[3] = 3 (odd, included). i = 4: my_list[4] = 4 (not odd, skipped). Result: m = [1, 3] Print Statement: Outputs the resulting list [1, 3] Correct answer: D. Outputs [1,3]

#74. Assuming that the following code has been executed successfully, select the expressions which evaluate to True. (Choose two.) var = 1 def f(): global var var += 1 def g(): return var return g a = f() b = f() A. a() > 2 B. a is not None C. b() > 2 D. a is b

Explanation Step-by-Step Breakdown Global Variable: var is declared as a global variable with an initial value of 1. First Call: a = f(): Inside f(), var is incremented by 1. So, var = 2. A function g() is defined and returned by f(). Now, a is assigned the returned function g(). Second Call: b = f(): Inside f(), var is incremented again by 1. So, var = 3. Another instance of g() is returned by f(). Now, b is assigned the second returned function g(). Behavior of a() and b(): Both a() and b() are closures that reference the same global variable var, which is now 3. Therefore: a() evaluates to 3. b() evaluates to 3. The correct answers are: a() > 2 When a() is called, it returns the current value of var, which is 3. 3 > 2 is True. B. a is not None a is a valid function reference and is not None. C. b() > 2 When b() is called, it also returns the current value of var, which is 3. 3 > 2 is True. The incorrect answer is: D. a is b a and b are two separate instances of the g() function, returned by two separate calls to f(). Even though they both access the same global var, they are distinct objects.

#69. What is the expected output of the following code? myli = [1, 2, 4] m = list(map(lambda x: 2**x, myli)) print(m[-1]) A. 4 B. 1 C. an exception is raised D. 16

Explanation Step-by-Step Breakdown myli Initialization: myli is a list: [1, 2, 4] map Function: map applies a function (lambda x: 2**x) to each element of myli. The lambda function calculates 2^x for each element x. Calculations: For x = 1: 2^1 = 2 For x = 2: 2^2 = 4 For x = 4: 2^4 = 16 The resulting mapped list is [2, 4, 16]. Convert map to List: m = list(map(lambda x: 2**x, myli)) creates the list [2, 4, 16]. Access m[-1]: m[-1] retrieves the last element of the list m, which is 16. Correct answer: D

#75. Assuming that the snippet below has been executed successfully, which of the following expressions will evaluate to True? (Choose two.) string = 'REPTILE'[:3:] string = string[-1] + string[-2::-1] A. len(string) == 3 B. string[0] == 'E' C. string[0] < string[-1] D. string is None

Explanation Step-by-Step Breakdown string = 'REPTILE'[:3:] The slicing [:3:] takes the first 3 characters of the string 'REPTILE'. Result: string = 'REP'. string = string[-1] + string[-2::-1] Let's break it down: string[-1]: Takes the last character of 'REP', which is 'P'. string[-2::-1]: Reverses the string up to the second-to-last character: string[-2] is 'E', and string[-2::-1] reverses 'RE' to 'ER'. Concatenate: 'P' + 'ER' → string = 'PER'. The correct answers are: A. len(string) == 3 The length of 'PER' is 3. This evaluates to True. C. string[0] < string[-1] string[0] is 'P' and string[-1] is 'R'. 'P' < 'R' is True because 'P' comes before 'R' in ASCII order. The incorrect answers are: B. string[0] == 'E' string[0] is 'P', not 'E'. D. string is None string is 'PER', so it is not None.

#51. Which of the following expressions evaluate to True? (Choose two.) * len("""" """) > 0 len('\'') == 1 C. ord("z") - ord("Z") == ord("0") D. chr(ord('a') + 1) == 'B'

Explanation The correct answers are: A: len(""" """) > 0 """ """ represents a multi-line string containing a single \n character like this """\n""" Therefore, len("""\n""") is 1, because there is one space character in the string. Since 1 > 0 is True, this expression evaluates to True. B: len('\'') == 1 '\'' is a string containing a single backslash character. len('\'') is 1 because it represents a single character. Therefore, len('\'') == 1 is True. The incorrect answers are: C: ord("z") - ord("Z") == ord("0") ord("z") gives the ASCII value of 'z', which is 122. ord("Z") gives the ASCII value of 'Z', which is 90. ord("z") - ord("Z") is 122 - 90 = 32. ord("0") gives the ASCII value of '0', which is 48. Since 32 != 48, this expression is False. D: chr(ord('a') + 1) == 'B' ord('a') gives the ASCII value of 'a', which is 97. ord('a') + 1 is 98. chr(98) gives the character 'b', not 'B'. Therefore, chr(ord('a') + 1) == 'B' is False.

#63. What is the expected output of the following code? mytu = ('a', 'b', 'c') m = tuple(map(lambda x: chr(ord(x) + 1), mytu)) print(m[-2]) A. an exception is raised B. a C. b D. c

Explanation mytu = ('a', 'b', 'c'): This creates a tuple mytu with elements 'a', 'b', and 'c'. m = tuple(map(lambda x: chr(ord(x) + 1), mytu)): The map function applies the lambda function to each element in mytu. The lambda function lambda x: chr(ord(x) + 1) takes each character x, converts it to its ASCII value with ord(x), adds 1 to this value, and then converts it back to a character with chr(...). Let's go through each element in mytu: For 'a': ord('a') is 97, so chr(97 + 1) becomes chr(98), which is 'b'. For 'b': ord('b') is 98, so chr(98 + 1) becomes chr(99), which is 'c'. For 'c': ord('c') is 99, so chr(99 + 1) becomes chr(100), which is 'd'. The resulting mapped values are 'b', 'c', and 'd', so m = ('b', 'c', 'd'). print(m[-2]): m[-2] accesses the second-to-last element of m, which is 'c'. The correct answer is: D. c

#48. What is the expected behavior of the following code? the_string = ',,'.join(('alpha', 'omega')) the_list = the_string.split(',') print(',' in the list) A. it outputs False B. it raises an exception C. it outputs True D. it outputs nothing

Explanation the_string = ',,'.join(('alpha', 'omega')): This line will execute successfully, resulting in the_string being 'alpha,,omega'. the_list = the_string.split(''): This line will also execute successfully, resulting in the_list being ['alpha', '', 'omega']. print(',' in the list): Here, there is a syntax error. the list is not a valid variable name in Python, as variable names cannot contain spaces. Python will raise a SyntaxError at this line because of the invalid variable name. Expected Behavior The code will raise a SyntaxError due to the invalid variable name the list in the print statement. Correct Answer B. it raises an exception

#52. Assuming that the following inheritance set is in force, which of the following classes are declared properly? (Choose two.) class A: pass class B(A): pass class C(A): pass class D(B, C): pass A. class Class_2(A,B): pass B. class Class_3(A,C): pass C. class Class_1(D): pass D. class Class_4(C,B): pass

Explanation of the Inheritance Structure: class A is the base class. class B(A) inherits from A. class C(A) also inherits from A. class D(B, C) inherits from both B and C, creating a diamond inheritance structure, where D indirectly inherits from A through both B and C. A / \ B C \ / D Now, let's evaluate each option based on this inheritance structure and Python's method resolution order (MRO) rules. The correct answers are: C: class Class_1(D): pass This class inherits from D, which already has a consistent MRO resolved through B and C. Python's MRO algorithm can handle this inheritance order without any ambiguity. Result: This option executes correctly without errors, so Option C is valid. D: class Class_4(C, B): pass This class attempts to inherit from both C and B. Since C and B both inherit from A, but are listed in an order that Python's MRO can resolve (C first, then B), there is no ambiguity in the MRO. Result: This option executes correctly without errors, so Option D is valid. The incorrect answers are: A: class Class_2(A, B): pass This class attempts to inherit from both A and B. Since B already inherits from A, there is an MRO (Method Resolution Order) conflict here because Python would find it ambiguous, as it would need to resolve A twice in different orders. Result: This option raises a TypeError due to an MRO conflict, so Option A is invalid. B: class Class_3(A, C): pass This class tries to inherit from both A and C. Since C already inherits from A, Python finds it conflicting to have A appear twice in the hierarchy in inconsistent orders, causing an MRO conflict. Result: This option also raises a TypeError due to an MRO conflict, so Option B is invalid.

#45. What is the expected behavior of the following code? s = '2A' try: n = int(s) except: n = 3 except ValueError: n = 2 except ArithmeticError: n = 1 print(n) A. the code is erroneous and it will not execute B. it outputs 1 C. it outputs 3 D. it outputs 2

Explanation: In Python, the bare except block must always be listed last, and this code will produce a traceback error and the code will fail to execute. The correct answer is: A. the code is erroneous and it will not execute Bonus --Explanation: If the bare except block was correctly listed last: s = '2A': The variable s is a string that contains non-numeric characters ('2A'), which cannot be converted to an integer. n = int(s): The code tries to convert the string '2A' to an integer using int(s). Since '2A' is not a valid integer string, this will raise a ValueError and sets n = 2. print(n): The value of n is printed, which will be 2 Therefore the correct answer would be: D. it outputs 2

#44. What is the expected behavior of the following code? m = 0 def foo(n): global m assert m != 0 try: return 1 / n except ArithmeticError: raise ValueError try: foo(0) except ArithmeticError: m += 2 except: m += 1 print(m) A. it outputs 3 B. the code is erroneous and it will not execute C. it outputs 2 D. it outputs 1

Explanation: The code provided contains a logical error due to incorrect indentation. Specifically, the second try block that calls foo(0) is inside the function foo, rather than being outside of it as likely intended. Because of this, the try block where foo(0) is called will never execute, and the program flow will never update the global m based on catching any exceptions. So the correct answer is: B. the code is erroneous and it will not execute Bonus --Explanation: However, if the second try block and print statement were properly indented, the execution of foo(0) would raise an AssertionError because 0 is passed to foo() and assert m != 0 require that m cannot be 0. And since AssertionError isn't trapped explicitly, it is trapped by the general except block, iterating m by +1, so 0 + 1 = 1. It would print 1, making the correct answer: D. it outputs 1

#31. What is the expected behavior of the following code? class Class: __Var = 0 def foo(self): Class.__Var += 1 self.__prop = Class.__Var o1 = Class() o1.foo() o2 = Class() o2.foo() print(o2._Class__Var + o1._Class__prop) A. it outputs 6 B. it raises an exception C. it outputs 1 D. it outputs 3

Explanation: The correct answer is: D. it outputs 3 Here is why: The class Class has a class-level variable __Var, which starts at 0. There is also an instance-level variable __prop set within the foo method. When o1.foo() is called, the class variable Class__Var is incremented by 1 (so it becomes 1), and __prop for o1 is set to this value (so o1.__prop is 1). When o2.foo() is called, the class variable Class__Var is incremented again by 1 (so it becomes 2), and __prop for o2 is set to this value (so o2.__prop is 2). Finally: o2._Class__Var is 2, and o1._Class__prop is 1. Adding them gives 2 + 1 = 3. Thus, the output is 3.

#26. What is the expected output of the following snippet? class Upper: def __init__(self): self.property = 'upper' class Lower(Upper): def __init__(self): super().__init__() Object = Lower() print(isinstance(Object, Lower), end=' ') print(Object.property) A. False upper B. True upper C. False lower D. True lower

Explanation: The correct answer is: The expected output of the provided Python code snippet is: B. True upper Here's why: The Object is an instance of the Lower class, which is a subclass of Upper. Therefore, isinstance(Object, Lower) will return True because Object is an instance of Lower. The Lower class doesn't define its own property attribute, but it inherits from the Upper class, which sets self.property = 'upper' in its __init__ method. So, Object.property will refer to the property of the Upper class, which has the value 'upper'. Thus, the output of the code will be: True upper

#30. What is true about Python class constructors? (Choose two.) A. the constructor's first parameter identifies an object currently being created B. super-class constructor is invoked implicitly during constructor execution C. the constructor can be invoked directly under strictly defined circumstances D. the constructor cannot use the default values of the parameters

Explanation: The correct answers are: A. the constructor's first parameter identifies an object currently being created This is correct. In Python, the first parameter of the constructor (__init__) is typically named self, which refers to the instance of the class that is being created. This parameter allows the constructor to initialize attributes specific to that object. B. super-class constructor is invoked implicitly during constructor execution This is also correct, but it requires some clarification. In Python, if a class inherits from another class and you do not explicitly call the superclass's constructor using super(), the superclass's constructor will not be called. However, if you explicitly call it, Python provides a straightforward way to invoke the superclass constructor. So while it's not automatically invoked (like in some other languages), Python makes this explicit through the use of super(). The incorrect answers are: C. the constructor can be invoked directly under strictly defined circumstances: Although you can technically invoke a constructor (the __init__ method) manually on an already existing object, this is not typical behavior and not generally recommended as a practice. Constructors are meant to initialize new objects, not reinitialize existing ones. D. the constructor cannot use the default values of the parameters: This is incorrect because constructors in Python can use default parameter values just like any other function. You can assign default values to parameters in the __init__ method.

#8. Which of the following snippets will execute without raising any unhandled exceptions? (Choose two.) A. try: x = 1 except: x = x + 1 else: x = x + 2 B. try: print(-1 / 1) except: print(0 / 1) else: print(1 / 1) C. try: x = y + 1 except (NameError, SystemError): x = y + 1 else: y = x D. try: x = 1 / 0 except NameError: x = 1 / 1 else: x = x + 1

Explanation: The correct answers are: A, It will run successfully because no exceptions occur. The else block is executed after the try block finishes without an exception, so x = x + 2, and x becomes 3. B. The try block executes without error (because -1 / 1 is a valid operation), so the else block is executed, printing 1.0. The incorrect answers are: C. The try block raises a NameError because y is not defined. The except (NameError, SystemError) block catches the exception and attempts to execute the same operation (x = y + 1), which again causes the same NameError, but it is caught and the program does not crash. D. The try block raises a ZeroDivisionError because 1 / 0 is invalid. The except block expects a NameError, but since the exception raised is a ZeroDivisionError, it will not be caught, leading to an unhandled exception. Thus, it will not execute successfully.

#17. Which of the following expressions evaluate to True? (Choose two.) A. 'in' in 'in' B. 'in' in 'Thames' C. 'in not' in 'not' D. 't'.upper() in 'Thames'

Explanation: The correct answers are: A. 'in' in 'in' This is True because the string 'in' is exactly present in the string 'in'. D. 't'.upper() in 'Thames' This is True because 't'.upper() returns 'T', and 'T' is present in the string 'Thames'. The incorrect answers are: B. 'in' in 'Thames': This is False because the substring 'in' is not found in the string 'Thames'. C. 'in not' in 'not': This is False because 'in not' is not a substring of 'not'.

#54. What is true about Python class constructors? (Choose two.) A. the constructor's first parameter must always be named self B. there can be only one constructor in a Python class C. the constructor cannot be invoked directly under any circumstances D. the constructor cannot return a result other than None

Explanation: The correct answers are: B: "There can be only one constructor in a Python class." This statement is true. Python classes can have only one __init__ method. Unlike some languages, Python does not support multiple constructors (overloading the constructor with different parameter lists). If you define more than one __init__ method, the latest definition will override the previous one. D: "The constructor cannot return a result other than None." This statement is true. In Python, the __init__ method is expected to return None. Attempting to return any other value will raise a TypeError. The purpose of __init__ is to initialize the instance, not to return a value, so it should always implicitly or explicitly return None. The incorrect answers are: A: "The constructor's first parameter must always be named self." This statement is false. In Python, the first parameter of the __init__ method (or any instance method) is conventionally named self, but it does not have to be named self. You can name it anything, like this, obj, or any valid variable name, as long as it refers to the instance. Although it works with any name, using self is a strong convention in Python to maintain readability and consistency. C: "The constructor cannot be invoked directly under any circumstances." This statement is mostly false. While the constructor (__init__) is typically invoked automatically when you create an instance of a class (e.g., obj = MyClass(10)), it can technically be called directly if an instance already exists (e.g., obj.__init__(value)). However, directly invoking __init__ on the class itself without creating an instance (e.g., MyClass.__init__(MyClass, 10)) will result in an error. Thus, the statement would only be true if we interpret it as "the constructor cannot be directly invoked to create an instance," but

#47. Which of the following expressions evaluate to True? (Choose two.) A. '1' + '1' + '1' < '1' * 3' B. 121 + 1 != '1' + 2 * '2' C. 'AbC'.lower() < 'AB' D.'3.14' != str(3.1415)

Explanation: The correct answers are: B: 121 + 1 != '1' + 2 * '2' 121 + 1 equals 122 (an integer). '1' + 2 * '2': 2 * '2' results in '22' (string repetition). '1' + '22' results in '122' (a string). 122 != '122' is True because they are of different types (integer vs. string). D: '3.14' != str(3.1415) str(3.1415) converts 3.1415 to the string '3.1415'. Comparing '3.14' != '3.1415': This is True because '3.14' is not equal to '3.1415'. So, D is True. The incorrect answers are: A: '1' + '1' + '1' < '1' * 3 '1' + '1' + '1' results in the string '111'. '1' * 3 repeats the string '1' three times, resulting in '111'. '111' < '111' is False because they are equal. C: 'AbC'.lower() < 'AB' 'AbC'.lower() converts 'AbC' to 'abc'. Comparing 'abc' < 'AB': In lexicographical order, lowercase letters have higher ASCII values than uppercase letters, so 'abc' is not less than 'AB'. Therefore, 'abc' < 'AB' is False.

#25. Assuming that the following piece of code has been executed successfully, which of the expressions evaluate to True? (Choose two.) class A: VarA = 1 def __init__(self): self.prop_a = 1 class B(A): VarA = 2 def __init__(self): super().__init__() self.prop_b = 2 obj_a = A() obj_aa = A() obj_b = B() obj_bb = obj_b A. A.VarA == 1 B. isinstance(obj_b,A) C. B.VarA == 1 D. obj_a is obj_aa

Explanation: The correct answers are: A. A.VarA == 1 This evaluates to True because VarA in class A is defined as 1. B. isinstance(obj_b, A) This evaluates to True because obj_b is an instance of class B, and B is a subclass of A. So, obj_b is also considered an instance of A due to inheritance. The incorrect answers are: C. B.VarA == 1 This is incorrect because B.VarA is actually set to 2, not 1. In the class B, VarA is explicitly defined as 2, so the expression B.VarA == 1 evaluates to False. D. obj_a is obj_aa This is incorrect because obj_a and obj_aa are two separate instances of the class A. Even though they are both instances of A, they are two distinct objects, so obj_a is obj_aa evaluates to False. The is operator checks for object identity (whether two references point to the exact same object in memory), not just equality.

#27. Which of the following lines of code will work flawlessly when put independently inside the add_new() method in order to make the snippet's output equal to [0, 1, 1]? (Choose two.) class MyClass: def __init__(self, initial): self.store = initial def put(self, new): self.store.append(new) def get(self): return self.store def dup(self): # insert the line of code here Object = MyClass([0]) Object.put(1) Object.dup() print(Object.get()) A. self.put(self.store[1]) B. self.put(self.get()[-1]) C. self.put(store[1]) D. put(self.store[1])

Explanation: The correct answers: A. self.put(self.store[1]) self.store[1] references the second element in the list (1), and self.put() appends it to the list. This would result in [0, 1, 1]. B. self.put(self.get()[-1]) self.get() returns the store list, and [-1] accesses the last element in that list (1). self.put() appends this value (1) to the list, resulting in [0, 1, 1]. The incorrect answers: C. self.put(store[1]) This will not work because store without self is undefined in this context. It should be self.store. D. put(self.store[1]) This is incorrect because put() is being called without the proper self reference. It should be self.put().

#77. Which of the following lambda function definitions are correct? (Choose two.) A. lambda lambda: lambda * lambda B. lambda x : def fun(x): return x C. lambda : 3.1415 D. lambda x : None

Explanation: A lambda function in Python is an anonymous function that can have zero or more arguments but must consist of a single expression. The correct answers are: C. lambda : 3.1415 This is a valid lambda function with no arguments (lambda :) that always returns 3.1415. D. lambda x : None This is a valid lambda function that takes one argument (x) and always returns None. The incorrect answers are: A. lambda lambda: lambda * lambda The syntax is invalid because lambda is a reserved keyword in Python and cannot be used as a variable name. This will result in a SyntaxError. B. lambda x : def fun(x): return x The syntax is invalid because lambda functions cannot contain statements like def. This will result in a SyntaxError.

#96: An alternative name for a data structure called a stack is: FIFO LIFO FOLO

Explanation: A stack operates in a LIFO (Last In, First Out) manner, meaning the last item added is the first to be removed. FIFO (First In, First Out) applies to a queue, not a stack. FOLO is not a standard data structure term. Correct answer is: B. LIFO

#7. What is the expected behavior of the following code? s = '2A' try: n = int(s) except ValueError: n = 2 except ArithmeticError: n = 1 except: n = 0 print(n) A. the code is erroneous and it will not execute B. it outputs 1 C. it outputs 2 D. it outputs 0

Explanation: Attempting Conversion with int(s): The code tries to convert s = '2A' to an integer using int(s). Since '2A' is not a valid integer representation, this raises a ValueError. Exception Handling: The ValueError is caught by the except ValueError block. Inside this block, n is set to 2. Printing the Value of n: The code proceeds to the print(n) statement. Since n was set to 2 in the ValueError block, the output will be 2. The correct answer is: C. it outputs 2

#60. What is the expected behavior of the following code? class Super: def make(self): return 0 def doit(self): return self.make() class Sub_A(Super): def make(self): return 1 class Sub_B(Super): def make(self): return 2 a = Sub_A() b = Sub_B() print(a.doit() + b.doit()) A. it raises an exception B. it outputs 2 C. it outputs 3 D. it outputs 1

Explanation: Class Super: The Super class has two methods: make(self), which returns 0. doit(self), which calls self.make() and returns the result. Class Sub_A: Sub_A inherits from Super and overrides the make method to return 1 instead of 0. Class Sub_B: Sub_B also inherits from Super and overrides the make method to return 2. Creating Instances: a = Sub_A() creates an instance of Sub_A. b = Sub_B() creates an instance of Sub_B. Calling Methods: a.doit() calls the doit method on the a instance of Sub_A. Since a is an instance of Sub_A, self.make() in doit() refers to Sub_A's make method, which returns 1. So, a.doit() returns 1. b.doit() calls the doit method on the b instance of Sub_B. Since b is an instance of Sub_B, self.make() in doit() refers to Sub_B's make method, which returns 2. So, b.doit() returns 2. Calculating the Result: print(a.doit() + b.doit()) will print the sum of a.doit() and b.doit(), which is 1 + 2 = 3. The correct answer is: C. it outputs 3

#53. What is the expected behavior of the following code? class Class: Var = 0 def __init__(self, var): self.var = var Class.Var += 1 object_1 = Class(1) object_2 = Class(2) print(Class.Var + object_1.var + object_2.var) A. it outputs 3 B. it outputs 2 C. it outputs 5 D. it raises an exception

Explanation: Class Variable (Var): Class.Var is a class variable initially set to 0. Each time an instance of Class is created, Class.Var is incremented by 1 in the __init__ method. Instance Creation: object_1 = Class(1): The __init__ method sets object_1.var to 1. Class.Var is incremented from 0 to 1. object_2 = Class(2): The __init__ method sets object_2.var to 2. Class.Var is incremented from 1 to 2. Final Calculation: Class.Var + object_1.var + object_2.var evaluates as follows: Class.Var is 2 (since it was incremented twice). object_1.var is 1. object_2.var is 2. Therefore, the expression Class.Var + object_1.var + object_2.var evaluates to: 2 + 1 + 2 = 5 The correct answer is: C. it outputs 5

#28. What is the expected behavior of the following code? class Class: Variable = 0 def __init__(self): self.value = 0 object_1 = Class() Class.Variable += 1 object_2 = Class() object_2.value += 1 print(object_2.Variable + object_1.value) A. it raises an exception B. it outputs 2 C. it outputs 0 D. it outputs 1

Explanation: Class.Variable = 0 This is a class-level variable, shared by all instances of the class. object_1 = Class() A new instance of Class is created. The instance variable self.value is initialized to 0, but the class variable Class.Variable remains 0. Class.Variable += 1 This increments the class-level variable Class.Variable to 1. All instances of Class will now see Class.Variable as 1. object_2 = Class() Another instance of Class is created. Like object_1, its self.value is initialized to 0. The class variable Class.Variable remains 1. object_2.value += 1 The instance variable value for object_2 is incremented by 1, so object_2.value is now 1. print(object_2.Variable + object_1.value) object_2.Variable accesses the class variable Class.Variable, which is 1 (not the instance variable, but the class-level one). object_1.value is the instance variable value of object_1, which is still 0 because we didn't change object_1.value. Therefore, the final print statement evaluates to: 1 (from object_2.Variable) + 0 (from object_1.value) = 1 The correct answer is: D. it outputs 1

#61. What is the expected output of the following code if the file named non_zero_length_existing_text_file is a non-zero length file located inside the working directory? try: f = open('non_zero_length_existing_text_file', 'rt') d = f.read(1) print(len(d)) f.close() except IOError: print(-1) A. an errno value corresponding to file not found B. 1 C. 0 D. -1

Explanation: File Opening: The code tries to open a file named 'non_zero_length_existing_text_file' in read text mode ('rt'). If this file exists in the working directory and has a non-zero length, it will open successfully without raising an IOError. Reading the File: d = f.read(1) reads 1 character from the file. Since the file has a non-zero length, f.read(1) will successfully read the first character. d will contain this single character, and thus, len(d) will be 1. Printing the Length: print(len(d)) will output the length of d, which is 1. Closing the File: f.close() closes the file after reading. Exception Handling: Since the file exists and is successfully read, no IOError will be raised, so the except block will not execute. The correct answer is: B. 1

#24. Assuming that the following inheritance set is in force, which of the following classes are declared properly? (Choose two.) class A: pass class B(A): pass class C(A): pass A. class Class_3(A,C): pass B. class Class_2(B,C): pass C. class Class_4(A,B): pass D. class Class_1(C,B): pass

Explanation: Given Hierarchy: A |__B |__C The correct answers are: B. class Class_2(B, C): pass This is valid. Python allows multiple inheritance where B and C are derived from the same base class A. Since both B and C derive from A, Class_2 can inherit from B and C. Python will use the method resolution order (MRO) to determine the hierarchy. So, this is fine. Valid: B and C both inherit from A. The MRO can resolve this hierarchy as: Class_2 -> B -> C -> A -> object No conflicts exist here. D. class Class_1(C, B): pass Valid: C and B both inherit from A. The MRO can resolve this hierarchy as: Class_1 -> C -> B -> A -> object No conflicts exist here. The incorrect answers are: A. class Class_3(A, C): pass This is incorrect because both A and C inherit from the same base class A, and Python doesn't support this type of multiple inheritance where both are directly derived from A. Invalid: This creates a direct conflict because A is a superclass of C. Python's MRO cannot linearize the hierarchy in this case. The order A -> C cannot satisfy the constraints of the MRO algorithm. C. class Class_4(A, B): pass Invalid: B is already a subclass of A. Declaring A before B creates an ambiguous hierarchy since A is redundantly declared as a base class.

#56. Assuming that the code below has been executed successfully, which of the following expressions evaluate to True? (Choose two.) class Class: data = 1 def __init__(self, value): self.prop = self.var = value Object = Class(2) A. len(Object.__dict__) == 2 B. 'var' in Object.__dict__ C. 'var' in Class.__dict__ D. 'data' in Object.__dict__

Explanation: Let's analyze the attributes and methods of both Object (an instance of Class) and Class itself after this code is executed. Class Attributes: Class.data is a class attribute with a value of 1. Class.__dict__ will contain this attribute as part of the class's definition. Instance Attributes: When Object (an instance of Class) is created with Class(2), the __init__ method assigns self.prop and self.var to the value 2. Therefore, Object will have two instance attributes, prop and var, each set to 2. Object.__dict__ will contain {'prop': 2, 'var': 2}. The correct answers are: A: len(Object.__dict__) == 2 Object.__dict__ contains two attributes: {'prop': 2, 'var': 2}. The length of Object.__dict__ is therefore 2. This statement is True. B: 'var' in Object.__dict__ Object.__dict__ contains the attribute 'var' with a value of 2. This statement is True. The incorrect answers are: C: 'var' in Class.__dict__ Class.__dict__ contains only class attributes and methods, not instance attributes. Since var is an instance attribute created by __init__, it will not be in Class.__dict__. This statement is False. D: 'data' in Object.__dict__ data is a class attribute, so it resides in Class.__dict__, not in the instance's __dict__. Object.__dict__ will not contain data. This statement is False.

#90. What is the expected behavior of the following code? class Super: def make(self): pass def doit(self): return self.make() class Sub_A(Super): def make(self): return 1 class Sub_B(Super): pass a = Sub_A() b = Sub_B() print(a.doit() + b.doit()) A. it outputs 0 B. it outputs 1 C. it raises an exception D. it outputs 2

Explanation: Step-by-Step Breakdown: Class Definitions: Super: Super defines two methods: make(self) is an empty method (pass). doit(self) calls self.make(). Sub_A: Sub_A inherits from Super and overrides the make(self) method to return 1. Sub_B: Sub_B inherits from Super but does not override the make(self) method, so it uses the unimplemented make method from Super. Object Instantiation and Method Calls: a = Sub_A(): Creates an instance of Sub_A. b = Sub_B(): Creates an instance of Sub_B. a.doit(): Calls doit() on the Sub_A instance. Inside doit(), it calls self.make(), which resolves to Sub_A.make(). This method returns 1. b.doit(): Calls doit() on the Sub_B instance. Inside doit(), it calls self.make(). Since Sub_B does not override make(), the call resolves to Super.make(), which is not implemented (pass). This causes Super.make() to implicitly return None. Adding Results: The expression a.doit() + b.doit() evaluates to 1 + None. In Python, adding an integer (1) to None is invalid and raises a TypeError. The correct answer is: C. it raises an exception

#92. What is the expected behavior of the following code? class Upper: def method(self): return 'upper' class Lower(Upper): def method(self): return 'lower' Object = Upper() print(isinstance(Object, Lower), end=' ') print(Object.method()) A. False lower B. False upper C. True upper D. True lower

Explanation: Step-by-Step Breakdown: Class Definitions: Upper: Defines a method that returns the string 'upper'. Lower: Inherits from Upper and overrides the method to return the string 'lower'. Creating an Object: Object = Upper() creates an instance of the Upper class. Object is an instance of Upper, not Lower. isinstance(Object, Lower): The isinstance function checks if Object is an instance of the Lower class or any of its subclasses. Since Object is explicitly an instance of Upper, and Upper is not a subclass of Lower, this evaluates to False. Object.method(): Object.method() calls the method defined in the Upper class because Object is an instance of Upper. This method returns 'upper'. print Statement: The first part of the print statement outputs False (from isinstance). The second part outputs upper (from Object.method()). The end=' ' ensures the two outputs are on the same line, separated by a space. The correct answer is: B. False upper

#91. What is the expected behavior of the following code? my_tuple = (1, 2, 3) try: my_tuple[3] = my_tuple[2] except IndexError as error: x = error except Exception as exception: x = exception else: x = None print(x) A. outputs list assignment index out of range B. it outputs None C. it outputs 'tuple' object does not support item assignment D. the code is erroneous and it will not execute

Explanation: Step-by-Step Breakdown: Defining the Tuple: my_tuple = (1, 2, 3) creates an immutable tuple with elements (1, 2, 3). Attempt to Modify the Tuple: my_tuple[3] = my_tuple[2] tries to assign a value to the 4th index (index 3) of the tuple. Tuples in Python are immutable, meaning you cannot modify their elements after creation. Attempting to assign a value to any element of a tuple raises a TypeError with the message: 'tuple' object does not support item assignment. try...except...else Handling: The try block raises a TypeError. The except IndexError block is skipped because the error is not an IndexError. The except Exception block catches the TypeError, as Exception is a base class for all exceptions. The exception object (exception) is assigned to x. print(x) Outputs: The exception object x contains the error message from the TypeError. When printed, it outputs 'tuple' object does not support item assignment. The correct answer is: C. it outputs 'tuple' object does not support item assignment

#76. Which of the following lines of code will work flawlessly when put independently inside the inc() method in order to make the snippet's output equal to 3? (Choose two.) class MyClass: Var = 0 def __init__(self): MyClass.Var += 1 self.prop = MyClass.Var def get(self): return self.prop def put(self, val): self.prop = val def inc(self, val): # insert the line of code here Object = MyClass() Object.inc(2) print(Object.get()) A. put(self.prop + val) B. self.put(self.prop + val) C. self.put(self.get() + val) D. self.put(get() + val)

Explanation: Step-by-Step Breakdown: Initialization: When Object = MyClass() is created, the __init__ method increments MyClass.Var to 1 and sets self.prop = 1. Object.inc(2): The inc() method takes val as an argument, and one of the provided options will be inserted to modify self.prop to 3. print(Object.get()): Calls Object.get() to return self.prop. To get the output 3, the inc() method must increment self.prop by val (2 in this case). The correct answers are: B. self.put(self.prop + val) self.put() is a method of MyClass that updates self.prop. self.prop + val calculates 1 + 2 = 3 and assigns it to self.prop. C. self.put(self.get() + val) self.get() returns the current value of self.prop, which is 1. self.get() + val calculates 1 + 2 = 3. self.put(3) assigns 3 to self.prop. The incorrect answers are: A. put(self.prop + val) The method call put() is not defined within the current scope (no self). It will raise an error: NameError: name 'put' is not defined. D. self.put(get() + val) The method get() is not defined in the current scope (missing self). It will raise an error: NameError: name 'get' is not defined.

#79. What is the expected output of the following code? import sys import math b1 = type(dir(math)[01]) is str b2 = type(sys.path[-1]) is str print(b1 and b2) A. None B. True C. 0 D. False

Explanation: Step-by-Step Breakdown: dir(math)[01] dir(math): Returns a list of all attributes and methods in the math module. Example: ['__doc__', '__loader__', ..., 'sin', 'sqrt', 'tan', 'trunc']. [01]: The syntax 01 is invalid in Python because numbers with leading zeros are not allowed in modern Python (since Python 3). This will raise a SyntaxError. If corrected to [0] or [1]: [0] equals the string '__doc__' [1] equals the string '__loader__' sys.path[-1] sys.path: A list of strings representing the directories that Python searches for modules. sys.path[-1]: Retrieves the last item in the sys.path list, which is typically a string (e.g., the current working directory or an empty string). type(sys.path[-1]) is str: Evaluates to True if the last element of sys.path is a string, which is typically the case. The correct answer is: With corrected line to: b1 = type(dir(math)[0]) is str or b1 = type(dir(math)[1]) is str B. True

#88. What is the expected behavior of the following code? s = '2A' try: n = int(s) except TypeError: n = 3 except LookupError: n = 2 except: n = 1 print(n) A. it outputs 2 B. it outputs 3 C. the code is erroneous and it will not execute D. it outputs 1

Explanation: Step-by-Step Breakdown: s = '2A': s is assigned the string '2A', which is not a valid base-10 integer. int(s): When int(s) is called, Python attempts to convert '2A' to an integer in base 10. This raises a ValueError because '2A' is not a valid base-10 number. except Blocks: The try block has three except clauses, but none of them explicitly handle a ValueError. Here's what happens: except TypeError: Skipped, because the error is not a TypeError. except LookupError: Skipped, because the error is not a LookupError. except: This is a catch-all block that handles all exceptions not explicitly handled by earlier except clauses. Since ValueError is not caught by the first two blocks, it is caught here. n = 1: The catch-all except block is executed, assigning 1 to n. print(n): Finally, n is printed, which outputs 1. The correct answer is: D. it outputs 1

#22. What is the expected behavior of the following code? class Super: def make(self): return 0 def doit(self): return self.make() class Sub_A(Super): def make(self): return 1 class Sub_B(Super): pass a = Sub_A() b = Sub_B() print(a.doit() + b.doit()) A. it outputs 1 B. it outputs 0 C. it raises an exception D. it outputs 2

Explanation: Sub_A class: Sub_A inherits from Super. Sub_A overrides the make() method, so whenever you call make() on an instance of Sub_A, it will return 1 (as defined in Sub_A). Sub_B class: Sub_B inherits from Super. Sub_B does not override the make() method, so when you call make() on an instance of Sub_B, it will call the make() method from the Super class, which returns 0. a.doit(): When you call a.doit(), you are calling the doit() method from Super, which in turn calls self.make(). Since a is an instance of Sub_A, self.make() calls the make() method from Sub_A, which returns 1. b.doit(): When you call b.doit(), you are calling the doit() method from Super, which calls self.make(). Since b is an instance of Sub_B, and Sub_B does not override make(), self.make() calls the make() method from Super, which returns 0. Final Result: a.doit() returns 1 (from Sub_A's make()). b.doit() returns 0 (from Super's make()). Adding them together: 1 + 0 = 1. Correct answer is: A. It outputs 1

#5. With regards to the directory structure below, select the proper forms of the directives in order to import module_c. (Choose two.) pypack (dir) ├── upper (dir) │ ├── lower (dir) │ │ └── module_c.py (file) │ └── module_b.py (file) └── module_a.py (file) A. from pypack.upper.lower import module_c B. import pypack.upper.lower.module_c C. import upper.module_c D. import upper.lower.module_c

Explanation: The correct answers are: A. from pypack.upper.lower import module_c This is correct. It imports module_c from the directory pypack.upper.lower. B. import pypack.upper.lower.module_c This is also correct. It imports the full path pypack.upper.lower.module_c. The incorrect answers are: C. import upper.module_c This is incorrect because you must start with pypack as the top-level package. D. import upper.lower.module_c This incorrect for the same reason: upper is inside pypack, so you need to reference pypack first.

#85. What is the expected behavior of the following code? the_list = "1,2 3.split() the_string = ''.join(the_list) print(the_string.isdigit()) A. it outputs False B. it outputs True C. it outputs nothing D. it raises an exception

Explanation: The code contains a syntax error: "1,2 3.split() is not a valid Python statement. There is a missing closing quote for the string and a misplaced method call (split()). This will raise a SyntaxError at runtime. The correct answer is: D. it raises an exception Bonus Explanation: If the code were intended to split the string "1,2 3" and join the resulting elements into a single string: the_list = "1,2 3".split() the_string = ''.join(the_list) print(the_string.isdigit()) Step-by-Step Bonus Explanation: "1,2 3".split(): Splits the string into a list of substrings using spaces as delimiters. Result: ['1,2', '3']. ''.join(the_list): Joins the elements of the list into a single string without spaces. Result: '1,23'. the_string.isdigit(): Checks whether all characters in the string '1,23' are digits. Since the string contains a comma, it returns False, so A. It outputs False would be the correct answer.

#65. What is the expected output of the following code if existing_file is the name of a file located inside the working directory? try: f = open('existing file', 'w') print(1, end=' ') except IOError as error: print(error.errno, end=' ') print(2, end=' ') else: f.close() print(3, end=' ') A. 1 2 3 B. 1 2 C. 1 3 D. 2 3

Explanation: The code tries to open a file named 'existing file' in write mode ('w'). Since the file doesn't exist (because it doesn't have the underscore that the existing file's filename contains), the file is created on the system. Then the following happens: The print(1, end=' ') statement inside the try block is executed, printing 1. Since no exception occurs, the except block is skipped. The else block is executed, which closes the file and then prints 3. Thus, the output will be: 1 3 The correct answer is: C. 1 3

#11. What is the expected behavior of the following code? my_list = [1, 2, 3] try: my_list[3] = my_list[2] except BaseException as error: print(error) A. it outputs error B. it outputs C. the code is erroneous and it will not execute D. it outputs list assignment index out of range

Explanation: The code will raise an IndexError because you are trying to assign a value to an index (3) that is out of range for the list my_list (which only has indices 0, 1, and 2). The except BaseException as error block catches any exception, including IndexError. Inside the except block, print(error) will print the error message associated with the exception. Therefore, the expected behavior is: D. it outputs list assignment index out of range

#20. A property that stores information about a given class's super-classes is named: A. __bases__ B. __super__ C. __upper__ D. __ancestors__

Explanation: The correct answer is: A. __bases__ The __bases__ property is a tuple containing references to a class's superclasses (i.e., the classes from which it inherits). It can be used to inspect the inheritance hierarchy in Python. For example: class A: pass class B(A): pass print(B.__bases__) # Output: (<class '__main__.A'>,) The incorrect answers are: B. __super__: This is not a valid Python property. However, super() is a function used to call methods from a superclass in the method resolution order (MRO). C. __upper__: This does not exist in Python and has no special meaning. D. __ancestors__: This is also not a valid Python property. The correct property to check superclasses is __bases__.

#6. Which one of the platform module functions should be used to determine the underlying platform name? A. platform.processor() B. platform.uname() C. platform.python_version() D. platform.platform()

Explanation: The correct answer is: D. platform.platform() This function returns a string that describes the underlying platform, including the system name, release, and version. The incorrect answers are: platform.processor() This returns the processor name. B. platform.uname() This returns a tuple with system-related information, but not specifically the platform name. C. platform.python_version() This returns the Python version, not the platform name.

#29. What is true about Object-Oriented Programming in Python? (Choose two.) A. encapsulation allows you to hide a whole class inside a package B. a class is a recipe for an object C. each object of the same class can have a different set of properties D. the arrows on a class diagram are always directed from a superclass towards its subclass

Explanation: The correct answers are: B. a class is a recipe for an object This is true. A class in Python is essentially a blueprint or recipe for creating objects. It defines the structure and behavior (methods) that the objects created from it will have. C. each object of the same class can have a different set of properties This is also true. Although all objects of the same class share the same methods and class-level properties, each object can have its own unique set of instance properties (attributes), which can differ based on how the object is initialized or modified. The incorrect answers are: A. encapsulation allows you to hide a whole class inside a package This is incorrect because encapsulation in OOP refers to hiding the internal details of an object and restricting access to certain attributes and methods. Encapsulation typically happens at the level of attributes and methods, not at the package level. D. the arrows on a class diagram are always directed from a superclass towards its subclass This is incorrect. In UML (Unified Modeling Language) diagrams, arrows typically point from the subclass towards the superclass, indicating that the subclass is inheriting from the superclass.

#55. What is true about Object-Oriented Programming in Python? (Choose two.) A. an object is a recipe for a class B. the arrows on a class diagram are always directed from a superclass towards its subclass C. encapsulation allows you to protect some data from uncontrolled access D. inheritance is the relation between a superclass and a subclass

Explanation: The correct answers are: C: "Encapsulation allows you to protect some data from uncontrolled access." This statement is true. Encapsulation is one of the core principles of OOP. It allows a class to restrict access to its internal data (attributes) and only expose certain parts through methods. In Python, this can be achieved through the use of private variables (e.g., prefixing with an underscore, _variable or __variable) and providing getter and setter methods. This helps protect the data from uncontrolled or unintended access and modification. D: "Inheritance is the relation between a superclass and a subclass." This statement is true. Inheritance is a fundamental concept in OOP that defines a relationship between a superclass (parent class) and a subclass (child class). The subclass inherits attributes and methods from the superclass, allowing code reuse and the creation of a hierarchical relationship between classes. The incorrect answers are: A: "An object is a recipe for a class." This statement is false. In Object-Oriented Programming (OOP), a class is like a recipe or blueprint for creating objects. A class defines the structure and behavior (attributes and methods) that the objects (instances of the class) will have. An object is an instance of a class, not the recipe itself. B: "The arrows on a class diagram are always directed from a superclass towards its subclass." This statement is false. In Unified Modeling Language (UML) class diagrams, the arrows generally point from a subclass towards its superclass, not the other way around. This shows the "is-a" relationship from the perspective of the subclass. For example, an arrow from Dog to Animal would indicate that Dog is a subclass of Animal.

#21. Assuming that the code below has been executed successfully, which of the following expressions evaluate to True? (Choose two.) class Class: var = data = 1 def __init__(self, value): self.prop = value Object = Class(2) A. 'var' in Class.__dict__ B. 'data' in Object.__dict C. len(Class.__dict__) == 1 D. 'data' in Class.__dict__

Explanation: The correct answers are: 'var' in Class.__dict__ This is True because var is a class attribute, and class attributes are stored in the class's __dict__. D. 'data' in Class.__dict__ This is True because data is also a class attribute, and it is defined in the same way as var. Both var and data will be present in Class.__dict__. The incorrect answers are: B. 'data' in Object.__dict: This is False because data is a class-level attribute, not an instance-level attribute. Only instance attributes are stored in Object.__dict__. C. len(Class.dict) == 1: This is False because Class.__dict__ contains more than just the single class attribute var. It also contains the class methods (like __init__) and other internal attributes (e.g., __module__, __doc__).

#13. Which of the following expressions evaluate to True? (Choose two.) A. 'xYz'.lower() > 'XY' B. '8'+'8' ! = 2 * '8' C. float ('3.14') == str('3.' + '14') D. 121 + 1 == int('1' + 2 * '2')

Explanation: The correct answers are: 'xYz'.lower() > 'XY' True: 'xYz'.lower() will convert the string to 'xyz', and when comparing it with 'XY', Python compares strings lexicographically (based on Unicode values). Lowercase letters have higher Unicode values than uppercase letters, so 'xyz' > 'XY' evaluates to True. D. 121 + 1 == int('1' + 2 * '2') True: 121 + 1 results in 122. On the right-hand side, '1' + 2 * '2' results in the string '122', and int('122') converts it to the integer 122. Therefore, 121 + 1 == int('1' + 2 * '2') evaluates to True. The incorrect answers are: B. '8' + '8' != 2 * '8' False: '8' + '8' results in the string '88', and 2 * '8' results in the string '88'. Therefore, '8' + '8' == 2 * '8' evaluates to True, making the expression '8' + '8' != 2 * '8' evaluate to False. C. float('3.14') == str('3.' + '14') False: float('3.14') results in the floating-point number 3.14, while str('3.' + '14') results in the string '3.14'. Since 3.14 is a float and '3.14' is a string, the comparison 3.14 == '3.14' is False.

#3. A Python package named pypack includes a module named pymod.py which contains a function named pyfun(). Which of the following snippets will let you invoke the function? (Choose two.) A. from pypack.pymod import pyfun pyfun() B. import pypack pymod.pyfun() C. from pypack import * pyfun() D. import pypack import pypack.pymod pypack.pymod.pyfun()

Explanation: The correct answers are: A. from pypack.pymod import pyfun pyfun() This imports the pyfun function directly from the pymod module in the pypack package, allowing you to call pyfun() directly. D. import pypack import pypack.pymod pypack.pymod.pyfun() Here, you import both the pypack package and the pypack.pymod module, then call the pyfun() function using the full path pypack.pymod.pyfun(). The incorrect answers are: B. import pypack pymod.pyfun() This is incorrect because import pypack alone does not automatically import pymod; you'd need to import pypack.pymod. C. from pypack import * pyfun() This is incorrect because from pypack import * does not necessarily import everything from the submodules unless it's explicitly stated in the package's __init__.py.

#82. Which of the following invocations are valid? (Choose two.) A. "python".index("th") B. rfind("python","r") C. "python".sort() D. sorted("python")

Explanation: The correct answers are: A. "python".index("th") The index() method is used to find the starting index of a substring within a string. "python".index("th") returns 2, as the substring "th" starts at index 2 in the string "python". Example: result = "python".index("th") print(result) # Outputs: 2 D. sorted("python") The sorted() function returns a new sorted list containing the characters of the string "python" in alphabetical order. Example: result = sorted("python") print(result) # Outputs: ['h', 'n', 'o', 'p', 't', 'y'] The incorrect answers are: B. rfind("python","r") The rfind() method is called on a string, but this code uses invalid syntax. Correct usage: "python".rfind("r") searches for the substring "r" from the right side of the string "python". Since "r" is not found, it would return -1. C. "python".sort() Strings in Python do not have a sort() method. Sorting is only applicable to mutable sequences like lists.

#95: Which of the following are examples of Python built-in concrete exceptions? (Select two answers.) A. ImportError B. ArithmeticError C. BaseException D. IndexError

Explanation: The correct answers are: A. ImportError: This is also a built-in concrete exception, so it can be a valid option depending on the context. If the task is strictly looking for two, then the inclusion of IndexError and BaseException typically takes precedence as they represent general and concrete exceptions. D. IndexError This is a built-in exception raised when a sequence (like a list or tuple) is accessed with an out-of-range index. It is concrete because it is directly raised and used in exception handling. The incorrect answers are: B. ArithmeticError Abstract: No. While ArithmeticError is a built-in exception, it is a base class (not concrete) for more specific arithmetic-related exceptions like ZeroDivisionError or OverflowError. Not correct in this context. C. BaseException While BaseException is concrete and usable, it is generally not recommended for most exception handling scenarios because it is too broad. It includes exceptions like SystemExit, KeyboardInterrupt, and GeneratorExit, which are not typical runtime errors.' For regular error handling, you should catch exceptions derived from Exception instead of BaseException.

#33. What is true about lambda functions? (Choose two.) A. they are called anonymous functions B. they cannot return the None value as a result C. they must contain the return keyword D. they must have a non-zero number of parameters

Explanation: The correct answers are: A. They are called anonymous functions This is true. Lambda functions are indeed called anonymous functions because they are defined without a formal name. D. They must have a non-zero number of parameters This is accurate as well. Lambda functions in Python require at least one parameter to define the expression within them. The incorrect answers are: B. They cannot return the None value as a result This is not correct because lambda functions can technically return None if their expression results in None. C. They must contain the return keyword This is incorrect, as lambda functions do not include an explicit return keyword; the expression itself is implicitly returned.

#72. Which one of the platform module functions should be used to determine the underlying OS version? A. platform.processor() B. platform.version() C. platform.python_version() D. platform.python_version_tuple()

Explanation: The correct answers is: B. platform.version() This function returns the operating system's version as a string. The incorrect answers are: A. platform.processor() This function returns the processor name (e.g., 'x86_64' or 'AMD64'). C. platform.python_version() This function returns the Python version as a string. Example: '3.9.7'. D. platform.python_version_tuple() This function returns the Python version as a tuple of strings. Example: ('3', '9', '7').

#93. With regards to the directory structure below, select the proper forms of the directives in order to import module_a. (Choose two.) pypack (dir) │ ├── upper (dir) │ └── lower (dir) │ └── module_c.py (file) │ ├── module_b.py (file) └── module_a.py (file) A. import pypack.module_a B. import module_a from pypack C. import module_a D. from pypack import module_a

Explanation: The correct answers are: A. import pypack.module_a If pypack is a package, this import is valid. It allows you to explicitly access module_a from the pypack package. D. from pypack import module_a If pypack is a package, this is valid syntax to import module_a from the pypack package. The incorrect answers are: B. import module_a from pypack This is not valid Python syntax. The correct syntax would be from pypack import module_a. C. import module_a This import will fail unless module_a.py is explicitly in the Python path. Since the directory structure does not suggest that module_a.py is globally accessible or in the same directory as the script, this cannot be guaranteed.

#81. What is true about Python class constructors? (Choose two.) A. the constructor is a method named __init__ B. there can be more than one constructor in a Python class C. the constructor must return a value other than None D. the constructor must have at least one parameter

Explanation: The correct answers are: A. the constructor is a method named __init__ In Python, the constructor method is always named __init__. It is automatically called when a new instance of a class is created. Example: class Example: def __init__(self, value): self.value = value obj = Example(10) # Automatically calls __init__ D. the constructor must have at least one parameter The __init__ method must have at least one parameter, typically self, which refers to the instance being created. Example: class Example: def __init__(self): # At least one parameter is required pass The incorrect answers are: B. there can be more than one constructor in a Python class Python classes cannot have more than one __init__ method. To simulate multiple constructors, you can use default arguments or class methods to create alternative ways of initializing the object. Example using a class method: class Example: def __init__(self, value): self.value = value @classmethod def from_string(cls, string): return cls(int(string)) obj1 = Example(10) # Regular constructor obj2 = Example.from_string("20") # Alternative constructor C. the constructor must return a value other than None The constructor does not return any value explicitly. It must return None implicitly. If you attempt to return a value explicitly from __init__, it will raise a TypeError. Example: class Example: def __init__(self): return 10 # Raises TypeError obj = Example() # Error

#64. Which of the following statements are true? (Choose two.) A. if open()'s second argument is 'r', the file must exist or open will fail B. the second open() argument describes the open mode and defaults to 'w' C. if open()'s second argument is 'w' and the invocation succeeds, the previous file's content is lost D. closing an opened file is performed by the closefile() function

Explanation: The correct answers are: A: "if open()'s second argument is 'r', the file must exist or open will fail" This statement is true. In Python, if you open a file in read mode ('r'), the file must exist. If the file does not exist, open() will raise a FileNotFoundError. C: "if open()'s second argument is 'w' and the invocation succeeds, the previous file's content is lost" This statement is true. When a file is opened in write mode ('w'), if the file already exists, it is truncated to zero length, meaning all previous content is erased. The incorrect answers are: B: "the second open() argument describes the open mode and defaults to 'w'" This statement is false. The second argument in open() indeed specifies the mode, but it defaults to 'r' (read mode), not 'w'. If you don't provide a mode, open() assumes 'r'. D: "closing an opened file is performed by the closefile() function" This statement is false. The correct method to close an opened file in Python is f.close(), where f is the file object returned by open(). There is no closefile() function in Python.

#84. Assuming that the code below has been placed inside a file named code.py and executed successfully, which of the following expressions evaluate to True? (Choose two.) class ClassA: var = 1 def __init__(self, prop): prop1 = prop2 = prop class ClassB(ClassA): def __init__(self, prop): prop3 = prop ** 2 super().__init__(prop) def __str__(self): return 'Object' Object = ClassA(2) A. ClassA.__module__ == '_main_' B. len(ClassB.__bases__) == 2 C. __name__ == '__ main__' D. str(Object) == 'Object'

Explanation: The correct answers are: A: ClassA.__module__ == '_main_' As is: The __module__ attribute of a class indicates the name of the module in which the class was defined. When a script is executed directly, the module name is "__main__", not "_main_". This evaluates to False. If corrected to: ClassA.__module__ == '__main__' ClassA.__module__ will equal __main__ if the file is executed directly. This evaluates to True C: __name__ == '__ main__' The __name__ variable is set to "__main__" when the script is executed directly. Assuming the file code.py is executed as a standalone script, this evaluates to True.. The incorrect answers are: B: len(ClassB.__bases__) == 2 The __bases__ attribute of a class returns a tuple of its base classes. ClassB inherits from a single class, ClassA. Hence, len(ClassB.__bases__) == 1, not 2. This evaluates to False. D: str(Object) == 'Object' Object is an instance of ClassA, not ClassB. ClassA does not override the __str__ method, so the default behavior from object is used, which returns a string like <__main__.ClassA object at 0x...>. Therefore, this evaluates to False.

#87. Python module named pymod.py contains a variable named pyvar. Which of the following snippets will let you access the variable? (Choose two.) A. from pymod import * pyvar = 1 B. import pyvar from pymod pyvar = 1 C. from pymod import pyvar pyvar() D. import pymod pymod.pyvar = 1

Explanation: The correct answers are: A: from pymod import * pyvar = 1 from pymod import * imports all names (variables, functions, etc.) defined in the pymod module into the current namespace, including pyvar. After importing, you can access or modify pyvar directly. Note: Overwriting pyvar with pyvar = 1 will replace its value with 1 in the current namespace. D: import pymod pymod. pyvar = 1 import pymod imports the entire pymod module. You can then access pyvar as pymod.pyvar. Assigning pymod.pyvar = 1 modifies the value of pyvar within the pymod module's namespace. The incorrect answers are: B: import pyvar from pymod pyvar = 1 The syntax is invalid. The correct syntax would be from pymod import pyvar. Using import pyvar from pymod will result in a SyntaxError. C: from pymod import pyvar pyvar() pyvar is a variable, not a callable (like a function). Attempting to use pyvar() will raise a TypeError because you cannot call a variable.

#59. Assuming that the following piece of code has been executed successfully, which of the expressions evaluate to True? (Choose two.) class A: __VarA = 1 def get(self): return self.__VarA class B(A): __VarA = 2 def get(self): return self.__VarA class C(B): __VarA = 3 obj_a = A() obj_b = B() obj_c = C() A. hasattr(B, 'get') B. isinstance(obj_b,C) C. obj_c.get() == 2 D. C._C__VarA == 2

Explanation: The correct answers are: A: hasattr(B, 'get') The hasattr function checks if the B class has an attribute or method named 'get'. Since B defines a method get, hasattr(B, 'get') will return True. This statement is True. C: obj_c.get() == 2 obj_c is an instance of C, which inherits the get method from class B. The get method in B returns the value of self.__VarA. Due to Python's name mangling, self.__VarA in B refers to B._B__VarA, which is 2. So, obj_c.get() will return 2. This statement is True. The incorrect answers are: B: isinstance(obj_b, C) The isinstance function checks if obj_b is an instance of class C or any subclass of C. obj_b is an instance of B, and while C is a subclass of B, B is not a subclass of C. Therefore, isinstance(obj_b, C) will return False. This statement is False. D: C._C__VarA == 2 The __VarA attribute in each class is name-mangled to the class where it is defined. So, C.__VarA is actually stored as C._C__VarA. However, C._C__VarA is 3 (as defined in class C), not 2. This statement is False.

#58. Which of the following lines of code will work flawlessly when put independently inside the add_new() method in order to make the snippet's output equal to [0, 1, 2]? (Choose two.) class MyClass: def __init__(self, size): self.queue = [i for i in range(size)] def get(self): return self.queue def get_last(self): return self.queue[-1] def add_new(self): # insert the line of code here Object = MyClass(2) Object.add_new() print(Object.get()) A. self.queue.append(self.queue[-1] + 1) B. self.queue.append(self.get_last() + 1) C. self.queue.append(get_last() + 1) D. queue.append(self.get_last() + 1)

Explanation: The correct answers are: A: self.queue.append(self.queue[-1] + 1) This option accesses the last element of self.queue directly with self.queue[-1], then adds 1 to it and appends the result to self.queue. Since self.queue initially is [0, 1], self.queue[-1] will be 1, so 1 + 1 results in 2, and the list becomes [0, 1, 2]. This option works correctly and will produce the desired output. B: self.queue.append(self.get_last() + 1) This option calls self.get_last(), which returns the last element of self.queue (equivalent to self.queue[-1]), adds 1 to it, and appends the result to self.queue. Since self.queue initially is [0, 1], self.get_last() returns 1, so 1 + 1 results in 2, and the list becomes [0, 1, 2]. This option also works correctly and will produce the desired output. The incorrect answers are: C: self.queue.append(get_last() + 1) This option attempts to call get_last() directly without the self prefix, which will result in an error because get_last is an instance method and must be called with self to access it. This option will raise a NameError because get_last() is not defined in the current scope without self. D: queue.append(self.get_last() + 1) This option attempts to access queue directly without the self prefix, which will also raise an error. queue is an instance variable (i.e., self.queue), so accessing it without self will cause a NameError. This option will raise a NameError because queue is not defined without self.

#78. What is true about Object-Oriented Programming in Python? (Choose two.) A. the same class can be used many times to build a number of objects B. each object of the same class can have a different set of methods C. if a real-life object can be described with a set of adjectives they may reflect a Python object method D. a subclass is usually more specialized than its superclass

Explanation: The correct answers are: A: the same class can be used many times to build a number of objects A class acts as a blueprint in Python. Multiple objects (instances) can be created from the same class, each having its own state and data. D: a subclass is usually more specialized than its superclass In object-oriented programming, a subclass inherits from a superclass and adds more specific functionality or overrides behavior. The incorrect answers are: B: each object of the same class can have a different set of methods All objects of the same class share the same set of methods defined in the class. However, their data (attributes) can differ. While you can add methods dynamically to individual objects, this is not typical behavior and goes against standard object-oriented practices. C: if a real-life object can be described with a set of adjectives they may reflect a Python object method Adjectives usually describe attributes (properties) of an object, not methods. Methods describe actions or behaviors that an object can perform, which are more like verbs.

#86. Which of the following snippets will execute without raising any unhandled exceptions? (Choose two.) A. try: print(int("0")) except NameError: print("0") else: print(int("")) B. try: print(0/0) except: print(0/1) else: print(0/2) C. import math try: print(math.sqrt(-1)) except: print(math.sqrt(0)) else: print(math.sqrt(1)) D. try: print(float("lel")) except (NameError, SystemError): print(float("lal")) else: print(float("1c1"))

Explanation: The correct answers are: B & C, they both return 0.0 The incorrect answers are: A. try: print(int("0")) except NameError: print("0") else: print(int("") print(int("0")): This executes successfully and prints 0. Since no exception is raised, the else block is executed. print(int("")): Raises a ValueError because an empty string cannot be converted to an integer. Result: Unhandled exception (ValueError). D. try: print(float("lel")) except (NameError, SystemError): print(float("lal")) else: print(float("1c1")) print(float("lel")): Raises a ValueError because "lel" cannot be converted to a float. The exception is not a NameError or SystemError, so it is not caught by the except block. Result: Unhandled exception (ValueError).

#16. Which of the following invocations are valid? (Choose two.) A. sort("python") B. "python".find("") C. "python".sort() D. sorted("python")

Explanation: The correct answers are: B. "python".find("") This is valid because the find() method can search for an empty string within another string, and it returns the position of the first character (in this case, it will return 0 since the empty string is found at the beginning of "python"). D. sorted("python") This is valid because sorted() can be used on a string. It returns a list of characters from the string in alphabetical order. For "python", it would return ['h', 'n', 'o', 'p', 't', 'y']. The incorrect answers are: sort("python") This is invalid because sort() is a method used on lists, not on strings. You would need to convert the string to a list first, then sort it. C. "python".sort() This is invalid because strings do not have a sort() method; only lists do.

#83. Which of the following invocations are valid? (Choose two.) A. 'python'.sorted() B. "python".rindex("th") C. sort("python") D. "python".find("")

Explanation: The correct answers are: B. "python".rindex("th") The rindex() method finds the last occurrence of a substring in a string and returns its starting index. If the substring is not found, it raises a ValueError. Example: result = "python".rindex("th") print(result) # Outputs: 2 D. "python".find("") The find() method returns the lowest index where the specified substring is found. An empty string ("") is always considered present in any string, starting at index 0. Example: result = "python".find("") print(result) # Outputs: 0 The incorrect answers are: A. 'python'.sorted() Strings in Python do not have a sorted() method. The sorted() function works on iterables, but it must be called as a standalone function, not as a method of a string. Correct usage: sorted("python") C. sort("python") sort() is a method available only for mutable sequences like lists. It is not a standalone function and cannot operate on a string. Correct usage with a list: lst = ['p', 'y', 't', 'h', 'o', 'n'] lst.sort() print(lst) # Outputs: ['h', 'n', 'o', 'p', 't', 'y']

#19. Which of the following statements are true? (Choose two.) A. an escape sequence can be recognized by the / sign put in front of it B. ASCII is a subset of UNICODE C. II in ASCII stands for Internal Information D. a code point is a number assigned to a given character

Explanation: The correct answers are: B. ASCII is a subset of UNICODE This is True. ASCII (American Standard Code for Information Interchange) is a subset of Unicode. ASCII defines 128 characters, while Unicode supports a much larger set, including characters from many different languages and symbol sets. D. a code point is a number assigned to a given character This is True. In Unicode, a code point is a unique number assigned to each character in the standard. For example, the Unicode code point for 'A' is U+0041. The incorrect answers are: an escape sequence can be recognized by the / sign put in front of it This is False. Escape sequences in Python (and most programming languages) use a backslash (\), not a forward slash (/). For example, \n is the escape sequence for a new line. C. II in ASCII stands for Internal Information This is False. ASCII stands for American Standard Code for Information Interchange, not Internal Information.

#98: Select the true statements. (Select two answers.) You cannot define new exceptions as subclasses derived from predefined exceptions. The args property is a tuple designed to gather all arguments passed to the class constructor. The finally branch of the try statement is always executed. The finally branch of the try statement may be executed if special conditions are met.

Explanation: The correct answers are: B. The args property is a tuple designed to gather all arguments passed to the class constructor. Python exceptions (which inherit from BaseException) have an args property, which is a tuple containing all arguments passed to the exception's constructor. Example: class MyException(Exception): pass try: raise MyException("Error occurred", 404) except MyException as e: print(e.args) # Output: ('Error occurred', 404) C. The finally branch of the try statement is always executed. The finally block is executed regardless of whether an exception occurs, is handled, or not. Example: try: raise ValueError("Test") except ValueError: print("Caught ValueError") finally: print("Finally block executed") Output: Caught ValueError Finally block executed The incorrect answers are: You cannot define new exceptions as subclasses derived from predefined exceptions. In Python, you can define custom exceptions as subclasses of predefined exceptions like Exception. Example: class CustomError(Exception): pass D. The finally branch of the try statement may be executed if special conditions are met. is false. The finally block is always executed, regardless of conditions.

#80. Which of the following statements are true? (Choose two.) A. a code point is a point inside the code when execution stops immediately B. UTF-8 is one of the ways of representing UNICODE code points C. ASCII is the name of a character coding standard D. an escape sequence can be recognized by the # sign put in front of it

Explanation: The correct answers are: B. UTF-8 is one of the ways of representing UNICODE code points UTF-8 is a widely used encoding scheme that represents Unicode code points as sequences of 1 to 4 bytes. Example: The Unicode code point U+0041 (the letter 'A') is represented in UTF-8 as 0x41. The code point U+1F600 (the 😀 emoji) is represented in UTF-8 as 0xF0 0x9F 0x98 0x80. C. ASCII is the name of a character coding standard ASCII (American Standard Code for Information Interchange) is a character encoding standard. It assigns numeric values to 128 characters, including letters, digits, punctuation marks, and control characters. Example: 'A' in ASCII has the value 65. 'a' in ASCII has the value 97. The incorrect answers are:Reveal Solution A. a code point is a point inside the code when execution stops immediately A code point refers to a numeric value assigned to each character in a character set (like Unicode). It is unrelated to program execution or debugging. Example: The Unicode code point for 'A' is U+0041. D. an escape sequence can be recognized by the # sign put in front of it Escape sequences are introduced by a backslash (\), not a #. Example of escape sequences: \n for newline. \t for tab.

#71. What is true about Python packages? (Choose two.) A. a package is a single file whose name ends with the pa extension B. a package is a group of related modules C. the __name__ variable always contains the name of a package D. the pyc extension is used to mark semi-compiled Python packages

Explanation: The correct answers are: B. a package is a group of related modules This is correct. A package is essentially a directory that contains Python modules (files ending with .py) grouped together for organizational purposes. Example: A directory named mypackage with files module1.py, module2.py, and an __init__.py file is a package. D. the pyc extension is used to mark semi-compiled Python packages This is correct. The .pyc extension is used for semi-compiled Python files, which are created by the Python interpreter after importing a module or package. These files store bytecode and are used to speed up loading. The incorrect answers are: A. a package is a single file whose name ends with the pa extension This is incorrect. Packages are directories containing a special __init__.py file (can be empty) and one or more related modules. The .pa extension is not a valid file type in Python. C. the __name__ variable always contains the name of a package This is incorrect. The __name__ variable contains the name of the current module or the value "__main__" when the module is executed directly. It is not specific to packages.

#12 Which of the following expressions evaluate to True? (Choose two.) A. ord("0") - ord("9") == 10 B. len("''") == 2 C. chr(ord('z') - 1) == 'y' D. len(''1234'') == 4

Explanation: The correct answers are: B. len("''") == 2 The string '' has two characters (each quote is a character). C. chr(ord('z') - 1) == 'y' The function ord('z') gives the Unicode code point of 'z', which is 122. Subtracting 1 gives 121, and chr(121) returns 'y'. The incorrect answers are: A. ord("0") - ord("9") == 10 The ord() function gives you the Unicode (or ASCII) code point of a character. ord("0") returns 48 because the Unicode code point for '0' is 48. ord("9") returns 57 because the Unicode code point for '9' is 57. So, ord("0") - ord("9") is 48 - 57, which equals -9, not 10. D. len(''1234'') == 4 The string ''1234'' as written has two extra single quotes around it, which means it is not interpreted as '1234' but rather as '\'\'1234\'\' (a string with two single quotes at the start and end). If you wrote it as len('1234'), the length would be 4, but with the two extra quotes, you are actually creating a longer string. So, '\'\'1234\'\'' has 6 characters, not 4.

#89. Which of the following expressions evaluate to True? (Choose two.) A. 'in not' in 'not' B. 'a' not in 'ABC'.lower() C. 'not' not in 'in' D. 't'.upper() in 'Thames'

Explanation: The correct answers are: C. 'not' not in 'in' The string 'not' is not present in 'in'. The not in operator correctly identifies that 'not' is not a substring of 'in', so this evaluates to True. D. 't'.upper() in 'Thames' 't'.upper() converts 't' to 'T'. The in operator checks if 'T' is a substring of 'Thames'. 'T' is present as the first character of 'Thames', so this evaluates to True. The incorrect answers are: A. 'in not' in 'not' 'in not' is a string, and 'not' is another string. The in operator checks if the first string is a substring of the second string. 'in not' is not a substring of 'not'. B. 'a' not in 'ABC'.lower() 'ABC'.lower() converts 'ABC' to 'abc'. The not in operator checks if 'a' is not in 'abc'. 'a' is in 'abc', so 'a' not in 'abc' evaluates to False.

#1. What is true about Python packages? (Choose two.) A. a code designed to initialize a package's state should be placed inside a file named init.py B. a package's contents can be stored and distributed as an mp3 file C. __pycache__ is a folder that stores semi-compiled Python modules D. the sys.path variable is a list of strings

Explanation: The correct answers are: C. __pycache__ is a folder that stores semi-compiled Python modules. This refers to __pycache__, which is a directory where Python stores the compiled bytecode versions of modules (usually .pyc files). D. the sys.path variable is a list of strings This is correct. sys.path is a list of directory paths (as strings) that Python searches to locate modules when importing them. The incorrect answers are: A. code designed to initialize a package's state should be placed inside a file named init.py. This is incorrect because the correct file name is __init__.py, with double underscores on both sides. __init__.py is used to initialize a package's state and can define what is exposed when the package is imported. B. a package's contents can be stored and distributed as an mp3 file This is incorrect. Python packages are typically distributed as .zip files, .whl (wheel) files, or through package management tools like pip. An .mp3 file format is not a valid way to distribute Python packages.

#67. Which of the following lambda definitions are correct? (Choose two.) A. lambda(x,y) = x//y - x%y B. lambda x,y: return x//y - x%y C. lambda x,y: (x,y) D. lambda x,y: x//y - x%y

Explanation: The correct answers are: C. lambda x,y: (x,y): This is correct. It defines a lambda function that takes two arguments, x and y, and returns a tuple (x, y). D. lambda x,y: x//y - x%y: This is correct. It defines a lambda function that takes two arguments, x and y, and returns the result of the expression x // y - x % y. The incorrect answers are: A. lambda(x,y) = x//y - x%y: This is incorrect because the syntax is wrong. Lambdas in Python do not use = for assignment. Instead, they use the syntax lambda arguments: expression. B. lambda x,y: return x//y - x%y: This is incorrect because lambda functions do not use the return keyword. The expression is implicitly returned in lambda functions.

#57. Assuming that the code below has been placed inside a file named code.py and executed successfully, which of the following expressions evaluate to True? (Choose two.) class ClassA: var = 1 def __init__(self, prop): prop1 = prop2 = prop def __str__(self): return 'Object' class ClassB(ClassA): def __init__(self, prop): prop3 = prop ** 2 super().__init__(prop) Object = ClassB(2) A. len(ClassB.__bases__) == 2 B. __name__ == 'code.py' C. str(Object) == 'Object' D. ClassA.__module__ == '__main__'

Explanation: The correct answers are: C. str(Object) == 'Object' str(Object) calls the __str__ method of the Object instance, which is an instance of ClassB. Since ClassB inherits from ClassA, the __str__ method in ClassA is used, and it returns the string 'Object'. Therefore, str(Object) will indeed return 'Object'. This statement is True. D. ClassA.__module__ == '__main__' ClassA.__module__ provides the name of the module in which ClassA is defined. If this code is run directly as a script, ClassA.__module__ will be '__main__'. This statement is True. The incorrect answers are: A: len(ClassB.__bases__) == 2 ClassB.__bases__ provides a tuple containing the base classes of ClassB. Since ClassB inherits from only one class, ClassA, ClassB.__bases__ will have a length of 1, not 2. This statement is False. B: __name__ == 'code.py' In Python, the __name__ variable will be equal to '__main__' when the code is executed directly as a script, not the filename. If this code is in a file named code.py, __name__ would be '__main__' when executed, not 'code.py'. This statement is False.

#39. Which of the following statements are true? (Choose two.) A. if invoking open() fails, an exception is raised B. instd, outstd, errstd are the names of pre-opened streams C. open() requires a second argument D. open() is a function which returns an object that represents a physical file

Explanation: The correct answers are: if invoking open() fails, an exception is raised This is true. If the open() function fails, for example, due to a missing file or permission issues, an exception (such as FileNotFoundError or PermissionError) will be raised. D. open() is a function which returns an object that represents a physical file This is true. The open() function returns a file object that allows you to interact with the file (read, write, etc.). This object represents the connection to the physical file on disk. The incorrect answers are: B. instd, outstd, errstd are the names of pre-opened streams: This is false. The correct names of the pre-opened standard streams in Python are sys.stdin (standard input), sys.stdout (standard output), and sys.stderr (standard error). C. open() requires a second argument: This is false. The second argument (the mode) is optional. If not provided, the file is opened in the default 'r' (read) mode.

#4. Assuming that the code below has been executed successfully, which of the following expressions will always evaluate to True? (Choose two.) import random v1 = random.random() v2 = random.random() A. len(random.sample([1,2,3],1)) > 2 B. v1 == v2 C. random.choice([1,2,3]) > 0 D. v1>1

Explanation: The correct answers is: C. random.choice([1,2,3]) > 0 This is correct. random.choice([1,2,3]) will always return one of the values 1, 2, or 3, all of which are greater than 0, so this expression will always evaluate to True. The incorrect answers are: A. len(random.sample([1,2,3], 1)) > 2 This is incorrect. The random.sample([1,2,3], 1) function returns a list of length 1, so it will never be greater than 2. B. v1 == v2 This is incorrect. Since v1 and v2 are generated by random.random(), they will most likely have different values. It is extremely unlikely that v1 will be equal to v2. D, v1 > 1 This is incorrect. random.random() generates a floating-point number between 0 and 1, so v1 will never be greater than 1.

#42. With regards to the directory structure below, select the proper forms of the directives in order to import module_b. (Choose two.) pypack (dir) ├── upper (dir) │ ├── lover (dir) │ │ └── module_c.py (file) │ └── module_b.py (file) └── module_a.py (file) A. import module_b B. import pypack.upper.module_b C. from pypack.upper import module_b D. import upper.module_b

Explanation: The correct answers: B. import pypack.upper.module_b: This is correct because it specifies the full path of module_b relative to the package pypack and the directory upper. C. from pypack.upper import module_b: This is also correct. This statement imports module_b from the package pypack.upper. The incorrect answers are: A. import module_b: This is incorrect because Python won't be able to locate module_b without specifying the package hierarchy (i.e., it must start with pypack). D. import upper.module_b: This is incorrect because the correct package path must start with the top-level package pypack, not just upper.

#66. Assuming that the following code has been executed successfully, select the expressions which evaluate to True. (Choose two.) def f(x): def g(x): return x * x return g a = f(2) b = f(3) A. a(2) == 4 B. a is not None C. b(1) == 4 D. a == b

Explanation: The function f(x) defines an inner function g(x), which returns x * x. The f(x) function then returns the function g. When a = f(2) is executed, a becomes the g function (a function that squares a given input), and similarly, b = f(3) makes b another instance of the g function. The correct answers are: a(2) == 4: This is True. Since a is a function that squares its input, a(2) returns 2 * 2, which is 4. a is not None: This is True. a is assigned a function, so it's not None. The incorrect answers are: C. b(1) == 4: This is False. b(1) returns 1 * 1, which is 1, not 4. D. a == b: This is False. Each call to f(x) returns a new instance of the function g, so a and b are different function objects.

#9. What is the expected behavior of the following code? m = 0 def foo(n): global m assert m == 0 try: return 1/n except ArithmeticError: m += 1 raise try: foo(0) except ArithmeticError: m += 2 except: m += 1 print(m) A. it outputs 3 B. it outputs 1 C. it outputs 2 D. the code is erroneous and it will not execute

Explanation: The function foo(0) is called. Inside foo(0), it tries to execute 1 / n, which raises a ZeroDivisionError (a subclass of ArithmeticError). The except ArithmeticError block is entered, and m is incremented by 1, making m = 1. The exception is re-raised after incrementing m, so control moves to the outer try-except. The outer except ArithmeticError: block catches the re-raised exception and increments m by 2, making m = 3. The final value of m is printed as 3. Correct answer: A. it outputs 3

#97: The function named super() may be used to: Make a class super Access a super class's attributes and/or methods Make a class better

Explanation: The super() function is used to access attributes and methods of a superclass in Python. It is not used to "make a class better" or "make a class super." Correct answer is: B. Access a super class's attributes and/or methods

#10. What is true about the following snippet? (Choose two.) class E(Exception): def __init__(self, message): self.message = message def __str__(self): return "it's nice to see you" try: print("I feel fine") raise E("what a pity") except E as e: print(e) else: print("the show must go on") A. the string what a pity will be seen B. the string it's nice to see you will be seen C. the code will raise an unhandled exception D. the string I feel fine will be seen

Explanation: The try block starts by printing "I feel fine", so this will be seen. Then, the custom exception E is raised with the message "what a pity". In the except block, the exception is caught as e, and when print(e) is called, the __str__ method of the exception class E is executed. This returns the string "it's nice to see you", which will be printed. The else block will not execute because an exception was raised. The correct answers are: B. the string it's nice to see you will be seen D. the string I feel fine will be seen

#62. What is the expected output of the following code? def foo(x, y, z): return x(y(z)) print(foo(lambda x: 2 * x, lambda x: x // 2, 2)) A. 3 B. 4 C. 2 D. an exception is raised

Explanation: Understanding foo(x, y, z): The function foo takes three arguments: x, y, and z. It returns the result of calling x with the argument y(z). Arguments in foo(lambda x: 2 * x, lambda x: x // 2, 2): The first argument, x, is a lambda function lambda x: 2 * x. This function takes a number x and returns 2 * x. The second argument, y, is a lambda function lambda x: x // 2. This function takes a number x and returns x // 2 (integer division by 2). The third argument, z, is the integer 2. Evaluating foo(lambda x: 2 * x, lambda x: x // 2, 2): foo will first evaluate y(z), which is lambda x: x // 2 with z = 2. y(2) computes 2 // 2, which equals 1. Then, foo will pass the result of y(z) (which is 1) to x. x(1) is evaluated as 2 * 1, which equals 2. The correct answer is: C. 2

#73. The __bases__ property contains: A. base class locations (addr) B. base class objects (class) C. base class names (str) D. base class ids (int)

Explanation: What is __bases__? It is an attribute of a class, not an instance. It provides access to the tuple of base class objects of the class. Base Class Objects: Base classes are the parent classes from which the current class derives. Example: class A: pass class B(A): pass print(B.__bases__) Output: (<class '__main__.A'>,) The correct answers is: B. base class objects (class)

#94: What is the expected output of the following code? try: print("5"/0) except ArithmeticError: print("arith") except ZeroDivisionError: print("zero") except: print("some")

Explanation: What the Code Does: The statement print("5"/0) inside the try block attempts to divide the string "5" by 0, which raises a TypeError. However, if we interpret the intent as dividing 5 (a number) by 0, a ZeroDivisionError would be raised. In Python, dividing a number by zero raises a ZeroDivisionError, which is a subclass of ArithmeticError. Exception Handling: The except block for ArithmeticError is listed before the one for ZeroDivisionError. Since ZeroDivisionError is a subclass of ArithmeticError, the first matching except block is executed. The exception hierarchy causes the ArithmeticError block to execute first, so arith is printed. Why Not zero: Although ZeroDivisionError is more specific, Python's exception handling checks blocks in order, and the ArithmeticError block matches first. Why Not some: The generic except block is only executed if no specific except block matches the raised exception. In this case, ArithmeticError matches, so some is not printed. The correct answer is: arith

#38. Assuming that the following code has been executed successfully, select the expressions which evaluate to True (Choose two.) def f(x, y): nom, denom = x, y def g(): return nom / denom return g a = f(1, 2) b = f(3, 4) A. a is not None B. a() == 4 C. a != b D. b() == 4

Explanation: a is not None: True: f(1, 2) returns the inner function g, so a is a function. Therefore, a is not None. a() == 4: False: When you call a(), it will execute g(), which does the calculation nom / denom. For a = f(1, 2), nom = 1 and denom = 2, so a() will return 1 / 2 = 0.5. a != b: True: a and b are two different closures because each call to f(x, y) creates a new function with different captured values (nom and denom). Therefore, a and b are distinct function objects. b() == 4: False: When you call b(), it will execute g() with nom = 3 and denom = 4. Thus, b() will return 3 / 4 = 0.75. Correct answers are: A, a is not None C. a != b

#46. What is the expected behavior of the following code? d = {'1': '1', '2', '3'} try: d['1'] = d['3'] except BaseException as error: print(type(error)) A. it outputs B. the code is erroneous and it will not execute C. it outputs D. it outputs

Explanation: d = {'1': '1', '2', '3'}: This line attempts to define a dictionary d with keys '1' and '2'. However, the syntax is incorrect because a dictionary in Python requires key-value pairs separated by a colon (:). The entry '2', '3' is missing a colon between '2' and '3'. This will result in a SyntaxError because the dictionary syntax is invalid. Since the code will raise a SyntaxError at the dictionary definition, it will not proceed to the try block, and therefore no exception handling or output will occur. Expected Output: The code will not execute because of the syntax error in defining the dictionary d. Correct Answer: B. the code is erroneous and it will not execute

#2. What is the expected output of the following code? import sys import math b1 = type(dir(math)) is list b2 = type(sys.path) is list print(b1 and b2) A. None B. True C. 0 D. False

Explanation: dir(math) returns a list of attributes for the math module, so type(dir(math)) is list. sys.path is also a list, so type(sys.path) is list. Therefore, b1 and b2 both evaluate to True, and print(b1 and b2) outputs True. The correct answers B. True

#43. What is the expected output of the following code? import sys b1 type (dir(sys)) is str b2 type (sys.path[-1]) is str print (b1 and b2) A. True B. False C. 0 D. None

Explanation: dir(sys): dir(sys) returns a list of the attributes and methods of the sys module. So, dir(sys) is not a string, it's a list. Therefore, type(dir(sys)) is str evaluates to False, because the type of dir(sys) is list, not str. sys.path[-1]: sys.path is a list of directories that Python searches for modules. sys.path[-1] accesses the last element of this list, which is typically a string representing a directory path. So, type(sys.path[-1]) is str will likely evaluate to True, because it's expected that elements of sys.path are strings (directory paths). print(b1 and b2): The expression b1 and b2 will evaluate to False because b1 is False (as determined in step 1) and b2 is True (as determined in step 2). The and operator returns False if any of the operands is False. Therefore, the expected output is: B. False

#40. What is the expected output of the following code if there is no file named non_existing_file inside the working directory? try: f = open('non_existing_file', 'r') print(1, end=' ') except IOError as error: print(error.errno, end=' ') print(2, end=' ') else: f.close() print(3, end=' ') A. 2 2 3 B. 2 2 C. 1 3 D. 1 2 2

Explanation: f = open('non_existing_file', 'r'): Since the file non_existing_file does not exist in the working directory and the mode 'r' is for reading, this line will raise a FileNotFoundError, which is a subclass of IOError in Python 2 or OSError in Python 3. except IOError as error:: The exception is caught here. The error.errno will be printed, which corresponds to the error number for a "file not found" error (in Python, this typically prints 2 for ENOENT). print(2, end=' '): After printing the error number, 2 is printed as per the next line in the except block. else:: The else block will not be executed because the try block raised an exception. Final Output: The expected output will be the error number (2 for file not found) followed by 2. Thus, the correct answer is: B. 2 2

#35. What is the expected output of the following code if the file named zero_length_existing_file is a zero-length file located inside the working directory? try: f = open('zero_length_existing_file', 'rt') d = f.readline() print(len(d)) f.close() except IOError: print(-1) A. 2 B. -1 C. an errno value corresponding to file not found D. 0

Explanation: f = open('zero_length_existing_file', 'rt'): The file is successfully opened, since it exists. No IOError will be raised. d = f.readline(): The readline() method is called. Since the file is zero-length, there is no content to read, so d will be an empty string (''). print(len(d)): The length of the string d is printed. Since d is an empty string, len(d) will be 0. f.close(): The file is closed properly. No exceptions will be raised because the file exists, so the except IOError: block will not be executed. Therefore, the expected output is: D. 0

#36. What is the expected output of the following code? def foo(x, y, z): return x(y) - x(z) print(foo(lambda x: x % 2, 2, 1)) A. an exception is raised B. 1 C. 0 D. -1

Explanation: foo(lambda x: x % 2, 2, 1): The function foo takes three arguments: x, y, and z. In this case: x is the lambda function lambda x: x % 2, which returns the remainder of x divided by 2 (essentially, it checks if x is even or odd). y is 2. z is 1. Inside foo, it evaluates: x(y) → lambda x: x % 2 applied to y = 2. This gives 2 % 2 = 0. x(z) → lambda x: x % 2 applied to z = 1. This gives 1 % 2 = 1. The function returns the result of x(y) - x(z), which is: 0 - 1 = -1 Therefore, the expected output is: D. -1

#41. Assuming that the math module has been successfully imported, which of the following expressions evaluate to True? (Choose two.) A. math.ceil(2.5) == math.trunc(2.5) B. math.ceil(2.5) < math.floor(2.5) C. math.floor(2.5) == math.trunc(2.5) D. math.hypot(3,4) == math.sqrt(25)

Explanation: math.ceil(2.5) == math.trunc(2.5): math.ceil(2.5) rounds up to the nearest integer, so it returns 3. math.trunc(2.5) truncates the decimal part, returning 2. 3 != 2, so this is False. B. math.ceil(2.5) < math.floor(2.5): math.ceil(2.5) is 3 (rounds up). math.floor(2.5) is 2 (rounds down). 3 < 2 is False, so this statement is False. C. math.floor(2.5) == math.trunc(2.5): Both math.floor(2.5) and math.trunc(2.5) return 2, as math.floor rounds down, and math.trunc simply removes the decimal part. So, this is True. D. math.hypot(3,4) == math.sqrt(25): math.hypot(3,4) calculates the hypotenuse of a right triangle with sides 3 and 4, which is 5 (since sqrt(3^2 + 4^2) = sqrt(9 + 16) = sqrt(25) = 5). math.sqrt(25) is also 5. Therefore, this is True. The correct answers are: C. math.floor(2.5) == math.trunc(2.5) D. math.hypot(3,4) == math.sqrt(25)

#37. What is the expected behavior of the following code? my_list = [i for i in range(5)] m = [my_list[i] for i in range(4, 0, -1) if my_list[i] % 2 != 0] print(m) A. the code is erroneus and it will not execute B. it outputs [4, 2, 0] C. it outputs [3, 1] D. it outputs [1, 3]

Explanation: my_list = [i for i in range(5)]: This creates a list of integers from 0 to 4: my_list = [0, 1, 2, 3, 4] m = [my_list[i] for i in range(4, 0, -1) if my_list[i] % 2 != 0]: This is a list comprehension that: Iterates over the range range(4, 0, -1), which generates the sequence [4, 3, 2, 1] (iterating backwards). For each value of i in this range, it checks if my_list[i] % 2 != 0 (i.e., if the element is odd). If the condition is true, it includes my_list[i] in the new list m. Now, let's see what this does for each value of I: For i = 4: my_list[4] = 4 (even, so not included). For i = 3: my_list[3] = 3 (odd, so it is included). For i = 2: my_list[2] = 2 (even, so not included). For i = 1: my_list[1] = 1 (odd, so it is included). As a result, the list m will be [3, 1]. print(m): This will print the list m. Therefore, the expected output is: C. it outputs [3, 1]

#15. What is the expected behavior of the following code? the_list = "alpha;beta;gamma".split(";") the_string = ''.join(the_list) print(the_string.isalpha()) A. it outputs True B. it outputs False C. it outputs nothing D. it raises an exception

Explanation: split(";"): The string "alpha;beta;gamma" is split by the ";", resulting in the list ['alpha', 'beta', 'gamma']. ''.join(the_list): This joins the elements of the list into one string without any separator, resulting in "alphabetagamma". the_string.isalpha(): Now, the string "alphabetagamma" consists of only alphabetic characters, so calling .isalpha() will return True. Thus, the correct output would be: A. it outputs True

#49. What is the expected behavior of the following code? string = '123' dummy = 0 for character in reversed(string): dummy += int(character) print(dummy) A. it outputs 123 B. it raises an exception C. it outputs 6 D. it outputs 321

Explanation: string = '123': The variable string is set to the string '123'. dummy = 0: The variable dummy is initialized to 0. for character in reversed(string):: reversed(string) creates an iterator that goes through the characters of string in reverse order, so it will iterate over '3', '2', and '1'. dummy += int(character): In each iteration, character is converted to an integer and added to dummy. The loop proceeds as follows: First iteration: character = '3' → dummy += 3 → dummy becomes 3.\ Second iteration: character = '2' → dummy += 2 → dummy becomes 5. Third iteration: character = '1' → dummy += 1 → dummy becomes 6. print(dummy): After the loop, dummy has accumulated the sum of 3 + 2 + 1, which is 6. The correct answer is: C. it outputs 6

#18. Assuming that the snippet below has been executed successfully, which of the following expressions will evaluate to True? (Choose two.) string = 'python'[::2] string = string[-1] + string[-2] A. len(string) == 3 B. string[0] == 'o' C. string[0] == string[-1] D. string is None

Explanation: string = 'python'[::2] This takes every second character from the string 'python'. So, string becomes 'pto'. string = string[-1] + string[-2] Now, string[-1] refers to the last character of 'pto', which is 'o'. string[-2] refers to the second last character of 'pto', which is 't'. The new string becomes 'ot' (last character 'o' + second last character 't'). The correct answer is: B. string[0] == 'o' This is True because the first character of the updated string 'ot' is 'o'. The incorrect answers are: len(string) == 3 This is False because the length of the updated string 'ot' is 2, not 3. C. string[0] == string[-1] This is False. The first character ('o') is not equal to the last character ('t'). D. string is None This is False because string is a string object, not None.

#14. What is the expected behavior of the following code? string = str(1/3) dummy = '' for character in string: dummy = dummy + character print (dummy [-1]) A. it outputs 3 B. it outputs 'None' C. it outputs 0 D. it raises an exception

Explanation: string = str(1/3) This converts the result of 1/3 (which is approximately 0.3333333333333333) into a string. So, string becomes '0.3333333333333333'. dummy = '' This initializes an empty string dummy. for character in string: This iterates over each character in the string representation of 1/3, appending each character to the dummy string. After the loop is done, dummy will hold the entire string '0.3333333333333333'. print(dummy[-1]) This prints the last character of the dummy string. The last character of the string '0.3333333333333333' is '3'. Expected output: A. it outputs 3

#34. What is the expected behavior of the following code? x =3 % 1 y = 1 if x > 0 else 0 print(y) A. the code is erroneous and it will not execute B. it outputs 1 C. it outputs 0 D. it outputs -1

Explanation: x = 3 % 1: This calculates the remainder of 3 divided by 1, which is 0 (since 3 divides evenly by 1 with no remainder). y = 1 if x > 0 else 0: Here, y will be assigned 1 if x > 0; otherwise, it will be assigned 0. Since x is 0, this condition is false, and y is assigned 0. print(y): This prints the value of y, which is 0. So the correct output is 0, making the correct answer: C. it outputs 0

#32. What is the expected output of the following code? myli = range (-2,2) m = list(filter(lambda x: True if abs(x) < 1 else False, myli)) print(len(m)) A. 4 B. 1 C. an exception is raised D. 16

Explanation: The correct answer is: B. 1 Here is why: myli = range(-2, 2) generates a range of integers: [-2, -1, 0, 1]. The filter function applies a lambda function to filter elements where abs(x) < 1. This condition means selecting numbers whose absolute value is less than 1, which would be 0 only. The list m contains only [0]. Finally, print(len(m)) prints the length of the list, which is 1.

#23. Assuming that the code below has been placed inside a file named code.py and executed successfully, which of the following expressions evaluate to True? (Choose two.) class ClassA: var = 1 def __init__(self, prop): prop1 = prop2 = prop class ClassB(ClassA): def __init__(self, prop): prop3 = prop ** 2 super().__init__(prop) Object = ClassB(2) A. str(Object) = 'Object' B. __name__ == '__main__' C. len(ClassB.__bases__) == 1 D. ClassA.__module__ == 'ClassA'

Explanation: The correct answers are: B. __name__ == '__main__' This is True, if the script is executed directly, not imported as a module. In Python, __name__ is set to '__main__' when the script is run as the main program. C. len(ClassB.__bases__) == 1 This is True. ClassB inherits from ClassA, so ClassB.__bases__ will contain only one base class, which is ClassA. Hence, the length of ClassB.__bases__ is 1. The incorrect answers are: A. str(Object) = 'Object' This is False. There's no __str__ or __repr__ method defined in the class. Therefore, str(Object) would return a default string representation like <__main__.ClassB object at 0x...>, and not 'Object'. D. ClassA.__module__ == 'ClassA' This is False. The __module__ attribute of a class refers to the module name in which the class was defined, not the class name. Since the class is defined in a module (e.g., code.py), ClassA.__module__ would be 'code', not 'ClassA'.


Related study sets

Preguntas y respuestas - Questions and answers

View Set

Cerro Grande Forest Fire Not What Was Prescribed

View Set

Analyze the Qualities of Art Quiz

View Set

Material Safety Data Sheets (MSDS)

View Set