PCAP Set 2

Ace your homework & exams now with Quizwiz!

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

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

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

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.

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 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.

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(1)

D. ch = s. read(l)

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()

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 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 ---------------

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 --------------------------- def f (n): if n == 1: return '1' return str (n) + f (n-1) print(f(2)) --------------------------- note that '1' has quotes 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 -------------------------------- def foo(x,y): return y(x) + (x+1) print(foo(1, lambda x: x*x)) --------------------------------

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 ----------------- def a (i, I): return i [I] print(a(0,[i])) ----------------- 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.

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 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 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".

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

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

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")

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 ------------------ i = 5 while i > 0: i = i//2 if i % 2 = 0: break else: i += 1 print(i) ------------------ 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.

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 -------------------------------------------- List1 = "don't think twice, do it!".split(',') -------------------------------------------- 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.

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]

Assuming that the following snippet has been successfully executed, which of the equations are True? A. len(a) == len(b) C. a[0] == b[0]

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

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 --------------------- s = 'abc' for i in len(s): s[i] = s[i].upper() print(s) --------------------- 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 ---------------- str = 'abcdef' def fun (s): del s [2] return s print(fun(str) ---------------- 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

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 newline 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 newline 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

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

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)

Which of the following lambda definitions are correct? (Select two answers) A. lambda 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)

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 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 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

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 ------------------ 1st = [1, 2, 3, 4] 1st = 1st[-3:-2] 1st = 1st[-1] print(1st) ------------------ 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. >>

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 Python's built-in function named open() tries to open a file and returns:

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]

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

C. cause a runtime exception ----------------------------- def f (n): for i in range(1, n + 1): yield I print(f(2)) ----------------------------- 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.

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

C. cause a runtime exception ------------------------------ def f (n): for i in range(1, n + 1): yield I print(f(2)) ------------------------------

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:

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 --------------------------- 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 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

The following expression 1 +-2 is: A. equal to 1 B. invalid C. equal to 2 D. equal to -1

D. equal to -1

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 --------------- def x(): return 2 x = 1 + x() print(x) --------------- 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.

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 -------------- a = 2 if a > 0: a += 1 else: a -= 1 print(a) -------------- else: shold not be indented

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

D. you can make an alias for the name using die as keyword


Related study sets

Prep U's - Chapter 43 - Loss, Grief, and Dying (TF)

View Set

Hesi Quiz: Professional Behaviors/Professionalism

View Set

NR 324 ATI Fundamentals Proctored Exam Study Guide

View Set

English 11 rhetorical/literary devices

View Set

Chapter 22 - Exercise Modalities

View Set

Chapter 6: Challenges to Effective Drug Therapy

View Set

Chapter 54: Management of Patients With Renal Disorders NCLEX

View Set