2 packs: 15% off with code BUY2. 3 or more: 20% off with code BUY3.

Free Python Institute PCAP-31-03 Practice Questions

32 free Python Institute PCAP-31-03 practice questions from the CertStash pack of 129, each with the correct answer and a full explanation. The rule is the same for every exam: ten free on the product page, 32 free here, all 129 in the pack, and each step includes the one before it.

Question 1

What is true about Python packages? (Choose two.)

  1. a code designed to initialize a package’s state should be placed inside a file named init.py
  2. a package’s contents can be stored and distributed as an mp3 file
  3. __pycache__ is a folder that stores semi-compiled Python modules
  4. the sys.path variable is a list of strings
Show answer and explanation

Correct answer: C, D. __pycache__ is a folder that stores semi-compiled Python modules; the sys.path variable is a list of strings

Option C is correct: __pycache__ is a directory created by Python to store bytecode (.pyc files) for faster module loading. Option D is correct: sys.path is a list of strings representing directories where Python searches for modules. Option A is incorrect because the initialization file is __init__.py (with double underscores), not init.py. Option B is incorrect because packages are distributed as archives (zip, tar, etc.) or via package managers, not as mp3 files.

Why the other options are wrong

  • A. The correct filename is __init__.py with double underscores on both sides, not init.py.
  • B. Packages are distributed as archives or via package managers like pip, never as mp3 audio files.

Question 2

A Python package named pypack includes a module named pymod.py which contains a function named pyfun(). Which of the following snippets will let you invoke the function? (Choose two.)

  1. from pypack.pymod import pyfun pyfun()
  2. import pypack pymod.pyfun()
  3. from pypack import * pyfun()
  4. import pypack import pypack.pymod pypack.pymod.pyfun()
Show answer and explanation

Correct answer: A, D. from pypack.pymod import pyfun pyfun(); import pypack import pypack.pymod pypack.pymod.pyfun()

Option A is correct: 'from pypack.pymod import pyfun' directly imports the function, allowing it to be called as pyfun(). Option D is correct: importing pypack and then pypack.pymod allows calling the function via the full path pypack.pymod.pyfun(). Option B is incorrect because importing pypack doesn't automatically import its submodules; pymod would be undefined. Option C is incorrect because 'from pypack import *' only works if __init__.py explicitly defines __all__ or imports pyfun; otherwise pyfun remains inaccessible.

Why the other options are wrong

  • B. Importing pypack does not automatically import submodules; pymod is not defined in the namespace.
  • C. The 'from pypack import *' statement only imports names defined in pypack's __init__.py or its __all__ list, and pyfun is in a submodule.

Question 3

Assuming that the code below has been executed successfully, which of the following expressions will always evaluate to True? (Choose two.) import random v1 = random.random() v2 = random.random()

  1. len(random.sample([1,2,3],1)) > 2
  2. v1 == v2
  3. random.choice([1,2,3]) > 0
  4. v1>1
Show answer and explanation

Correct answer: C. random.choice([1,2,3]) > 0

Option C is correct: random.choice([1,2,3]) always returns one of the three positive integers 1, 2, or 3, all of which are greater than 0, so this always evaluates to True. Option A is incorrect because random.sample([1,2,3],1) returns a list with exactly one element, and len() of that is 1, which is not greater than 2. Option B is incorrect because random.random() generates floats between 0.0 and 1.0, and the probability that two consecutive calls return identical values is virtually zero. Option D is incorrect because random.random() always returns a value in the range [0.0, 1.0), never greater than 1.

Why the other options are wrong

  • A. random.sample([1,2,3],1) returns a list of length 1, and 1 is not greater than 2.
  • B. Two consecutive calls to random.random() produce different floating-point values with extremely high probability.
  • D. random.random() always returns a value in the range [0.0, 1.0), which is never greater than 1.

Question 4

With regards to the directory structure below, select the proper forms of the directives in order to import module_c. (Choose two.)

  1. from pypack.upper.lower import module_c
  2. import pypack.upper.lower.module_c
  3. import upper.module_c
  4. import upper.lower.module_c
Show answer and explanation

