PCAP Combined
Which of the following snippets will execute without raising any unhandled exceptions? (Choose two.) ----------------------------------------- A. try: print (0/0) except: print (0/1) else: print (0/2) B. try: print (int("0")) except NameError: print ("0") else: print (int("")) C. import math try: print(math.sqrt(-1)) except: print(math.sqrt(0)) else: print(math.sqrt(1)) D. try: print(float("1e1")) except (NameError, SystemError): print(float("1a1")) else: print(float("1c1"))
A. 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))
What is true about Python packages? (Select two answers) A. the sys.path variable is a list of strings B. _pycache_is a folder that stores semi-completed Python modules C. a package contents can be stored and distributed as an mp3 file D. a code designed to initialize a package's state should be placed inside a file named init.py
A. the sys.path variable is a list of strings B. _pycache_is a folder that stores semi-completed Python modules
What is true about Python packages? (Select two answers) A. the__name__variable content determines the way in which the module was run B. a package can be stored as a tree of sub-directories/sub-folders C. __pycache__is the name of a built-in variable D. hashbang is the name of a built-in Python function
A. the__name__variable content determines the way in which the module was run B. a package can be stored as a tree of sub-directories/sub-folders
Which of the following statements are true? (Select two answers) A. Python strings are actually lists B. Python strings can be concatenated C. Python strings can be sliced like lists D. Python strings are mutable
B. Python strings can be concatenated C. Python strings can be sliced like lists
If S is a stream open for reading, what do you expect from the following invocation? c - s.read() A. one line of the file will be read and stored in the string called C B. the whole file content will be read and stored in the string called C C. one character will be read and stored in the string called C D. one disk sector (512 bytes) will be read and stored in the string called C
B. the whole file content will be read and stored in the string called C
Which of the following sentences are true? (Select two answers) A. lists may not be stored inside tuples B. tuples may be stored inside lists C. tuples may not be stored inside tuples D. lists may be stored inside lists
B. tuples may be stored inside lists D. lists may be stored inside lists
Assuming that the code below has been executed successfully, which of the following expressions will always evaluate to True? (Select two answers) ------------------------- import random random.seed(1) v1 = random.random() random.seed(1) v2 = random.random() ------------------------- A. len(random.sample([1,2,3],2)) > 2 B. v1 == v2 C. random.choice([1,2,3]) >=1 D. v1 >= 1
B. v1 == v2 C.random.choice([1,2,3]) >=1
What would you use instead of XXX if you want to check whether a certain 'key' exists in a dictionary called diet? (Select two answers) ----------------------- if XXX: print Key exists ----------------------- A. 'key' in diet B. diet['key'] != None C. diet.exists('key') D. 'key' in diet.keys()
A. 'key' in diet D. 'key' in diet.keys() To check if a certain 'key' exists in a dictionary called diet, you can use the following Python expressions: A. 'key' in diet: This checks whether 'key' is one of the keys in the dictionary diet. It's a common, idiomatic way to check for the existence of a key in a Python dictionary and would be used in the if statement like this: if 'key' in diet:. D. 'key' in diet.keys(): This also checks if 'key' is among the keys of the dictionary diet. The .keys() method returns a view of the dictionary's keys, and 'key' in diet.keys() iterates over them to see if 'key' is present. It's more verbose than necessary but still correct. Typically, you would just use 'key' in diet for simplicity and readability. For the other options: B. diet['key'] != None: This isn't a reliable method to check for the presence of a key because it will raise a KeyError if 'key' is not in the dictionary. Even if the key exists and its value is None, it would incorrectly suggest the key does not exist. C. diet.exists('key'): There is no .exists() method for dictionaries in Python, so this would result in an AttributeError. Therefore, the correct expressions to use in the place of XXX to check whether a certain 'key' exists in a dictionary called diet are: A. 'key' in diet D. 'key' in diet.keys()
Which of the following literals reflect the value given as 34.23? (select two answers) A. .3423e2 B. 3423e-2 C. .3423e-2 D. 3423e2
A. .3423e2 B. 3423e-2
What will be the value of the i variable when the while e loop finishes its execution? --------------- i = 0 while i != 0: i = i-1 else: i = i + 1 --------------- A. 1 B. 0 C. 2 D. the variable becomes unavailable
A. 1 Let's analyze the code step-by-step to determine the value of i when the while loop finishes its execution: 1. i = 0 initializes i to 0. 2. The while loop condition is i != 0. Since i is 0 at the start, the condition is False. Therefore, the loop does not execute, not even once. 3. The else block associated with the while loop executes when the loop completes without encountering a break statement. Since the while loop never started (as the condition was False from the beginning), the else block executes immediately. 4. Within the else block, i = i + 1 increments i by 1. Since i was 0, adding 1 sets i to 1. After the else block executes, the final value of i is 1. Therefore, when the while loop finishes its execution (which, in this case, is immediately as it never starts due to the initial condition being false), the value of i will be: A. 1.
Which of the following expressions evaluate to True? (Select two answers) A. 121 + 1 != '!' + 2 * '2' B. 'AbC' lower () < 'AB' C. '1' + '1' + '1' < '1' * 3' D. '3.14' != str(3.1415)
A. 121 + 1 != '!' + 2 * '2' D. '3.14' != str(3.1415)
What is the expected output of the following code? --------------------------- def f (n): if n == 1: return '1' return str (n) + f (n-1) print(f(2)) --------------------------- A. 21 B. 2 C. 3 D. 12
A. 21 Let's analyze the code and its recursive function to understand the expected output: Function f(n): Takes a single argument n. If n is 1, it returns the string '1'. Otherwise, it returns str(n) concatenated with the result of calling f(n-1). Recursive Call Breakdown: The function is called with f(2). Since n is not 1, the function returns str(2) + f(1). Now f(1) needs to be evaluated. Given n == 1, f(1) returns '1'. The return value of f(2) is therefore '2' + '1'. Putting it all together, f(2) returns '21'. Therefore, the expected output of the code is: A. 21.
What is the expected output of the following code? -------------------------------- def foo(x,y): return y(x) + (x+1) print(foo(1, lambda x: x*x)) -------------------------------- A. 3 B. 5 C. 4 D. an exception is raised
A. 3
What is the expected output of the following code? -------------------------------- import sys import math bl = type(dir(math) [0]) is str b2 = type(sys.path[-1]) is str print(bl and b2) -------------------------------- A. True B. 0 C. False D. None
A. True
What is the expected behavior of the following snippet? ----------------- def a (i, I): return i [I] print(a(0,[i])) ----------------- It will: A. cause a runtime exception B. print 1 C. print 0 , [1] D. print [1]
A. cause a runtime exception Let's analyze the given code snippet step by step to understand its behavior and determine the expected outcome: Function Definition: def a(i, I): defines a function a with two parameters, i and I. return i[I]: attempts to return the element at index I from i. Function Call: print(a(0, [i])): attempts to call function a with 0 as the first argument and [i] as the second. However, there is an issue here as i is not defined before it's used in the list [i]. Before we proceed, let's clarify the issues and Python's behavior: The function a is expecting its first parameter i to be indexable (like a list, tuple, or string), as it attempts to access an element using i[I]. The variable i in the list [i] is not defined anywhere in the code, which would lead to a NameError at runtime. Even if i were defined, passing 0 as the first argument would not work for indexing because an integer isn't indexable. Given the provided code and typical Python behavior, the expected outcome when attempting to run this snippet is: A. cause a runtime exception The runtime exception will likely be a NameError due to i being undefined in the list [i] when the function a is called. Even if i were defined, attempting to use an integer (0) for indexing would then cause a TypeError.
Assuming that the following inheritance set is in force, which of the following classes are declared properly? (Select two answers) ---------------- class A: pass class B(A): pass class C(A): pass class D(B): pass ---------------- A. class Class_4(D,A): pass B. class Class_1(C,D): pass C. class Class_3(A,C): pass D. class Class_2(B,D): pass
A. class Class_4(D,A): pass B. class Class_1(C,D): pass
You need data which can act as a simple telephone directory. You can obtain it with the following clauses (choose two relevant variants; assume that no other items have been created before) A. dir={'Mom':5551234567, 'Dad':5557654321} B. dir={'Mom':'5551234567', 'Dad':'5557654321'} C. dir={Mom:5551234567, Dad:5557654321} D. dir={Mom:'5551234567', Dad:'5557654321'}
A. dir={'Mom':5551234567, 'Dad':5557654321} B. dir={'Mom':'5551234567', 'Dad':'5557654321'}
Assuming that the math module has been successfully imported, which of the following expressions evaluate to True? (Select two answers) A. math. hypot (3,4) == math.sqrt (25) B. math. hypot (2,5) == math.truec (2.5) C. math. hypot (2,5) == math.true (2.5) D. math. cell (2,5) == math.floor (2.5)
A. math. hypot (3,4) == math.sqrt (25) B. math. hypot (2,5) == math.truec (2.5)
Assuming that String is six or more letters long, the following slice String[1:-2] is shorter than the original string by: A. four chars B. three chars C. one char D. two chars
A. four chars Let's analyze what the slice String[1:-2] does for a string that is at least six characters long: String[1:-2] takes the substring of String starting from the second character (as indexing starts at 0) up to the third-to-last character (as -2 refers to the second-to-last character, and slicing is up to but not including the end index). For a string "abcdef" (as an example of a string that's exactly six characters long): The original string is "abcdef". The slice String[1:-2] would result in "bcde". Comparing the length difference: Original string length: 6 characters. Sliced string length: 4 characters ("bcde"). The sliced string is shorter by two characters at the start (original first character 'a') and by two characters at the end (original last two characters 'ef'), making it a total of 4 characters shorter. Therefore, the slice String[1:-2] is shorter than the original string by: A. four chars.
The first parameter of each method: A. holds a reference to the currently processed object B. is always set to None C. is set to a unique random value D. is set by the first argument's value
A. holds a reference to the currently processed object
With regards to the directory structure below, select the proper forms of the directives in order to import module_A. (Select two answers) ------------------------------------- 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
A. import pypack.module_a D. from pypack import module_a
Assuming that the following piece of code has been executed successfully, which of the expressions evaluate to True? (Select two answers) ------------------------- class A: VarA = 1 def __init__(self): self.prop_a = 1 class B(A): VarA = 2 def __init__(self): super().__int_() self.prop_b_ = 2 obj_a = A() obj_aa = A() obj_b = B() obj_bb = obj_b ------------------------- A. isinstance(obj_b,A) B. A.VarA == 1 C. obj_a is obj_aa D. B.VarA == 1
A. isinstance(obj_b,A) B. A.VarA == 1 Let's analyze the given classes and their instances, and then evaluate each expression: Given Classes and Instances: Class A: Initializes VarA to 1 and self.prop_a to 1. Class B: Inherits from A and sets VarA to 2, and self.prop_b to 2. Note that the code super().__int_() seems to be a typo and should be super().__init__(). Assuming the typo is meant to be init and the code executed successfully, as per the assumption. Evaluating Each Expression: A. isinstance(obj_b, A) obj_b is an instance of B, which is a subclass of A. In Python, an object is considered an instance of both its class and any of its superclass. So obj_b is indeed an instance of A. This statement is True. B. A.VarA == 1 VarA is a class variable in A set to 1. This statement is True and reflects the initial definition of VarA in class A. C. obj_a is obj_aa obj_a and obj_aa are two different instances of A. The is operator checks for identity, not equality. Since they are two distinct instances, they do not share the same identity. This statement is False. D. B.VarA == 1 Within class B, VarA is overridden to be 2. This does not change VarA in class A, but it does mean that for class B, VarA is 2, not 1. Therefore, B.VarA is 2, not 1. This statement is False. Based on the analysis, the expressions that evaluate to True are: A. isinstance(obj_b, A) B. A.VarA == 1
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 1 B. it outputs 2 C. the code is erroneous and it will not execute D. it outputs 3
A. it outputs 1 The given code snippet is attempting to convert the string s into an integer using int(s). The value of s is '2A', which is not a valid integer, so this will raise a ValueError. Now let's look at how the code is structured: 1. try block: It tries to convert '2A' to an integer, which will fail and raise a ValueError. 2. except TypeError block: This block would catch a TypeError, but since ValueError is raised (not TypeError), this block won't execute. 3. except LookupError block: This block would catch a LookupError, but ValueError does not inherit from LookupError, so this block won't execute either. 4. except block: This is a catch-all for any exception not previously caught. Since ValueError is not caught by the other two, this block will execute. Given this flow, the except block will be executed, setting n = 1. Finally, the script prints the value of n, which is 1. So, the expected behavior of the code is: A. it outputs 1.
What is the expected behavior of the following code? -------------------------- x = 8 ** (1/3) y = 2. if x < 2.3 else 3. print (y ) -------------------------- A. it outputs 2.0 B. it outputs 2.5 C. the code is erroneus and it will not execute D. it outputs 3.0
A. it outputs 2.0
What is the expected behavior of the following code? ------------------------------------------- the_list = "alpha;beta;gamma".split(":") the_string = ''.join(the_list) print(the_string.isaplpha()) ------------------------------------------- A. it raises an exception B. it outputs True C. it outputs False D. it outputs nothing
A. it raises an exception
Which of the following lambda function definitions are correct? (Select two answers) A. lambda X : None B. lambda : 3,1415 C. lambda x : def fun(x): return x D. lambda lambda: lambda * lambda
A. lambda X : None D. lambda lambda: lambda * lambda
Assuming that the following snippet has been successfully executed, which of the equations are True? (Select two answers) ------------- a = [1] b = a a[0] = 0 ------------- A. len(a) == len (b) B. b[0] fe- 1 == a[0] C. a [0] == b [0] D. a[0] + 1 == b[0]
A. len(a) == len (b) C. a [0] == b [0] Code Analysis: 1. a = [1]: This creates a list a with one element 1. 2. b = a: This assigns b to the same list that a refers to. Now both a and b refer to the same list in memory. 3. a[0] = 0: This modifies the first element of the list a refers to, changing it from 1 to 0. Since b is also referring to the same list, this change is reflected in b as well. Evaluating Each Equation: A. len(a) == len(b) Both a and b refer to the same list, which has not changed in length throughout the operations. So the length of a is equal to the length of b. This statement is True. B. b[0] != 1 == a[0] This equation seems to be syntactically incorrect (fe- is not a valid operator). However, assuming it's meant to be b[0] != 1, we can analyze it. After the operations, both a[0] and b[0] are 0, not 1. So, it's true that b[0] is not 1. However, the complete statement with the == a[0] part is not clear due to the syntactical issue. If interpreted as "is b[0] not equal to 1 and equal to a[0]", the statement is still confusing and likely meant to be two separate comparisons. Given the likely intended meaning and ignoring syntax issues, b[0] is indeed 0, and so is a[0], but the exact correctness depends on the intended syntax and logical expression. C. a[0] == b[0] Since a and b refer to the same list, and only the first element of that list was changed, a[0] and b[0] are indeed equal, both being 0. This statement is True. D. a[0] + 1 == b[0] After the change, a[0] is 0. So, a[0] + 1 is 1. However, b[0] is also 0, as both a and b refer to the same modified list. Therefore, 1 is not equal to 0, making this statement False. Based on the analysis, the correct equations that are True are: A. len(a) == len(b) C. a[0] == b[0]
If you need a function that does nothing, what would you use instead of XXX? (Select two answers) -------------- def idler(): XXX -------------- A. pass B. return C. exit D. None
A. pass B. return In Python, if you need a function to do nothing, you would typically use the pass statement, which is a null operation — when it is executed, nothing happens. It's often used as a placeholder for functionality to be added later. Here are the suitable options: A. pass The pass statement is exactly for this purpose. It allows you to define a function that does nothing at all. It's syntactically needed to create an empty block. B. return The return statement can also effectively make a function do nothing, especially if it's the only statement in the function. It exits the function and returns a None by default if no value is specified. It's not as semantically clear as pass for indicating "do nothing" behavior, but functionally, it can result in a do-nothing function. Options C (exit) and D (None) are not used for creating a do-nothing function: exit: This is used to exit from Python. It's not appropriate for a do-nothing function, as it would terminate the program. None: Simply having None in the body of the function without a return statement wouldn't make it syntactically valid for a do-nothing function. However, return None explicitly would work similarly to return, but just None alone wouldn't serve as a placeholder for an action. So the correct answers are: A. pass B. return
There is a stream named s open for writing. What option will you select to write a line to the stream'' A. s.write("Hello\n") B. write(s, "Hello") C. s.writeln("Hello") D. s.writeline("Hello")
A. s.write("Hello\n")
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]? (Select two answers) --------------------------------------------- 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) Oblect.add_new () print(Object.get()) --------------------------------------------- A. self.queue.append(self.get_last() + 1) B. self.queue.append(get_last() + 1) C. self.queue.append(self.queue[-1] + 1) D. queue.append(self.get_last() + 1)
A. self.queue.append(self.get_last() + 1) C. self.queue.append(self.queue[-1] + 1) Given Class: - The class MyClass initializes with a queue list containing integers from 0 up to but not including size. - The get() method returns the current queue. - The get_last() method returns the last element of the queue. - The add_new() method is where we need to insert a line of code to make sure when Object.add_new() is called, the resulting queue is [0, 1, 2]. Evaluating Each Option: A. self.queue.append(self.get_last() + 1) This line gets the last element of the queue using self.get_last() method, adds 1 to it, and appends the result to the queue. This is a valid and working solution because self.get_last() properly retrieves the last element of the queue, which is 1 in this context (after initialization with size=2), and then adds 1 to it, resulting in 2 being appended. The queue would become [0, 1, 2]. B. self.queue.append(get_last() + 1) This line attempts to use get_last() without the self prefix, which is incorrect in the context of a class method because it would not be recognized as a method of the instance. This line will raise a NameError as get_last is not defined in the scope of the add_new method. C. self.queue.append(self.queue[-1] + 1) This line directly accesses the last element of the queue using self.queue[-1], adds 1 to it, and appends the result to the queue. This effectively does the same thing as option A but without calling the get_last() method. It's a more direct approach and also works flawlessly. D. queue.append(self.get_last() + 1) This line attempts to append to queue without the self prefix. In the context of a class method, queue needs to be accessed with self.queue to refer to the instance variable. Without self, it will raise a NameError as queue won't be recognized.
Which of the following expressions evaluate to True? (Select two answers) A. str(1-1) in '0123456739'[:2] B. 'phd' in 'alpha' C. 'dcb' not in 'abcde' [::-1] D. 'True' not in 'False'
A. str(1-1) in '0123456739'[:2] D. 'True' not in 'False'
What is the expected output of the following snippet? ------------------ i = 5 while i > 0: i = i//2 if i % 2 = 0: break else: i += 1 print(i) ------------------ A. the code is erroneous B. 3 C. 7 D. 15
A. the code is erroneous 1. i = 5: Sets the initial value of i to 5. 2. while i > 0:: Enters a loop that continues as long as i is greater than 0. 3. i = i//2: This line divides i by 2 using integer (floor) division and assigns the result back to i. 4. if i % 2 = 0:: This line is meant to check if i is even. However, the correct syntax for comparison is ==, not =. As it stands, i % 2 = 0 is a syntax error because it attempts to assign 0 to the expression i % 2, which is not valid. The correct line should be if i % 2 == 0: to check if i is even. 5. else: This else block is associated with the while loop and will execute only if the while loop completes without hitting a break statement. Given that the line if i % 2 = 0: contains a syntax error due to the use of a single equals sign (=) instead of the equality operator (==), the expected outcome is: A. the code is erroneous.
What is the expected behavior of the following code? ----------------------------------------------------------- my_list = [i for i in range(5, 0, -1)] 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 [2, 4] C. it outputs [4, 2] D. it outputs [0, 1, 2, 3, 4]
A. the code is erroneus and it will not execute The code provided has a syntax error in the list comprehension. The intended use seems to be to generate a list of even numbers from my_list in a certain order. Let's analyze the problematic part: Issues in this part of the code: The correct syntax for a conditional inside a list comprehension is [item for item in iterable if condition]. The given code seems to mistakenly place the if condition outside of the list comprehension brackets and does not match the correct syntax. The if condition if my_list[i] % 2 == 0 is placed as if it's filtering the whole list comprehension, but without proper use of the list comprehension syntax, it's not clear which i it refers to since it's outside the list comprehension. The correct way to write a list comprehension that filters my_list for even numbers would be something like: m = [x for x in my_list if x % 2 == 0] Given the erroneous syntax in the code snippet, the expected behavior is: A. the code is erroneous and it will not execute
What is true about Python class constructors? (Select two answers) A. the constructor's first parameter identifies an object currently being created B. the constructor cannot use the default values of the parameters C. the constructor can be invoked directly under strictly defined circumstances D. super-class constructor is invoked implicitly during constructor execution
A. the constructor's first parameter identifies an object currently being created C. the constructor can be invoked directly under strictly defined circumstances
A file name like this one below says that: (select three answers) ------------------------------ services.cpython-36.pyc ------------------------------ A. the interpreter used to generate the file is version 3.6 B. it has been produced by CPython C. it is the 36th version of the file D. the file comes from the services . py source file
A. the interpreter used to generate the file is version 3.6 B. it has been produced by CPython D. the file comes from the services . py source file
Which of the listed actions can be applied to the following tuple? (Select two answers) ---------- tup = () ---------- A. tup [:] B. tup.append (0) C. tup [0] D. del tup
A. tup [:] D. del tup Let's analyze each of the listed actions to see which can be applied to the tuple tup = (): A. tup[:] This is a slicing operation. Slicing can be applied to tuples, even if they are empty. It will return another tuple, which is a slice of the original tuple. In the case of an empty tuple, slicing it in any way will just return another empty tuple. This action is valid. B. tup.append(0) Tuples are immutable in Python, which means you cannot modify them after they are created. The append method is used to add an item to a list, not a tuple. This action will raise an AttributeError because tuples do not have an append method. This action is invalid. C. tup[0] This tries to access the first element of the tuple. However, tup is an empty tuple, and trying to access an element that doesn't exist will raise an IndexError. This action is invalid. D. del tup The del statement can be used to delete variables in Python. Using del tup would delete the entire tuple tup. It's a valid operation, but it's worth noting that it doesn't modify the tuple (as tuples are immutable); it simply removes the tuple from the namespace. This action is valid. Based on the analysis, the actions that can be applied to the tuple tup = () are: A. tup[:] D. del tup
How many elements will the list1 list contain after execution of the following snippet? -------------------------------------------- List1 = "don't think twice, do it!".split(',') -------------------------------------------- A. two B. zero C. one D. three
A. two The given code snippet creates a list called List1 by splitting the string "don't think twice, do it!" on the comma character ,. The .split(',') method will divide the string into elements of a list wherever it finds a comma. Let's break down the string: "don't think twice, do it!" When we split this string by the comma, we get two parts: "don't think twice" " do it!" So, after splitting the string by ',', there are two elements in the resulting list: "don't think twice" " do it!" Therefore, List1 will contain two elements after the execution of the snippet. The answer is: A. two.
Can a module run like regular code? A. yes, and it can differentiate its behavior between the regular launch and import B. it depends on the Python version C. yes, but it cannot differentiate its behavior between the regular launch and import D. no. it is not possible; a module can be imported, not run
A. yes, and it can differentiate its behavior between the regular launch and import
What can you do if you don't like a long package path like this one? ---------------------------------------------------- import alpha.beta.gamma.delta.epsilon.zeta ---------------------------------------------------- A. you can make an alias for the name using the alias keyword B. nothing; you need to come to terms with it C. you can shorten it to alpha.zeta and Python will find the proper connection D. you can make an alias for the name using die as keyword
A. you can make an alias for the name using the alias keyword
Assuming that the code below has been executed successfully, which of the following expressions evaluate to True? (Select two answers) ------------------------------ class Class: Var = data = 1 def __init__(self , value): self.prop = value Object = Class(2) ------------------------------ A. len(Class.__dict__) == 1 B. 'data' in Class.__dict__ C. 'Var' in Class.__dict__ D. 'data' in Object.__dict__
B. 'data' in Class.__dict__ C. 'Var' in Class.__dict__ Class and Object: 1. Class Definition:Var = data = 1: This line sets two class variables, Var and data, to the same value (1). They are both class-level attributes.def __init__(self, value): Defines an initializer that sets an instance variable self.prop to the given value.Object = Class(2): Creates an instance of Class named Object with prop set to 2. Evaluating Each Expression: A. len(Class.dict) == 1 Class.__dict__ contains all the attributes and methods of the class, including Var, data, and the __init__ method, among others (like __module__, __doc__, etc., which are default attributes). Since there are several items, the length of Class.__dict__ is certainly more than 1. This statement is False. B. 'data' in Class.dict data is a class variable set with Var = data = 1. It should be part of the class's dictionary. This statement is True. C. 'Var' in Class.dict Var is also a class variable defined with Var = data = 1. It is part of the class's dictionary. This statement is True. D. 'data' in Object.dict Object.__dict__ contains all the instance attributes for the object. Since data is a class variable and not an instance variable assigned to Object directly, it won't be in Object.__dict__, which only contains prop set to 2 in this case. This statement is False. Based on the analysis, the expressions that evaluate to True are: B. 'data' in Class.dict C. 'Var' in Class.dict
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','w') print(1, end='') s = f.readline() print(2, end='') except IOError as error: print(3, end='') else: f.close() print(4, end='') --------------------------------------- A. 2 2 B. 1 3 C. 1 2 3 D. 2 2 3
B. 1 3 Let's analyze the given code block by block to determine the expected output: try block: f = open('non_existing_file','w'): Opens a file named 'non_existing_file' in write mode ('w'). If the file does not exist, write mode will create the file, so this line should not throw an IOError. print(1, end=''): Prints 1 without moving to a new line. This should execute since the previous line would not throw an error. s = f.readline(): This line attempts to read a line from the file. However, the file is opened in write mode, not read or read/write mode. Thus, it's not possible to read from the file, and this operation will cause an IOError. except IOError as error: If an IOError occurs, as it does with the attempt to read from a file opened in write mode, this block will execute. It prints 3 without moving to a new line. else: This block executes if no exceptions were raised in the try block. In this case, it would close the file and print 4. However, because an IOError is raised, this block does not execute. Given the sequence of operations and the conditions provided: The file opens successfully in write mode. "1" is printed. An IOError occurs on attempting to read from the file, which is not opened in the correct mode for reading. "3" is printed as part of the exception handling. Therefore, the expected output of the code is "13". The answer is: B. 1 3.
What is the expected output of the following snippet? --------------------- s = 'abc' for i in len(s): s[i] = s[i].upper() print(s) --------------------- A. abc B. The code will cause a runtime exception C. ABC D. 123
B. The code will cause a runtime exception Let's analyze the code snippet to understand what it's doing and determine the expected output: s = 'abc': This initializes a string s with the value 'abc'. for i in len(s): This line attempts to iterate over the length of the string s. However, len(s) returns an integer, which is not iterable. You would typically use range(len(s)) to iterate over the indices of a string. As it stands, this line will raise a TypeError because integers are not iterable. s[i] = s[i].upper(): This line is intended to convert each character in the string to uppercase. However, strings in Python are immutable, which means you can't change them in place. Even if the iteration was corrected, attempting to assign s[i] a new value would raise a TypeError. Given the issues in the code: The loop will cause a runtime exception due to attempting to iterate over an integer (len(s)). Even if the iteration was corrected, attempting to modify the string in place would cause another runtime exception since strings are immutable. Therefore, the expected behavior of the code is: B. The code will cause a runtime exception.
What is the expected output of the following code? ---------------- str = 'abcdef' def fun (s): del s [2] return s print(fun(str) ---------------- A. abcef B. The program will cause a runtime exception error C. acdef D. abdef
B. The program will cause a runtime exception error Let's break down the given code to understand its behavior and determine the expected output: str = 'abcdef': This initializes a string str with the value 'abcdef'. def fun(s): This defines a function fun that takes a single argument s. del s[2]: Inside the function, this attempts to delete the character at index 2 of the string s. However, strings in Python are immutable, which means you cannot change them once they are created. This includes attempting to delete characters from them. return s: The function is intended to return the modified string. Given that strings in Python are immutable, attempting to modify them with del s[2] will raise a TypeError. The code will not successfully delete the character and instead will cause a runtime exception. Therefore, the expected behavior of the code is: B. The program will cause a runtime exception error.
What is the expected output of the following snippet? ---------------------------------------------- class X: pass class Y (X): pass class Z(Y): pass X = Z() Z = Z() print(isinstance (x, z), isinstance (z, X)) ---------------------------------------------- A. True False B. True True C. False False D. False True
B. True True
A property that stores information about a given class's super-classes is named: A. _upper_ B. _bases_ C. _ancestors_ D. _super_
B. _bases_
What can you deduce from the following statement? (Select two answers) --------------------------- str = open('file.txt', 'rt') --------------------------- A. str is a string read in from the file named file.txt B. a newlina character translation will be performed during the reads C. if file. txt does not exist, it will be created D. the opened file cannot be written with the use of the str variable
B. a newlina character translation will be performed during the reads D. the opened file cannot be written with the use of the str variable
What is the output of the following piece of code? -------------------------- a = 'ant' b = "bat" c = 'camel' print(a, b, c, sep = '"') -------------------------- A. ant'bat'camel B. ant"bat"camel C. antbatcamel D. ant bat camel
B. ant"bat"camel
Assuming that the following code has been executed successfully, select the expressions which evaluate to True. (Select two answers) ----------------------- var = 1 def f(): global var var += 1 def g(): return var return g a = f() b = f() ----------------------- A. a is b B. b() > 2 C. a() > 2 D. a is not None
B. b( ) > 2 C. a() > 2 D. a is not None To determine which expressions evaluate to True, let's first understand what the code is doing: Code Breakdown: Global Variable: var = 1: Initializes a global variable var with the value 1. Function f(): Declares var as a global inside the function. Increments var by 1 each time f() is called. Defines a nested function g() that returns the current value of var. Returns the function g (not the value of g(), but the function itself). Function Calls: a = f(): Calls f(), which increments var to 2 and assigns a to function g. b = f(): Calls f() again, which increments var to 3 and assigns b to a new instance of function g. Evaluating Each Expression: A. a is b False. Each call to f() creates a new instance of the nested function g(). So a and b are different instances of g and not the same object. B. b() > 2 True. When b is called (b()), it returns the current value of var, which is 3 after both calls to f(). Since 3 is greater than 2, this expression is True. C. a() > 2 False. Similar to b(), when a() is called, it returns the value of var at the time of its creation. After the first call to f(), var was 2. So a() returns 2, which is not greater than 2. D. a is not None True. a is assigned to the function g returned by the first call to f(). It is not None; it is a function object. So this expression is True. Based on the analysis, the expressions that evaluate to True are: B. b() > 2 D. a is not None
A class constructor (Select two answers) A. can return a value B. cannot be invoked directly from inside the class C. can be invoked directly from any of the subclasses D. can be invoked directly from any of the superclasses
B. cannot be invoked directly from inside the class C. can be invoked directly from any of the subclasses
A compiler is a program designed to (select two answers) A. rearrange the source code to make it clearer B. check the source code in order to see if its correct C. execute the source code D. translate the source code into machine code
B. check the source code in order to see if its correct D. translate the source code into machine code
The simplest possible class definition in Python can be expressed as: A. class X: B. class X: pass C. class X: return D. class X: {}
B. class X: pass
If you need to serve two different exceptions called Ex1 and Ex2 in one except branch, you can write: A. except Ex1 Ex2: B. except (Ex1, Ex2): C. except Ex1, Ex2: D. except Ex1+Ex2:
B. except (Ex1, Ex2): In Python, to handle multiple exceptions within a single except block, you should use a tuple to specify the exception classes you want to catch. The syntax involves enclosing the exception classes in parentheses and separating them with commas. The correct way to catch two different exceptions named Ex1 and Ex2 in one except branch is: B. except (Ex1, Ex2): This syntax allows the except block to handle either Ex1 or Ex2 exceptions that may be raised in the try block.
Select the valid fun () invocations: (select two answers) --------------------- def fun(a, b = 0): return a * b --------------------- A. fun(b=1) B. fun (a=0) C. fun(b=1, 0) D. fun (1)
B. fun (a=0) D. fun (1) Let's look at each invocation option considering the function definition def fun(a, b = 0):: a is a positional argument that doesn't have a default value; it must be provided in every call to the function. b is a keyword argument with a default value of 0. It can be omitted in the call, and 0 will be used, or it can be provided with a different value. Now let's evaluate the invocations: A. fun(b=1) This invocation only specifies b, but does not provide a value for the mandatory positional argument a. This would result in a TypeError as a is required. So, it's not a valid invocation. B. fun(a=0) This invocation correctly provides a value for a and uses the default value for b. It's a valid way to call the function. So, this is a valid invocation. C. fun(b=1, 0) Python does not allow a non-keyword argument (0) after a keyword argument (b=1). This would result in a SyntaxError. So, it's not a valid invocation. D. fun(1) This invocation provides a value for a and uses the default value for b. It's a simple and valid way to call the function. So, this is a valid invocation. Therefore, the valid fun() invocations are: B. fun(a=0) D. fun(1)
Assuming that the following piece of code has been executed successfully, which of the expressions evaluate to True? (Select two answers) ------------------------------ class A: VarA = 1 def __init__(self): self.prop_a = 1 class B(A): VarA = 2 def __init__(self): self.prop_a = 2 self.prop_aa = 2 class C(B): VarA = 3 def __init__(self): super().__init__() obj_a = A() obj_b = B() obj_c = C() ------------------------------ A. obj_b.prop_a == 3 B. hasattr(obj_b, 'prop_aa') C. isinstance(obj_c,A) D. B.VarA == 3
B. hasattr(obj_b, 'prop_aa') C. isinstance(obj_c,A) Classes and Instances: 1. Class A: Initializes prop_a to 1 and has a class variable VarA = 1. 2. Class B: Inherits from A, changes VarA to 2, and initializes prop_a and prop_aa to 2. 3. Class C: Inherits from B, changes VarA to 3, and in its constructor, it calls the constructor of its superclass, which is B. So prop_a and prop_aa are set to 2. Evaluating Each Expression: A. obj_b.prop_a == 3 obj_b is an instance of B. When B is instantiated, prop_a is set to 2, not 3. Therefore, this statement is False. B. hasattr(obj_b, 'prop_aa') obj_b is an instance of B, which initializes a prop_aa attribute in its constructor. Therefore, obj_b should have the attribute prop_aa. This statement is True. C. isinstance(obj_c, A) obj_c is an instance of C, which is a subclass of B, and B is a subclass of A. In Python, an object is considered an instance of both its class and all parent classes. Therefore, obj_c is indeed an instance of A. This statement is True. D. B.VarA == 3 Inside class B, VarA is set to 2. Class C does set VarA to 3, but this does not affect the VarA of class B. Therefore, B.VarA remains 2. This statement is False. Based on the analysis, the expressions that evaluate to True are: B. hasattr(obj_b, 'prop_aa') C. isinstance(obj_c, A)
A Python module named pymod, py contains a function named pyfun ( ). Which of the following snippets will let you invoke the function? (Select two answers) A. from pymod import * pymod.pyfun ( ) B. import pymod pymod.pyfun ( ) C. import pyfun from pymod.pyfun ( ) D. from pymod import pyfun pyfun ( )
B. import pymod pymod.pyfun ( ) D. from pymod import pyfun pyfun ( )
What is the expected behavior of the following code? ---------------------------------------------- class Class: Variable = 0 def __init__(self): self.value = 0 object_1 = Class() object_1.Variable += 1 object_2 = Class() object_2.value += 1 print(object_2.Variable + object_1.value) ---------------------------------------------- A. it outputs 1 B. it outputs 0 C. it raises an exception D. it outputs 2
B. it outputs 0 Let's break down the code to understand its behavior: 1. Class Definition: A class named Class is defined with:A class variable Variable initialized to 0.An instance variable value initialized to 0 in the __init__ constructor. 2. Creating object_1: An instance object_1 of Class is created. object_1.Variable += 1: This line seems to attempt to increment the class variable Variable. However, due to how Python's name resolution works, this doesn't actually change the class variable Variable for all instances but instead attaches a new instance attribute Variable to object_1 and sets it to 1. 3. Creating object_2: Another instance object_2 of Class is created. object_2.value += 1: This increments the value instance variable of object_2 by 1. The initial value is 0, so after incrementing, object_2.value becomes 1. 4. Print Statement: print(object_2.Variable + object_1.value): This line is adding object_2.Variable and object_1.value. For object_2.Variable: Since Variable was incremented in object_1 but not object_2, and because class variables are shared across instances, one might expect Variable to be 1. However, due to the way Python handles instance and class variables, object_1.Variable was actually creating and modifying an instance variable for object_1, not the class variable Class.Variable. So, object_2.Variable remains 0. For object_1.value: It was never modified and remains 0 as initialized. So, the print statement effectively adds 0 (object_2.Variable) + 0 (object_1.value), resulting in 0. Therefore, the expected output of the code is 0. The answer is B. it outputs 0.
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 list assignment index out of range C. the code is erroneous and it will not execute D. it outputs <class ' IndexError' >
B. it outputs list assignment index out of range
Which of the following lambda definitions are correct? (Select two answers) A. lanbda x, y; return x\\y - x%y B. lambda x, y: x//y - x%y C. lambda (x, y = x\\y x%y D. lambda x, y: (x, y)
B. lambda x, y: x//y - x%y D. lambda x, y: (x, y) Let's break down the code and its behavior: Function foo(x, y): Takes two arguments x and y. Returns the result of y(x) + (x+1). Lambda Function: The provided lambda function lambda x: x*x takes a single argument and returns the square of the argument. Calling foo: foo is called with 1 as x and the lambda function as y. Now, let's compute the values: y(x) = (lambda x: x*x)(1) = 1*1 = 1 x+1 = 1 + 1 = 2 So, foo(1, lambda x: x*x) returns 1 + 2 = 3. Therefore, the expected output of the code is 3. The answer is: A. 3.
What is true about Object-Oriented Programming in Python? (Select two answers) A. if a real-life object can be described with a set of adjectives, they may reflect a Python object method B. the same class can be used many times to build a number of objects C. each object of the same class can have a different set of methods D. a subclass is usually more specialized than its superclass
B. the same class can be used many times to build a number of objects D. a subclass is usually more specialized than its superclass
What is true about the following snippet? (Select two answers) -------------------------------------- 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 Exception ("what a pity") except E as e: print(e) else: print("the show must go on") -------------------------------------- A. the code will raise an unhandled exception B. the string I feel fine 'will be seen C. the string it's nice to see you will be seen D. the string what a pity will be seen
B. the string I feel fine 'will be seen D. the string what a pity will be seen
Which of the following expressions evaluate to True? (Select two answers) A. len('\') == 1 B. len("""""") == 0 C. chr(ord('A') + 1) == 'B' D. ord("Z") - ord("z") -- ord("0")
B. len("""""") == 0 C. chr(ord('A') + 1) == 'B' Let's evaluate each expression one by one: A. len('\') == 1 The expression here seems to be attempting to define a single backslash as a string, but it's incorrectly escaped. In Python, the backslash (\) is an escape character; to represent an actual backslash in a string, you need to use two backslashes (\\). As it stands, this expression will result in a syntax error due to the incorrect string literal. B. len("""""") == 0 This expression uses a triple-quoted string, which is valid syntax in Python for multi-line strings. However, since there's nothing between the triple quotes, the string is empty. Therefore, its length is indeed 0. This expression evaluates to True. C. chr(ord('A') + 1) == 'B' ord('A') returns the ASCII value of 'A', which is 65. Adding 1 gives 66, which is the ASCII value of 'B'. chr(66) then converts this back to the character 'B'. So, this expression essentially checks if 'B' equals 'B', which is True. D. ord("Z") - ord("z") -- ord("0") First, ord("Z") and ord("z") are the ASCII values for 'Z' and 'z', respectively. The ASCII value of 'Z' is 90, and 'z' is 122. ord("0") is the ASCII value for '0', which is 48. The expression includes a double negative (--), which is equivalent to a plus. So, the expression becomes 90 - 122 + 48. Doing the math, 90 - 122 + 48 = 16, which is not 0; therefore, this expression does not equal true. Based on this analysis, the expressions that evaluate to True are: B. len("""""") == 0 C. chr(ord('A') + 1) == 'B'
How many lines does the following snippet output? ----------------------- for i in range(1, 3): print("*", end = "") else: print("*") ---------------------- A. three B. one C. two D. four
B. one Let's break down the code and see what it does: 1. for i in range(1, 3): - This for loop iterates over a range from 1 to 2 (since range in Python is up to, but not including, the stop value). The loop will iterate exactly two times. 2. print("*", end = "") - Within the loop, it prints a * without moving to a new line (due to end = ""). This part of the code will execute twice due to the loop, resulting in **. 3. else: - This block executes after the for loop completes. The else associated with a for loop is not like the else in an if statement; it doesn't check a condition but rather executes after the loop finishes normally (i.e., not broken by a break statement). print("*") - This prints another * and moves to a new line (since no end parameter is specified, it defaults to a new line). Combining the prints from the for loop and the else block, the output would be *** on a single line, as there's no line break until after the else block's print statement. Therefore, the number of lines the snippet outputs is: B. one.
Which of the following statements are true? (Select two answers) A. open () requires a second argument B. open () is a function which returns an object that represents a physical file C. instd, outstd, errstd are the names of pre-opened streams D. if invoking open () fails, an exception is raised
B. open () is a function which returns an object that represents a physical file D. if invoking open () fails, an exception is raised
Which one of the platform module functions should be used to determine the underlying platform name? A. platform.uname () B. platform.platform () C. platform.python_version() D. platform.processor()
B. platform.platform ()
What is the expected behavior of the following code? ------------------------------ def f (n): for i in range(1, n + 1): yield I print(f(2)) ------------------------------ It will: A. print 4321 B. print <generator object f at (some hex digits)> C. cause a runtime exception D. print 1234
B. print <generator object f at (some hex digits)>
What is the expected behavior of the following code? ----------------------------- def f (n): for i in range(1, n + 1): yield I print(f(2)) ----------------------------- It will: A. print 4321 B. print <generator object f at (some hex digits)> C. cause a runtime exception D. print 1234
B. print <generator object f at (some hex digits)> Let's analyze the provided code snippet: Function Definition: def f(n): Defines a generator function f that takes a single argument n. for i in range(1, n + 1): Iterates from 1 to n inclusive. yield I: Attempts to yield the variable I. However, there is a typo here. It seems like it should be yield i, with lowercase 'i', which is the loop variable. As written, I is not defined anywhere in the function. Calling the Function: print(f(2)): This line calls the generator function with an argument of 2. Instead of iterating over the generator to retrieve its values, this line attempts to print the generator object itself. Normally, printing a generator object in Python displays its memory address in the format "<generator object f at 0x...>". However, there's a critical issue in the code: the use of I instead of i in the yield statement. Since I is not defined, attempting to call this function will result in a NameError at runtime due to the undefined name I. Therefore, the expected behavior of the code is: C. cause a runtime exception.
Assuming that the snippet below has been executed successfully, which of the following expressions evaluate to True? (Choose two.) ----------------------------------------- string = 'SKY'[::-1] string = string[-1] ----------------------------------------- A. string[0] == 'Y' B. string[0] == string [-1] C. string is None D. len(string) == 1
B. string[0] == string [-1] D. len(string) == 1 Let's analyze the provided code to determine the value of string and then evaluate each expression: Code Analysis: string = 'SKY'[::-1]: This reverses the string 'SKY', resulting in 'YKS'. string = string[-1]: This sets string to the last character of 'YKS', which is 'S'. After executing these two lines, the value of string is 'S'. Evaluating Each Expression: A. string[0] == 'Y' string[0] is the first character of string, which is 'S', not 'Y'. This statement is False. B. string[0] == string[-1] Since string is 'S', both string[0] and string[-1] refer to the same character, 'S'. This statement is True. C. string is None string is set to 'S', not None. This statement is False. D. len(string) == 1 string is 'S', which is a single character. Therefore, the length of string is indeed 1. This statement is True. Based on the analysis, the expressions that evaluate to True are: B. string[0] == string[-1] D. len(string) == 1
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 2 B. the code is erroneous and it will not execute C. it outputs 1 D. it outputs 3
B. the code is erroneous and it will not execute except ArithmeticError is missing colon
The following expression 1 +-2 is: A. equal to 1 B. invalid C. equal to 2 D. equal to -1
D. equal to -1
Which of the following expression evaluate to True? (Select two answers) A. 'in not' in 'not' B. 'in' in 'Thames' C. 't'.upper ( ) in 'Thames' D. 'in' in 'in'
C. 't'.upper ( ) in 'Thames' D. 'in' in 'in' Let's evaluate each expression one by one to determine which ones are True: A. 'in not' in 'not' This expression checks if the substring 'in not' is found within the string 'not'. Clearly, 'in not' is longer and not a substring of 'not'. This expression is False. B. 'in' in 'Thames' This expression checks if the substring 'in' is found within the string 'Thames'. The substring 'in' does not appear in 'Thames'. This expression is False. C. 't'.upper() in 'Thames' 't'.upper() converts 't' to uppercase, resulting in 'T'. This expression checks if 'T' is found within the string 'Thames'. Since 'Thames' does start with a 'T', this expression is True. D. 'in' in 'in' This expression checks if the substring 'in' is found within the string 'in'. A string always contains itself, so this expression is True. Based on the evaluation, the expressions that evaluate to True are: C. 't'.upper() in 'Thames' D. 'in' in 'in'
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. 1 B. 0 C. -1 D. an exception is raised
C. -1 To determine the expected output of the given code snippet, let's first analyze the function foo: 1. Function foo(x,y,z): Takes three arguments x, y, and z. Returns the result of x(y) - x(z). 2. Lambda Function: The provided lambda function lambda x: x % 2 takes a single argument and returns the remainder of the argument divided by 2. 3. Calling foo: foo is called with the lambda function as x, 2 as y, and 1 as z. Now, let's compute the values: - x(y) = (lambda x: x % 2)(2) = 2 % 2 = 0 - x(z) = (lambda x: x % 2)(1) = 1 % 2 = 1 So, foo(lambda x: x % 2, 2, 1) returns 0 - 1 = -1. Therefore, the expected output of the code is -1. The answer is: C. -1.
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 B. 1 2 3 C. 1 3 D. 2 3
C. 1 3 Let's analyze the code to understand its flow and determine the expected output: try block: f = open('existing_file', 'w'): Opens a file named 'existing_file' in write mode ('w'). If 'existing_file' is indeed the name of a file located in the working directory, this operation should succeed. When opening a file in write mode, if the file exists, it is truncated to zero length (essentially cleared), but it will not cause an IOError just because the file exists. print(1, end=' '): Prints 1 followed by a space, without moving to a new line. This should execute successfully if the file opens without issues. except IOError as error: This block would execute if there was an IOError during the try block. Given the information that 'existing_file' exists and no other issues are mentioned, this block is unlikely to be executed. else: This block executes if the try block doesn't raise an exception. Here, f.close() will close the file, and print(3, end=' ') will print 3 followed by a space. Given the sequence of operations and the conditions provided, the try block should execute successfully, printing "1 ". Then, since no exception is raised, the else block should execute, closing the file and printing "3 ". There is no output for "2" because the except block is not executed. Therefore, the expected output of the code is: C. 1 3
What is the expected output of the following snippet? ------------------ 1st = [1, 2, 3, 4] 1st = 1st[-3:-2] 1st = 1st[-1] print(1st) ------------------ A. 1 B. 4 C. 2 D. 3
C. 2 Let's go through the code snippet step by step to understand what it's doing and determine the expected output. However, before we proceed, it's important to note that 1st is not a valid Python variable name as variable names cannot begin with a number. Assuming it's a typo and replacing 1st with a valid variable name, such as lst, let's proceed: lst = [1, 2, 3, 4]: The list contains four elements: 1, 2, 3, and 4. lst = lst[-3:-2]: This slice takes elements from the third-last to the second-last, not including the second-last. In other words, it takes just the second element of the list, which is 2. So now lst is [2]. lst = lst[-1]: This takes the last element of the list, which is the only element, 2. The final value of lst (originally 1st) is 2. Therefore, the expected output of the code is: C. 2.
An operator able to perform bitwise shifts is coded as. (select two answers) A. -- B. ++ C. << D. >>
C. << D. >>
Assuming that the V variable holds an integer value to 2, which of the following operators should be used instead of OPER to make the expression equal to 1? --------------- V OPER 1 - --------------- A. <<< B. >>> C. >> D. <<
C. >> In the context of integers and common programming operators, << and >> typically represent bitwise shift operations: <<: Left shift >>: Right shift The question is asking which operator can be used in place of OPER in the expression V OPER 1 to make the result equal to 1, given that V is 2. Let's analyze what each shift operation does: Left shift (<<): V << 1 means shifting the binary representation of V left by 1 bit. Since V is 2 (binary 10), shifting it left by one bit results in 100 binary, which is 4 in decimal. This does not result in 1. Right shift (>>): V >> 1 means shifting the binary representation of V right by 1 bit. Since V is 2 (binary 10), shifting it right by one bit results in 1 binary, which is 1 in decimal. This does result in 1. The other options provided are not standard operators in most programming languages: <<< and >>> are not standard bitwise operators in languages like Python, C++, or Java. Given the context of the question, we need the expression to result in 1. The right shift by 1 position (V >> 1) will take the integer 2, represented as 10 in binary, and shift it right by one bit, resulting in 1 binary, which is equal to 1 decimal. Therefore, the correct operator to use is: C. >>
A Python module named pymod.py contains a variable named pyvar. Which of the following snippets will let you access the variable? A. import pyvar from pymod pyvar = 1 B. from pymod import pyvar = 1 C. from pymod import pyvar pyvar () D. import pymod pymod.pyvar = 1
D. import pymod pymod.pyvar = 1
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? ------------------------------ class ClassA: var = 1 def __init__(self, prop): propl = prop2 = prop def __str__(self): return class ClassB(ClassA): def __init__(self, prop): prop3 = prop ** 2 super().__init__(prop) Object = ClassB(2) ------------------------------ A. str(Object) == 'Object' B. __name__ == 'code.py' C. ClassA.__module__ == '__main__' D. len(ClassB.__bases__) == 2
C. ClassA.__module__ == '__main__' Evaluation: A. str(Object) == 'Object' Since the __str__ method in ClassA is defined with an incorrect indentation and without a proper return statement, it effectively does not alter the default string representation of Object. The default __str__ method would not return the string 'Object'. This expression is False. B. name == 'code.py' The __name__ variable in Python is set to '__main__' when the script is run as the main program. If the file is being imported as a module, __name__ would be set to the module's name. Neither would it ever be 'code.py', so this expression is False. C. ClassA.module == 'main' Assuming this code is part of the main script that's being executed (not imported as a module), ClassA.__module__ would indeed be '__main__'. This is typically the case when you directly run a script. This expression is likely True. D. len(ClassB.bases) == 2 ClassB is defined as inheriting from ClassA, meaning it has only one direct base class. Thus, ClassB.__bases__ would contain a single element, the ClassA class, making its length 1, not 2. This expression is False. Based on the analysis above, the expressions that evaluate to True are: C. ClassA.module == 'main'
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. True lower B. True upper C. False upper D. False lower
C. False upper Let's analyze the given code snippet step by step to determine the expected output: 1. Class Definitions: - Upper: This class has a method called method that returns the string 'upper'. - Lower: This class inherits from Upper and overrides the method to return the string 'lower'. 2. Instantiating Object: - Object = Upper(): Creates an instance Object of the Upper class. 3. Print Statements: - print(isinstance(Object,Lower), end=''): This checks if Object (which is an instance of Upper) is an instance of Lower. Since Object is an instance of Upper, not Lower, this will return False. The end='' part ensures that the next print statement continues on the same line without a newline. - print(Object.method()): This calls the method on the Object. Since Object is an instance of Upper, the method from the Upper class will be called, returning the string 'upper'. Combining the results: - The first print statement will output False because Object is an instance of Upper, not Lower. - The second print statement will output 'upper' because that's the string returned by the method of the Upper class. Therefore, the expected output of the code snippet is "False upper". The answer is: C. False upper.
Which of the following statements are true? (Select two answers) A. \e is an escape sequence used to mark the end of lines B. ASCII is synonymous with UTF-8 C. II in ASCII stands for Information Interchange D. a code point is a number assigned to a given character
C. II in ASCII stands for Information Interchange D. a code point is a number assigned to a given character
Which of the following statements are true? (Select two answers) A. a code point is a point inside the code when execution stops immediately B. an escape sequence can be recognized by the # sign put in front of it. C. UTF-8 is one of the ways of representing UNICODE code points. D. ASCII is the name of a character coding standard
C. UTF-8 is one of the ways of representing UNICODE code points. D. ASCII is the name of a character coding standard
Python's built-in function named open () tries to open a file and returns: A. an integer value identifying an opened file B. an error code (0 means success) C. a stream object D. always None
C. a stream object
Assuming that the following snippet has been successfully executed, which of the equations are False? (Select two answers) ----------- a = [0] b = a[:] a[0] = 1 ----------- A. len(a)== len (b) B. a [0]-1 ==b [0] C. a[0] = b[0] D. b[0] - 1 == a[0]
C. a[0] = b[0] D. b[0] - 1 == a[0] Let's analyze the code to understand what it does and then evaluate each equation: Code Analysis: 1. a = [0]: This creates a list a with one element 0. 2. b = a[:]: This creates a new list b as a copy of list a. Now b is a separate list with the same content as a. 3. a[0] = 1: This modifies the first element of the list a to 1. List b remains unchanged. Evaluating Each Equation: A. len(a) == len(b) Both a and b are lists with one element each, even after modifying a. Their lengths are equal. So this statement is True. B. a[0] - 1 == b[0] After the change, a[0] is 1. So, a[0] - 1 is 0. b[0] is also 0 because b was copied from a before a was changed. Thus, a[0] - 1 is indeed equal to b[0]. This statement is True. C. a[0] = b[0] This is a syntactic error. = is an assignment operator, not a comparison operator. The correct comparison operator is ==. If corrected, the statement a[0] == b[0] would be comparing 1 (the value of a[0] after modification) to 0 (the original value of b[0]). They are not equal, so the corrected statement would be False. However, as written, this is a syntax error and thus False as a logical statement. D. b[0] - 1 == a[0] b[0] is 0 as it was copied from a before a was changed. So, b[0] - 1 is -1. a[0] is 1 after the change. Clearly, -1 is not equal to 1. This statement is False. Based on the analysis, the equations that are False are: C. a[0] = b[0] (due to syntax error, interpreting as a logical statement) D. b[0] - 1 == a[0]
If you want to access an exception object's components and store them in an object called e, you have to use the following form of exception statement A. except Exception(e): B. except e=Exception: C. except Exception as e: D. such an action is not possible in Python
C. except Exception as e:
Which of the following statement are true? (Select two answers) A. closing an open file is performed by the closefile ( ) function B. the second open ( ) argument describes the open mode and defaults to 'w' C. if open ( )'s second argument is 'r' the file must exist or open will fail D. if open ( )'s second argument is 'w' and the invocation succeeds, the previous file's content is lost
C. if open ( ) `s second argument is `r' the file must exist or open will fail D. if open ( )'s second argument is `w' and the invocation succeeds, the previous file's content is lost Let's evaluate each statement to determine its truthfulness: A. closing an open file is performed by the closefile() function This is incorrect. In Python, an open file is closed using the close() method on the file object, not a function called closefile(). So this statement is False. B. the second open() argument describes the open mode and defaults to 'w' This is incorrect. The second argument of open() indeed describes the mode, but it defaults to 'r' for reading, not 'w' for writing. So this statement is False. C. if open()'s second argument is 'r' the file must exist or open will fail This is true. When opening a file in read mode ('r'), the file must exist. If it doesn't, Python will raise a FileNotFoundError. So this statement is True. D. if open()'s second argument is 'w' and the invocation succeeds, the previous file's content is lost This is true. When opening a file in write mode ('w'), the file is created if it doesn't exist. If it does exist, the file is truncated to zero length (i.e., its content is erased) before the new writing begins. So this statement is True. Based on the analysis, the statements that are true are: C. if open()'s second argument is 'r' the file must exist or open will fail D. if open()'s second argument is 'w' and the invocation succeeds, the previous file's content is lost
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 0 B. it outputs 1 C. it raises an exception D. it outputs 2
C. it raises an exception 1. Classes Setup: Super class has two methods:make(), which returns 0.doit(), which returns the result of self.make(). However, the doit() method is not properly indented to be part of the Super class as intended. It should be indented to be within the class definition. As it is written, it's defined as a standalone function, which will cause an error when trying to call doit() method on instances of Super or its subclasses. This will likely be the source of an exception. Sub_A inherits from Super and overrides the make() method to return 1. Sub_B also inherits from Super but does not override any methods. 2. Creating Instances: a = Sub_A(): An instance of Sub_A is created. b = Sub_B(): An instance of Sub_B is created. 3. Print Statement: Attempting to call a.doit() and b.doit() and add the results together. Now, let's evaluate the behavior: Both a and b are supposed to have the method doit(), which calls self.make(). However, due to the incorrect indentation of doit(), it's not actually a method of either class. This means when the code tries to execute a.doit() or b.doit(), it will raise an AttributeError, as instances of Sub_A and Sub_B won't have a doit() method. Moreover, even if doit() were correctly defined within the Super class, it would work as follows: a.doit(): Since a is an instance of Sub_A, a.make() would return 1. b.doit(): Since b is an instance of Sub_B and Sub_B doesn't override make(), it would use Super's make() method and return 0. However, because of the indentation error of the doit() function, the actual behavior when attempting to execute the given code will be: C. it raises an exception The expected behavior of the code is that it will raise an exception due to the doit function not being correctly defined as a method of the Super or its subclasses.
What is the expected behavior of the following code? ------------------------------------ string = str(1/3) dummy = '' for character in strong : dummy= character + dummy print(dummy[-1]) ------------------------------------ A. it outputs 'None' B. it outputs 3 C. it raises an exception D. it outputs 0
C. it raises an exception Let's break down the given code snippet to understand its expected behavior: 1. string = str(1/3) This will set string to the string representation of 1331, which is '0.3333333333333333' (or a similar fraction representation depending on the precision). 2. dummy = '' Initializes an empty string named dummy. 3. for character in strong: This appears to be a typo in the provided code. It should be string instead of strong. Since Python will not find a variable named strong, it will raise a NameError when trying to iterate over it. 4. dummy = character + dummy This line intends to reverse the string by prepending each character of string to dummy. However, due to the typo, this part of the code will not execute. 5. print(dummy[-1]) This line would print the last character of the dummy string if the for loop had run successfully. Given the typo in the loop (for character in strong :), the code will raise a NameError as it attempts to iterate over a variable (strong) that does not exist. The correct variable name should be string. So, the expected behavior of the code is: C. it raises an exception.
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]? (Select two answers) ----------------------------------------- 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. put self.store(1]) B. self put stire(1]) C. self .put self.get () [-1]) D. self .put (self.store[1])
C. self .put self.get () [-1]) D. self .put (self.store[1]) Given Class: The class MyClass initializes with an initial list assigned to self.store. put(self, new): Adds a new element to the store list. get(self): Returns the store list. The dup() method is where we need to insert a line of code to duplicate the last element of store, making the output [0, 1, 1]. Evaluating Each Option: A. put self.store(1]) This line of code contains syntax errors and does not follow the proper Python syntax for calling methods or accessing list elements. It will not execute flawlessly. B. self put stire(1]) This line is a jumble of words and is not valid Python syntax. It will not execute flawlessly. C. self.put(self.get()[-1]) This line correctly calls the put method of self and passes the last element of the store list as an argument. self.get()[-1] correctly retrieves the last element of the store list, and self.put() correctly adds it to the store. This should work to duplicate the last element of the list, making the output [0, 1, 1]. D. self.put(self.store[1]) This line tries to duplicate the element at index 1 of the store list (self.store[1]). Given that the initial list is [0] and then 1 is added, self.store[1] refers specifically to the second element (which is 1), which seems correct at a glance. However, since the task is to duplicate the last element of the list, if the list changes in size or the contents vary, this code would not always work as intended. It would work in this specific case since self.store[1] is indeed the last element after the sequence of operations, but it's not a general solution for duplicating the last element of any list. For robustness and correct duplication of the last element regardless of the list's size, we typically use indexing like [-1].
What is the expected behavior of the following code? ----------------------- x = 3 % 1 y = 1 if x > 0 else 0 print(y) ----------------------- A. it outputs -1 B. the code is erroneous and it will not execute C. it outputs 1 D. it outputs 0
D. it outputs 0 Let's break down the code and understand the expected behavior: x = 3 % 1: This performs the modulo operation, finding the remainder of 3 divided by 1. The remainder of any number divided by 1 is always 0, so x is assigned the value 0. y = 1 if x > 0 else 0: This line uses a ternary conditional operator to assign a value to y. It checks if x is greater than 0. If true, y would be assigned 1; otherwise, y is assigned 0. Since x is 0, the condition x > 0 is False. print(y): This will print the value of y, which is determined by the conditional statement in the previous line. Since x is not greater than 0, y is assigned 0. Therefore, the expected output of the code is: D. it outputs 0.
How many elements will the list2 list contain after execution of the following snippet? -------------------------------------- list1 = [False for i in range (1, 10)] list2 = list1 [-1:1:-1] -------------------------------------- A. zero B. five C. seven D. three
C. seven Let's break down the code to understand how list1 and list2 are constructed: list1 = [False for i in range (1, 10)]: This list comprehension creates a list of 9 elements, all set to False. The range is from 1 to 9 (since range in Python is exclusive of the second number), resulting in 9 elements. list2 = list1[-1:1:-1]: This line creates list2 as a slice of list1. Here's how the slicing works: list1[-1]: This is the last element of list1. 1: This is the stop index, not inclusive. In Python, slicing is up to but not including the end index. -1: This is the step, indicating that we're going backward through the list. The slice starts at the last element and goes backward to the second element (index 1) because the stop index is not inclusive. The indices involved in the slice are -1 (last element), -2, -3, ... up to the second element (index 1) of the original list. So, let's count: Starting from the last element (index 8 or -1 in negative indexing) up to (but not including) index 1. This includes elements at indices 8, 7, 6, 5, 4, 3, and 2 (or -1, -2, -3, -4, -5, -6, -7 in negative indices). Counting those elements, you have 7 elements in total. Therefore, the list list2 will contain seven elements after execution of the snippet. The answer is: C. seven.
Which of the following words can be used as a variable name? (Select two valid names) A. for B. True C. true D. For
C. true D. For
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. 0 B. -1 C. an errno value corresponding to file not found D. 1
D. 1 Let's analyze what the code is expected to do: try block: f = open('non_zero_length_existing_text_file', 'rt'): Opens a file named 'non_zero_length_existing_text_file' in read text mode ('rt'). If the file exists, as stated in the question, and there are no permissions issues or other IO problems, this operation should succeed. d = f.read(1): Reads 1 character from the file. Since the file is specified to be of non-zero length, this will read the first character and store it in d. print(len(d)): Prints the length of the string d. Since d contains one character read from the file, len(d) will be 1. f.close(): Closes the file. except IOError: This block is designed to print -1 if an IOError occurs during the file operation. However, since the file is said to exist and be of non-zero length, it's unlikely that an IOError will occur for reading one character, assuming normal conditions (like the file is not locked, the program has read permissions, etc.). Given the provided conditions and the operation of the code, the file opens successfully, reads one character, and closes. The print(len(d)) statement will output the length of the string d, which is 1, as it contains one character. Therefore, the expected output of the code is: D. 1.
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. 16 C. an exception is raised D. 1
D. 1 To understand the expected output of the code, let's break it down: 1. myli = range(-2, 2): This creates a range object from -2 to 1 (since the upper bound in range is non-inclusive). So, myli is [-2, -1, 0, 1]. 2. m = list(filter(lambda x: True if abs(x) < 1 else False, myli)): This line filters myli using a lambda function. The lambda function returns True if the absolute value of x is less than 1, otherwise returns False. The only number in myli whose absolute value is less than 1 is 0. Therefore, the filter will keep only 0. 3. print(len(m)): This prints the length of list m. Since m contains only one element (0), its length is 1. Therefore, the expected output of the code is the length of the filtered list, which is 1. The answer is: D. 1.
What will the value of the i variable be when the following loop finishes its execution? ---------------------- for i in range (10): pass ---------------------- A. 10 B. the variable becomes unavailable C. 11 D. 9
D. 9 When a for loop iterates over a range in Python, the loop variable (i in this case) takes each value in the range sequentially. The range(10) function generates a sequence of numbers from 0 to 9 (10 numbers in total, as it starts counting from 0 up to, but not including, 10). The for i in range(10): loop will iterate with i taking values from 0 to 9. After the loop finishes, i retains the last value it was assigned during the loop, which is 9, since the range is up to but not including 10. The pass statement inside the loop is simply a placeholder that does nothing; it allows for the syntax to be correct, but doesn't affect how the loop operates or what happens to i. Therefore, when the loop finishes its execution, the value of i will be: D. 9.
The following class hierarchy is given. What is the expected output of the code? --------------------------- class A: def a (self): print("A", end='') def b (self): self.a() class B(A): def a (self): print("B", end = '') def do (self): self.b() class C(A): def a (self): print("C", end = '') def do (self): self.b() B().do() C().do() --------------------------- A. BB B. CC C. AA D. BC
D. BC Let's analyze the given class hierarchy and the calls made to understand the expected output: Class A: Has two methods:a(self): Prints "A".b(self): Calls self.a(). Class B (inherits from A): Overrides a(self): Prints "B". Defines do(self): Calls self.b(). Class C (inherits from A): Overrides a(self): Prints "C". Defines do(self): Calls self.b(). Execution: B().do(): This creates an instance of B and calls its do() method.do() calls self.b(), which is inherited from A.b() then calls self.a(), which refers to B's overridden a() method.So, it prints "B". C().do(): This creates an instance of C and calls its do() method.do() calls self.b(), which is inherited from A.b() then calls self.a(), which refers to C's overridden a() method.So, it prints "C". Putting it all together, when B().do() is called, it prints "B". Then, when C().do() is called, it prints "C". So, the expected output is the sequence "BC". Therefore, the expected output of the code is: D. BC.
A variable stored separately in every object is called: A. there are no such variables, all variables are shared among objects B. a class variable C. an object variable D. an instance variable
D. an instance variable
You are going to read just one character from a stream called s. Which statement would you use? A. ch = read(s, 1) B. ch = s. input(1) C. ch = input(s, 1) D. ch = s. read(l)
D. ch = s. read(l)
What is the expected behavior of the following code? --------------------------------------------- class Class: __Var = 0 def foo (self ): Class._Class__Var += 1 self.__prop = Class._Class__Var o1 = Class() o1.foo o2 = Class() o2.foo () print (o2._Class__Var + o1._Class__prop) --------------------------------------------- A. it outputs 6 B. it outputs 1 C. it outputs 3 D. it raises an exception
D. it raises an exception 1. Class Definition: __Var = 0: This line declares a private class variable __Var and initializes it to 0. In Python, double underscores at the start of a variable name are used to make the variable private and mangle the name to _Class__Var. def foo(self): This line defines a method foo for the class. Inside foo, Class._Class__Var += 1: This line attempts to increment the private variable __Var. The syntax Class._Class__Var is used to access the mangled version of __Var. self.__prop = Class._Class__Var: This line is incorrectly placed and will cause a syntax error. It should be inside a method (like __init__ or foo), but it's directly inside the class body. This will lead to a syntax error when the class is defined. 2. Instantiating Objects: o1 = Class(): Creates an instance o1 of Class. o1.foo: This line is just a reference to the foo method and does not call it. To call the method, it should be o1.foo(). o2 = Class(): Creates another instance o2 of Class. o2.foo(): This properly calls the foo method on o2. 3. Print Statement: print (o2._Class__Var + o1._Class__prop): This attempts to print the sum of o2's private variable _Class__Var and o1's private variable _Class__prop. However, __prop was incorrectly set at the class level and not as an instance variable due to the syntax error. Given the code's syntax errors and issues: - The line self.__prop = Class._Class__Var is incorrectly placed in the class body and will cause a syntax error. - The method o1.foo is never called due to missing parentheses. Therefore, the expected behavior is that the code will raise a syntax error due to the incorrect placement of self.__prop = Class._Class__Var within the class body. The answer is: D. it raises an exception.
What is the expected behavior of the following snippet? --------------- def x(): return 2 x = 1 + x() print(x) --------------- It will: A. cause a runtime exception on line 02 B. cause a runtime exception on line 01 C. cause a runtime exception on line 03 D. print 3
D. print 3 Let's analyze the code to understand its behavior: Function Definition: def x():: This defines a function x that takes no arguments. return 2: The function x returns 2 when called. Function Call and Reassignment: x = 1 + x(): This line calls the function x() which returns 2, then adds 1 to this result and assigns the sum (3) to x. After this line is executed, x is no longer a function; it's now an integer with the value 3. Print Statement: print(x): This line prints the current value of x, which is 3. There is no syntax or logical error in the code. The function x is defined and called correctly, and its return value is used in an arithmetic operation. The fact that x is reassigned from a function to an integer does not cause an error in this context; it just changes what x refers to. Therefore, the expected behavior of the code is: D. print 3.
Assuming that the snippet below has been executed successfully, which of the following expressions will evaluate to True? --------------------------------- string = 'python' [::2] string = string[-1] + string[-2] --------------------------------- A. string[0] == string[-1] B. string is None C. len(string] == 3 D. string[0] == 'o'
D. string[0] == 'o' First, let's break down the given code snippet step by step to understand what the variable string ends up as: 1. string = 'python'[::2] This slices the string 'python' from start to end with a step of 2. This means it takes every second character from the string 'python', resulting in 'pto'. 2. string = string[-1] + string[-2] Now, string is 'pto' from the first operation. string[-1] is the last character of 'pto', which is 'o'. string[-2] is the second last character of 'pto', which is 't'. So, it concatenates 'o' + 't', resulting in string being 'ot'. Now let's evaluate the given expressions with string = 'ot': A. string[0] == string[-1] string[0] is 'o', and string[-1] is also 't'. So, this statement is False. B. string is None Clearly, string is 'ot', not None. So, this statement is False. C. len(string) == 3 The length of 'ot' is 2, not 3. So, this statement is False. D. string[0] == 'o' The first character of string ('ot') is 'o'. So, this statement is True. Therefore, the expression that will evaluate to True is: D. string[0] == 'o'.
What is the expected output of the following snippet? -------------- a = 2 if a > 0: a += 1 else: a -= 1 print(a) -------------- A. 3 B. 1 C. 2 D. the code is erroneous
D. the code is erroneous else: shold not be indented