PCAP sample questions with answers

10 free PCAP sample questions across the exam's domains, each with its answer and an explanation. No account needed.

PCAP sample questions

PCAP – Certified Associate in Python Programming (PCAP-31-03), Python Institute (OpenEDG).

  1. Question 1

    Domain: Modules and Packages

    After the statement import math as m runs, which name refers to the module inside the importing file?

    1. Both m and math, because an alias is an extra name for the same module
    2. m only, because the alias replaces the original module name in this namespace
    3. math only, because aliases are used for documentation and do not bind a name
    4. math.m, because the alias becomes an attribute of the module
    Show the answer

    Answer: B. m only, because the alias replaces the original module name in this namespace

    `import x as y` binds exactly one name, y, in the importing namespace, so only m is defined; referring to math afterwards raises NameError. The form that binds both names does not exist: you would need a second plain `import math` statement for that.

    Checked against: https://docs.python.org/3/reference/simple_stmts.html#import

  2. Question 2

    Domain: Exceptions

    When does the finally branch of a try statement run?

    1. Only when an exception was raised and matched by an except branch
    2. Only when the try branch completed without raising anything
    3. Always, whether the try branch succeeded, raised a handled exception, or raised an unhandled one
    4. Only when the try branch ends with a return statement
    Show the answer

    Answer: C. Always, whether the try branch succeeded, raised a handled exception, or raised an unhandled one

    finally is the clean-up branch: the interpreter runs it on every way out of the try statement, including a return, a break, or an exception that is still propagating. The branch that runs only when nothing was raised is else, which is what "only when the try branch completed without raising anything" describes.

    Checked against: https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions

  3. Question 3

    Domain: Exceptions

    A settings module defines and raises its own exception:

    class ConfigError(Exception):
        def __init__(self, key, message='missing key'):
            super().__init__(message)
            self.key = key
    
    try:
        raise ConfigError('timeout')
    except ConfigError as err:
        print(err.key, err.args[0])

    What is printed?

    1. ConfigError missing key
    2. Nothing, because a user-defined exception may not define its own __init__
    3. timeout ()
    4. timeout missing key
    Show the answer

    Answer: D. timeout missing key

    The custom constructor stores the key on the instance and passes the message up to the base constructor, which is what fills args, so both values are available in the handler. If the call to super().__init__ were left out, args would stay empty and err.args[0] would raise IndexError.

    Checked against: https://docs.python.org/3/tutorial/errors.html#user-defined-exceptions

  4. Question 4

    Domain: Strings

    An input validator uses character-class methods:

    print('abc123'.isalnum(), 'abc 123'.isalnum(), '123'.isdigit(), ''.isdigit())

    What does this code print?

    1. False False True False
    2. True False True False
    3. True True True False
    4. True False True True
    Show the answer

    Answer: B. True False True False

    isalnum() is True only if every character is a letter or digit, so the space makes 'abc 123' fail. isdigit() is True for '123', but isdigit(), like isalnum(), isalpha() and isspace(), returns False for an empty string because it requires at least one character. Expecting True for '' is the trap: 'all characters are digits' is not treated as vacuously true.

    Checked against: https://docs.python.org/3/library/stdtypes.html#str.isalnum

  5. Question 5

    Domain: Strings

    split() and join() are chained:

    print('a1b2c3'.split('b'), 'x'.join('ab'.split('a')))

    What does this code print?

    1. ['a1', '2c3'] xb
    2. ['a1', '2c3'] b
    3. ['a1', 'b2c3'] xb
    4. ['a1', '2c3'] bx
    Show the answer

    Answer: A. ['a1', '2c3'] xb

    split('b') cuts at the separator and drops it, giving ['a1', '2c3']. 'ab'.split('a') returns ['', 'b'] because the separator at position 0 leaves an empty string before it; joining those two items with 'x' gives 'x' + 'b'. The answer 'b' forgets the leading empty string that split() keeps when the text starts with the separator.

    Checked against: https://docs.python.org/3/library/stdtypes.html#str.split

  6. Question 6

    Domain: Object-Oriented Programming

    Type checks are made on a subclass object:

    class A:
        pass
    
    class B(A):
        pass
    
    b = B()
    print(isinstance(b, A), isinstance(A(), B), type(b) == A)

    What does this code print?

    1. True True False
    2. False False False
    3. True False True
    4. True False False
    Show the answer

    Answer: D. True False False

    isinstance() accepts subclass instances, so a B object is an A. The reverse fails because an A object is not a B. type(b) returns exactly B and ignores inheritance, so comparing it with A gives False; that difference is why isinstance() is preferred for type checks.

    Checked against: https://docs.python.org/3/builtins/functions.html#isinstance

  7. Question 7

    Domain: Object-Oriented Programming

    A three-level hierarchy is inspected:

    class A:
        pass
    
    class B(A):
        pass
    
    class C(B):
        pass
    
    print([k.__name__ for k in C.__bases__], issubclass(C, A))

    What does this code print?

    1. ['B', 'A'] True
    2. ['B', 'A', 'object'] True
    3. ['B'] True
    4. ['B'] False
    Show the answer

    Answer: C. ['B'] True

    __bases__ lists only the direct superclasses written in the class statement, so C.__bases__ contains B alone. issubclass() follows the whole chain, however, so C is still a subclass of A. Listing A or object in __bases__ confuses it with the full method resolution order.

    Checked against: https://docs.python.org/3/reference/datamodel.html#type.__bases__

  8. Question 8

    Domain: Object-Oriented Programming

    A class uses a different name for its first parameter:

    class A:
        def __init__(me, v):
            me.v = v
    
        def get(me):
            return me.v * 2
    
    print(A(4).get())

    What does this code print?

    1. 8
    2. NameError is raised because self is not defined
    3. TypeError is raised because the first parameter must be named self
    4. 4
    Show the answer

    Answer: A. 8

    The first parameter of a method receives the instance whatever it is called; self is a strong convention, not a keyword. me.v stores 4 and get() returns 8. Nothing in the language checks the parameter name, so no TypeError or NameError occurs.

    Checked against: https://docs.python.org/3/tutorial/classes.html#random-remarks

  9. Question 9

    Domain: Miscellaneous (List Comprehensions, Lambdas, Closures, I/O)

    A comprehension filters and transforms a range:

    print([x * x for x in range(5) if x % 2])

    What does this code print?

    1. [0, 1, 4, 9, 16]
    2. [1, 9]
    3. [0, 4, 16]
    4. [1, 9, 25]
    Show the answer

    Answer: B. [1, 9]

    x % 2 is truthy (1) for odd numbers, so only 1 and 3 pass the filter and are squared. range(5) stops at 4, so 5 never appears and 25 is not produced. '[0, 4, 16]' reads the condition as 'x is even', but a zero remainder is falsy.

    Checked against: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

  10. Question 10

    Domain: Miscellaneous (List Comprehensions, Lambdas, Closures, I/O)

    map() is given two iterables of different lengths:

    print(list(map(lambda a, b: a * b, [1, 2, 3], [4, 5])))

    What does this code print?

    1. ValueError is raised, because the iterables differ in length
    2. [4, 10, 3]
    3. [4, 10, 0]
    4. [4, 10]
    Show the answer

    Answer: D. [4, 10]

    With several iterables, map() calls the function with one item from each and stops as soon as the shortest iterable is exhausted, so only two products are produced. It neither pads the shorter list nor raises an error by default.

    Checked against: https://docs.python.org/3/builtins/functions.html#map

More practice

A 20-question practice sampler is free with an account; Pro adds the full question bank and timed mock exams.

PCAP course and practice exam: Certified Associate in Python Programming: the exam guide, with the format, cost, pass mark and domains from the vendor.