Correct answer: A, B. from pypack.upper.lower import module_c; import pypack.upper.lower.module_c

Both options A and B are correct ways to import module_c from the nested directory structure. Option A uses the 'from...import' syntax, specifying the full package path pypack.upper.lower and importing the module_c file directly. Option B uses the 'import' syntax with the complete dotted path to module_c, which Python resolves to the file module_c.py within the lower directory. Both forms are valid and will successfully locate and import the module_c.py file.

Why the other options are wrong

  • C. This omits the top-level package name 'pypack', so Python cannot resolve the relative path starting from 'upper' without additional context.
  • D. This also omits the top-level package name 'pypack' and uses 'import' syntax without 'from', which requires the full absolute path from the root package to work correctly.

Question 5

Which one of the platform module functions should be used to determine the underlying platform name?

  1. platform.processor()
  2. platform.uname()
  3. platform.python_version()
  4. platform.platform()
Show answer and explanation

Correct answer: D. platform.platform()

Option D is correct: platform.platform() returns a string describing the underlying platform name, including the operating system and version information. Option A is incorrect because platform.processor() returns the processor name. Option B is incorrect because platform.uname() returns detailed system information as a named tuple but is more comprehensive than just the platform name. Option C is incorrect because platform.python_version() returns the Python version, not the platform name.

Why the other options are wrong

  • A. platform.processor() returns processor information, not the platform name.
  • B. platform.uname() returns comprehensive system information including platform details, but is not the dedicated function for just the platform name.
  • C. platform.python_version() returns the Python interpreter version, not the underlying platform name.

Question 6

What is the expected behavior of the following code?

  1. the code is erroneous and it will not execute
  2. it outputs 1
  3. it outputs 2
  4. it outputs 0
Show answer and explanation

Correct answer: C. it outputs 2

The code attempts to convert the string '2A' to an integer using int(s). Since '2A' is not a valid decimal integer, this raises a ValueError (not an ArithmeticError). The except clauses are evaluated in order, so the ValueError is caught by the first except block, setting n = 2. This value is then printed. The subsequent except clauses are not evaluated because the exception has already been handled.

Why the other options are wrong

  • A. The code is syntactically valid and will execute successfully without errors.
  • B. The ArithmeticError handler sets n = 1, but a ValueError is raised first, which is caught by the ValueError handler before reaching the ArithmeticError handler.
  • D. The bare except clause sets n = 0, but since the ValueError is caught by the specific ValueError handler, execution never reaches the bare except block.

Question 7

What is the expected behavior of the following code?

  1. it outputs 3
  2. it outputs 1
  3. it outputs 2
  4. the code is erroneous and it will not execute
Show answer and explanation

Correct answer: A. it outputs 3

The code executes foo(0), which attempts to return 1/0, causing a ZeroDivisionError (a subclass of ArithmeticError). This is caught by the outer except ArithmeticError block, which increments m by 2 (m becomes 2). However, the inner except clause in foo() also executes before the exception propagates: when the ArithmeticError occurs, m is incremented by 1 inside foo's except block (m becomes 1), then the raise statement re-raises the exception. The outer except ArithmeticError catches it and increments m by 2 again (m becomes 3). Finally, print(m) outputs 3.

Why the other options are wrong

  • B. The inner exception handler in foo increments m by 1, but this is not the final value because the outer handler also executes.
  • C. While m is incremented to 2 by the outer ArithmeticError handler alone, the inner handler's increment of 1 occurs first, making the total 3.
  • D. The code is syntactically valid Python; the exception handling structure is correct and the code executes without errors.

Question 8

What is true about the following snippet? (Choose two.)

  1. the string what a pity will be seen
  2. the string it's nice to see you will be seen
  3. the code will raise an unhandled exception
  4. the string I feel fine will be seen
Show answer and explanation

Correct answer: B, D. the string it's nice to see you will be seen; the string I feel fine will be seen

The code executes print("I feel fine") successfully, then raises exception E with message "what a pity". The except block catches this exception and executes print(e), which calls the __str__ method of the exception object, returning "it's nice to see you" regardless of the message passed during initialization. The else block only executes if no exception occurred, so it is skipped. Therefore, the output includes "I feel fine" and "it's nice to see you".

Why the other options are wrong

  • A. The string "what a pity" is never printed; it's only passed as the exception message, but the __str__ method returns a different string.
  • C. The exception is properly handled by the except block, so it does not propagate as an unhandled exception.

Question 9

What is the expected behavior of the following code?

  1. it outputs error
  2. it outputs
  3. the code is erroneous and it will not execute
  4. it outputs list assignment index out of range
Show answer and explanation

Correct answer: D. it outputs list assignment index out of range

The code attempts to access index 3 of a list that only has 3 elements (indices 0, 1, 2). When my_list[3] is accessed, Python raises an IndexError with the message 'list assignment index out of range', which is caught by the except BaseException clause and printed. The code will execute successfully and output this error message.

Why the other options are wrong

  • A. While an error is printed, the specific output is the IndexError message, not a generic 'error'
  • B. The code does not output nothing; it prints the IndexError exception message
  • C. The code is syntactically valid and will execute; the exception is properly handled by the try-except block

Question 10

Which of the following expressions evaluate to True? (Choose two.)

  1. ord("0") - ord("9") == 10
  2. len("''") == 2
  3. chr(ord('z') - 1) == 'y'
  4. len(''1234'') == 4
Show answer and explanation

Correct answer: C, D. chr(ord('z') - 1) == 'y'; len(''1234'') == 4

Option C uses ord('z'), which is 122; subtracting 1 gives 121, and chr(121) is 'y', so the comparison is True. Option D measures the literal four-character string 1234, and len returns 4, so that comparison is True as well.

Why the other options are wrong

  • A. ord("0") is 48 and ord("9") is 57, so the difference is -9, not 10.
  • B. This literal does not contain four characters worth of content the way the comparison assumes, so the length test does not yield 2.

What people say about the full PCAP-31-03 pack 5.0 from 4

Dumps for Python Institute PCAP-31-03 were very accurate. Passed my exam with 96% marks. I suggest everyone study from Cert Stash dumps.
KenPCAP-31-03
Got through my exam using this
Ingrid NairPCAP-31-03
Your PCAP-31-03 exam guide is valid in India. Thanks for your helpful questions.
Cesar ArgenbrightPCAP-31-03

Question 11

Which of the following lines of code will work flawlessly when put independently inside the add_new() method in order to make the snippet’s output equal to [0, 1, 1]? (Choose two.)

  1. self.put(self.store[1])
  2. self.put(self.get()[-1])
  3. self.put(store[1])
  4. put(self.store[1])
Show answer and explanation

Correct answer: A, B. self.put(self.store[1]); self.put(self.get()[-1])

The dup() method needs to duplicate the last element of self.store. Option A uses self.put(self.store[1]) which accesses index 1 (the second element, which is 1 after put(1) executes), and puts it again, resulting in [0, 1, 1]. Option B uses self.put(self.get()[-1]) which retrieves the entire store via get(), accesses the last element with [-1] (which is 1), and puts it, also resulting in [0, 1, 1]. Both correctly reference self to access instance variables and methods.

Why the other options are wrong

  • C. Missing the 'self.' prefix before 'store', so it references an undefined global variable instead of the instance attribute.
  • D. Missing the 'self.' prefix before 'put', so it calls an undefined global function instead of the instance method.

Question 12

What is the expected behavior of the following code?

  1. it outputs 6
  2. it raises an exception
  3. it outputs 1
  4. it outputs 3
Show answer and explanation

Correct answer: D. it outputs 3

The code demonstrates the difference between class variables and instance attributes. When `o1.foo()` is called, `Class._Class__Var` is incremented from 0 to 1, and `o1.__prop` is set to 1. When `o2.foo()` is called, `Class._Class__Var` is incremented from 1 to 2, and `o2.__prop` is set to 2. The final print statement accesses `o2._Class__Var` (which is 2) plus `o1.__prop` (which is 1), resulting in 2 + 1 = 3.

Why the other options are wrong

  • A. The class variable reaches 2, not 6; the calculation 2 + 1 equals 3, not 6.
  • B. No exception is raised; the name mangling syntax is valid Python and the attribute access is correct.
  • C. The sum is 2 + 1 = 3, not 1; o2._Class__Var is 2 after two increments, not 1.

Question 13

Assuming that the following inheritance set is in force, which of the following classes are declared properly? (Choose two.)

  1. class Class_2(A,B): pass
  2. class Class_3(A,C): pass
  3. class Class_1(D): pass
  4. class Class_4(C,B): pass
Show answer and explanation

Correct answer: C, D. class Class_1(D): pass; class Class_4(C,B): pass

In Python, multiple inheritance is allowed and follows the Method Resolution Order (MRO). Class D inherits from both B and C, which both inherit from A, creating a valid diamond inheritance pattern. Option C (class Class_1(D): pass) is valid because D is properly defined. Option D (class Class_4(C,B): pass) is valid because both C and B are defined and inherit from A in a consistent order that respects Python's MRO. Option A creates a conflict because it tries to inherit from A and B in an order that violates MRO consistency (B already inherits from A, so listing A first is problematic). Option B is invalid because C inherits from A, and listing both A and C in that order creates an MRO violation since the parent class A appears after its derived class C in the inheritance list.

Why the other options are wrong

  • A. Inheriting from (A,B) violates MRO because B already inherits from A, making the inheritance order inconsistent.
  • B. Inheriting from (A,C) is invalid because C already inherits from A, creating an MRO conflict when A appears before C in the parent list.

Question 14

Assuming that the following code has been executed successfully, select the expressions which evaluate to True (Choose two.)

  1. a is not None
  2. a() == 4
  3. a != b
  4. b() == 4
Show answer and explanation

Correct answer: A, C. a is not None; a != b

The function f(x,y) returns the inner function g, which is a closure that captures nom and denom from f's scope. When a = f(1,2) is executed, a becomes a function object that closes over nom=1 and denom=2. When b = f(3,4) is executed, b becomes a different function object that closes over nom=3 and denom=4. Option A is true because a is assigned a function object (not None). Option C is true because a and b are different function objects with different closures, so a != b evaluates to True. Option B is false because a() evaluates to 1/2 = 0.5, not 4. Option D is false because b() evaluates to 3/4 = 0.75, not 4.

Why the other options are wrong

  • B. a() returns nom/denom = 1/2 = 0.5, which does not equal 4.
  • D. b() returns nom/denom = 3/4 = 0.75, which does not equal 4.

Question 15

Which of the following expressions evaluate to True? (Choose two.)

  1. len(""" """) > 0
  2. len('\'') == 1
  3. ord("z") - ord("Z") == ord("0")
  4. chr(ord('a') + 1) == 'B'
Show answer and explanation

Correct answer: A, B. len(""" """) > 0; len('\'') == 1

In A the triple-quoted literal holds a single space character, so its length is 1, which is greater than 0, giving True. In B the escape sequence \' represents one apostrophe character, so len returns 1 and the comparison is True.

Why the other options are wrong

  • C. ord("z") is 122 and ord("Z") is 90, giving 32, whereas ord("0") is 48.
  • D. ord('a') + 1 is 98 and chr(98) is 'b', which is not equal to the uppercase 'B'.

Question 16

Assuming that the code below has been placed inside a file named code.py and executed successfully, which of the following expressions evaluate to True? (Choose two.)

  1. len(ClassB.__bases__) == 2
  2. __name__ == 'code.py'
  3. str(Object) == 'Object'
  4. ClassA.__module__ == '__main__'
Show answer and explanation

Correct answer: C, D. str(Object) == 'Object'; ClassA.__module__ == '__main__'

Option C is correct because str(Object) calls the __str__ method of the ClassA instance, which returns 'Object' as defined in the ClassA.__str__ method. Option D is correct because when code.py is executed directly (not imported), the __module__ attribute of any class defined in that file is set to '__main__'. Option A is incorrect because ClassB.__bases__ only contains ClassA (length 1), not 2 base classes. Option B is incorrect because __name__ would be '__main__' when the script is executed directly, not 'code.py'.

Why the other options are wrong

  • A. ClassB only inherits from ClassA, so __bases__ contains one element, not two.
  • B. When code.py is executed as the main script, __name__ equals '__main__', not 'code.py'.

Question 17

Which of the following statements are true? (Choose two.)

  1. an escape sequence can be recognized by the / sign put in front of it
  2. ASCII is a subset of UNICODE
  3. II in ASCII stands for Internal Information
  4. a code point is a number assigned to a given character
Show answer and explanation

Correct answer: B, D. ASCII is a subset of UNICODE; a code point is a number assigned to a given character

Option B is true: ASCII is a subset of Unicode; all ASCII characters are valid Unicode characters. Option D is true: a code point is a numeric value assigned to each character in Unicode. Option A is false: escape sequences use the backslash (\) character, not the forward slash (/). Option C is false: in ASCII, 'II' does not stand for 'Internal Information'; ASCII stands for American Standard Code for Information Interchange.

Why the other options are wrong

  • A. Escape sequences are recognized by the backslash (\) character, not the forward slash (/).
  • C. ASCII stands for American Standard Code for Information Interchange, not 'Internal Information'.

Question 18

Which of the following expressions evaluate to True? (Choose two.)

  1. 'xYz'.lower() > 'XY'
  2. '8'+'8' ! = 2 * '8'
  3. float ('3.14') == str('3.' + '14')
  4. 121 + 1 == int('1' + 2 * '2')
Show answer and explanation

Correct answer: A, D. 'xYz'.lower() > 'XY'; 121 + 1 == int('1' + 2 * '2')

In A, 'xYz'.lower() produces 'xyz'; comparing it with 'XY' compares code points character by character, and lowercase 'x' (120) is greater than uppercase 'X' (88), so the expression is True. In D, 121 + 1 equals 122, while '1' + 2 * '2' builds the string '122', and int('122') is 122, so both sides match.

Why the other options are wrong

  • B. '8'+'8' is '88' and 2 * '8' is also '88', so the inequality is False.
  • C. float('3.14') is a float while str('3.' + '14') is the string '3.14'; a float never equals a string, so it is False.

Question 19

Assuming that the code below has been executed successfully, which of the following expressions evaluate to True? (Choose two.)

  1. len(Object.__dict__) == 2
  2. 'var' in Object.__dict__
  3. 'var' in Class.__dict__
  4. 'data' in Object.__dict__
Show answer and explanation

Correct answer: A, B. len(Object.__dict__) == 2; 'var' in Object.__dict__

When `Object = Class(2)` is executed, the `__init__` method sets `self.prop = self.var = 2`, creating instance attributes on the Object instance. The `__dict__` of an instance contains only instance attributes (prop and var), giving it a length of 2. Class-level attributes like `data = 1` reside in `Class.__dict__`, not in individual instances. Therefore, `len(Object.__dict__) == 2` is True (containing 'prop' and 'var'), and `'var' in Object.__dict__` is True since var is an instance attribute. However, `'var'` does not exist in `Class.__dict__` (only 'data' and '__init__' do), and `'data'` is a class attribute, not an instance attribute.

Why the other options are wrong

  • C. 'var' is an instance attribute set in __init__, not a class attribute, so it does not appear in Class.__dict__
  • D. 'data' is a class-level attribute defined in the class body, not an instance attribute, so it does not appear in Object.__dict__

Question 20

Which of the following expressions evaluate to True? (Choose two.)

  1. 'dcb' not in 'abcde'[::-1]
  2. 'True' not in 'False'
  3. str(1-1) in '0123456789'[:2]
  4. 'phd' in 'alpha'
Show answer and explanation

Correct answer: B, C. 'True' not in 'False'; str(1-1) in '0123456789'[:2]

Option B: 'True' not in 'False' evaluates to True because the string 'True' does not appear within 'False'. Option C: str(1-1) produces '0', and '0' is in '0123456789'[:2] which is '01', so the expression evaluates to True. Option A is False because 'abcde'[::-1] reverses to 'edcba', which contains 'dcb'. Option D is False because 'phd' does not appear in 'alpha'.

Why the other options are wrong

  • A. 'abcde'[::-1] produces 'edcba', and 'dcb' IS in 'edcba', making 'not in' evaluate to False.
  • D. The substring 'phd' does not exist anywhere in the string 'alpha'.

Question 21

Which of the following lines of code will work flawlessly when put independently inside the add_new() method in order to make the snippet's output equal to [0, 1, 2]? (Choose two.)

  1. self.queue.append(self.queue[-1] + 1)
  2. self.queue.append(self.get_last() + 1)
  3. self.queue.append(get_last() + 1)
  4. queue.append(self.get_last() + 1)
Show answer and explanation

Correct answer: A, B. self.queue.append(self.queue[-1] + 1); self.queue.append(self.get_last() + 1)

The add_new() method needs to append a new element to self.queue that is one greater than the last element. Starting with MyClass(2), self.queue is [0, 1]. After calling add_new(), it should become [0, 1, 2]. Option A uses self.queue[-1] + 1, which correctly accesses the last element of the queue list and appends the incremented value. Option B uses self.get_last() + 1, which calls the instance method get_last() that returns self.queue[-1], achieving the same result. Both correctly reference the instance and its attributes/methods using self, and both will produce the desired output [0, 1, 2].

Why the other options are wrong

  • C. Missing the self prefix when calling get_last() causes a NameError because get_last is not defined in the local scope.
  • D. Missing the self prefix when accessing queue causes a NameError because queue is not a standalone variable; it exists only as an instance attribute self.queue.

Question 22

What is true about lambda functions? (Choose two.)

  1. they are called anonymous functions
  2. they cannot return the None value as a result
  3. they must contain the return keyword
  4. they must have a non-zero number of parameters
Show answer and explanation

Correct answer: A, C. they are called anonymous functions; they must contain the return keyword

Lambda functions in Python are indeed called anonymous functions because they are defined without a name using the lambda keyword. They can implicitly return None if no return value is specified, making option B false. While lambda functions don't require an explicit return keyword (the expression is automatically returned), they can optionally contain one. Lambda functions can have zero or more parameters, making option D false.

Why the other options are wrong

  • B. Lambda functions can return None as a result, either explicitly or implicitly when the expression evaluates to None.
  • D. Lambda functions can have zero parameters, such as lambda: 42.

Question 23

What is the expected behavior of the following code?

  1. it outputs 3
  2. the code is erroneous and it will not execute
  3. it outputs 2
  4. it outputs 1
Show answer and explanation

Correct answer: D. it outputs 1

Calling foo(0) first hits the assertion: the global m still holds 0, so `assert m != 0` fails and an AssertionError is raised before the division is ever attempted. AssertionError derives from Exception, not from ArithmeticError, so the first except clause does not match it; control falls through to the bare `except:` clause, which catches everything, and m is incremented by 1. The subsequent print therefore shows 1.

Why the other options are wrong

  • A. Only one handler runs for the single raised exception, so m can be increased by at most 1, never to 3.
  • B. The construct is entirely legal Python, assert, try/except with a specific and a bare handler, and a raise are all valid, so it runs to completion.
  • C. The 2 branch belongs to the ArithmeticError handler, but the exception raised is an AssertionError from the failed assert, which that handler does not intercept; the ZeroDivisionError/ValueError path is never reached.

Question 24

What is true about Object-Oriented Programming in Python? (Choose two.)

  1. encapsulation allows you to hide a whole class inside a package
  2. a class is a recipe for an object
  3. each object of the same class can have a different set of properties
  4. the arrows on a class diagram are always directed from a superclass towards its subclass
Show answer and explanation

Correct answer: B, C. a class is a recipe for an object; each object of the same class can have a different set of properties

Option B is true: a class is indeed a blueprint or recipe for creating objects. Option C is true: objects of the same class can have different property values; each instance has its own state. Option A is false: encapsulation hides details within a class, not a whole class inside a package. Option D is false: in class diagrams, arrows are directed from a subclass toward its superclass, not the other way around.

Why the other options are wrong

  • A. Encapsulation hides implementation details within a class, not entire classes within packages.
  • D. Class diagram arrows point from subclasses upward to superclasses, not from superclass to subclass.

Question 25

What is the expected behavior of the following code? the_string = ',,'.join(('alpha', 'omega')) the_list = the_string.split(',') print(',' in the list)

  1. it outputs False
  2. it raises an exception
  3. it outputs True
  4. it outputs nothing
Show answer and explanation

Correct answer: A. it outputs False

Joining with the two-character separator produces 'alpha,,omega'. Splitting that on a single comma yields ['alpha', '', 'omega'], where the empty string comes from the two adjacent separators. The membership test looks for an element exactly equal to ',', and no element equals a comma, so False is printed.

Why the other options are wrong

  • B. All the operations are legal, so no error is raised.
  • C. The comma characters were consumed as delimiters, so no list element is ','.
  • D. The print call always produces output; here it prints False.

25 questions in. Want the rest? The first half of the pack, free by email · The full pack

Question 26

Assuming that the following inheritance set is in force, which of the following classes are declared properly? (Choose two.)

  1. class Class_3(A,C): pass
  2. class Class_2(B,C): pass
  3. class Class_4(A,B): pass
  4. class Class_1(C,B): pass
Show answer and explanation

Correct answer: B, C. class Class_2(B,C): pass; class Class_4(A,B): pass

In Python, multiple inheritance is allowed and classes can inherit from multiple parent classes in any order. Given the inheritance hierarchy where B inherits from A and C inherits from A, both class Class_2(B,C) and class Class_4(A,B) are properly declared because they follow valid syntax and the Method Resolution Order (MRO) is resolvable. Class_2(B,C) creates a diamond inheritance pattern with A as the common base, which Python handles through C3 linearization. Class_4(A,B) is valid since B is a subclass of A, creating a clear linear hierarchy. Both options use proper Python syntax with valid parent classes.

Why the other options are wrong

  • A. class Class_3(A,C) is valid syntax, but both A and C are unrelated in the hierarchy shown (C inherits from A, not the reverse), making this a less ideal pattern than the correct answers.

Question 27

What is the expected behavior of the following code?

  1. it outputs 3
  2. it outputs 'None'
  3. it outputs 0
  4. it raises an exception
Show answer and explanation

Correct answer: A. it outputs 3

The code converts 1/3 to a string using str(1/3), which in Python 3 produces '0.3333333333333333' (a float division result converted to string). The loop iterates through each character in this string, concatenating them into the dummy variable. After the loop completes, dummy contains the entire string. The print statement accesses dummy[-1], which is the last character of the string, which is '3'. Therefore, the output is 3.

Why the other options are wrong

  • B. The str() function returns a string representation, not None, and the loop builds a concatenated string, not None.
  • C. The last character of '0.3333333333333333' is '3', not '0', so indexing with [-1] gives '3' not '0'.
  • D. The code is syntactically valid Python and executes without error; no exception is raised.

Question 28

Which of the following statements are true? (Choose two.)

  1. if open()'s second argument is 'r', the file must exist or open will fail
  2. the second open() argument describes the open mode and defaults to 'w'
  3. if open()'s second argument is 'w' and the invocation succeeds, the previous file's content is lost
  4. closing an opened file is performed by the closefile() function
Show answer and explanation

Correct answer: A, C. if open()'s second argument is 'r', the file must exist or open will fail; if open()'s second argument is 'w' and the invocation succeeds, the previous file's content is lost

Option A is True: when open() uses mode 'r' (read), the file must already exist or FileNotFoundError is raised. Option C is True: when open() uses mode 'w' (write) and succeeds, the file is truncated, destroying any previous content. Option B is False: the default mode is 'r' (read), not 'w'. Option D is False: files are closed using the close() method on the file object, not a closefile() function.

Why the other options are wrong

  • B. The default open() mode is 'r' (read), not 'w' (write).
  • D. Files are closed by calling the close() method on the file object, not via a closefile() function.

Question 29

What is the expected behavior of the following code? my_list = [i for i in range(5)] m = [my_list[i] for i in range(4, 0, -1) if my_list[i] % 2 != 0] print(m)

  1. the code is erroneus and it will not execute
  2. it outputs [4, 2, 0]
  3. it outputs [3, 1]
  4. it outputs [1, 3]
Show answer and explanation

Correct answer: C. it outputs [3, 1]

First, my_list = [0, 1, 2, 3, 4] from range(5). The list comprehension iterates with range(4, 0, -1), which produces [4, 3, 2, 1]. For each index i, it checks if my_list[i] % 2 != 0 (odd numbers). At i=4: my_list[4]=4 (even, skipped); i=3: my_list[3]=3 (odd, included); i=2: my_list[2]=2 (even, skipped); i=1: my_list[1]=1 (odd, included). The result is [3, 1].

Why the other options are wrong

  • A. The code is syntactically correct and executes successfully.
  • B. The filter checks for odd numbers only, and it processes indices in reverse order [4,3,2,1], not forward.
  • D. The indices are processed in descending order [4,3,2,1], so 3 appears before 1 in the result.

Question 30

What is true about Python class constructors? (Choose two.)

  1. the constructor's first parameter must always be named self
  2. there can be only one constructor in a Python class
  3. the constructor cannot be invoked directly under any circumstances
  4. the constructor cannot return a result other than None
Show answer and explanation

Correct answer: A, B. the constructor's first parameter must always be named self; there can be only one constructor in a Python class

Option A is True: the first parameter of __init__() must be 'self' by convention and requirement in Python. Option B is True: a Python class can have only one __init__() constructor method defined at a time (though it can be overridden in subclasses). Option C is False: constructors are invoked directly when instantiating a class (e.g., MyClass()). Option D is False: __init__() implicitly returns None, but __new__() can return instances, and explicit return statements in __init__() don't override None being returned.

Why the other options are wrong

  • C. Constructors are invoked directly every time an object is instantiated using the class name followed by parentheses.
  • D. While __init__() conventionally returns None, constructors are designed to initialize objects and always implicitly return None.

Question 31

What is the expected behavior of the following code?

  1. it outputs 3
  2. it outputs 2
  3. it outputs 5
  4. it raises an exception
Show answer and explanation

Correct answer: C. it outputs 5

The code creates a class with a class variable `Var` initialized to 0 and an instance variable `var`. Each time `__init__` is called, the class variable `Class.Var` is incremented by 1. When `object_1 = Class(1)` is created, `Class.Var` becomes 1; when `object_2 = Class(2)` is created, `Class.Var` becomes 2. The final print statement adds `Class.Var` (which is 2) + `object_1.var` (which is 1) + `object_2.var` (which is 2), resulting in 2 + 1 + 2 = 5.

Why the other options are wrong

  • A. This would be the result if only the class variable and one instance variable were summed, but all three values are included in the print statement.
  • B. This would be the result if only the class variable were counted, ignoring the instance variables completely.
  • D. The code is syntactically valid Python and executes without errors; there are no conditions that would raise an exception.

Question 32

What is the expected behavior of the following code?

  1. the code is erroneous and it will not execute
  2. it outputs 1
  3. it outputs 3
  4. it outputs 2
Show answer and explanation

Correct answer: A. the code is erroneous and it will not execute

The code contains a syntax error in its exception handling structure. In Python, when using multiple except clauses, the correct syntax requires each except statement to be followed by a colon and then the exception type (or exception type with a variable). However, the code shows 'except:' (a bare except clause) followed by 'n = 3', then 'except ValueError:' on a new line. This is invalid syntax because after a bare except clause with its body, you cannot have another except clause at the same indentation level without proper structure. The bare 'except:' catches all exceptions and its block ends before the next except statement, which violates Python's exception handling syntax rules. The code will not execute and will raise a SyntaxError.

Why the other options are wrong

  • B. The code would output 1 only if it executed successfully and caught an ArithmeticError, but the code has a syntax error and will not run.
  • C. The code would output 3 only if the bare except clause caught an exception, but the code has a syntax error preventing execution.
  • D. The code would output 2 only if it executed successfully and caught a ValueError, but the code has a syntax error and will not run.

That was 32 of 129.

The full Python Institute PCAP-31-03 pack has all 129 questions, each with the answer, the explanation and why the other options are wrong, plus a questions-only copy for timed runs. US$39, paid once, with free monthly updates and a pass-or-your-money-back guarantee.

Get the full pack

Not ready yet? Get the first 64 free as one PDF by email. Get the Half Pack →