PCAP: Certified Associate in Python Programming (PCAP-31-03) Exam-style mock test
PCAP Certified Associate in Python Programming Practice Exams|Practice test
Full explanations
Exam format
Pass line 70%
33 USD One-time · lifetime access
Enroll →
Sample questions
Example1 · Modules and Packages
On the data tooling team, a script needs only the sqrt function from the math module and must call it without any module prefix, as sqrt(2). Which import approach achieves exactly this behavior?
・Bind the whole module with import math and then always call it as math dot sqrt everywhere
Incorrect. Plain import binds the module object, so the call would have to be written with the math prefix, not bare sqrt.
✓Copy only that one name into scope with the from math import sqrt form
Correct. The from-import form copies the sqrt name directly into the current namespace, so it is callable as sqrt(2) with no prefix.
・Alias the entire module by writing import math as sqrt before the call
Incorrect. Aliasing the whole module to sqrt means the call would read sqrt dot sqrt, which is not the required bare form.
・Import the function as a submodule using the import math dot sqrt form
Incorrect. The dotted import treats sqrt as a submodule, which is invalid because sqrt is a function, not a module.
Explanation
The from-import form copies a specific name into the current namespace, allowing an unqualified call, while plain import keeps the module prefix.
Example2 · Exceptions
On the data tooling team, a loader reads a config dict and runs settings['retries'] to fetch a value. The 'retries' key was never written to the dict. Which exception is raised?
・ValueError
Incorrect. ValueError signals a value of the right type but wrong content, not a missing dictionary key.
✓KeyError
Correct. Subscripting a dict with an absent key raises KeyError.
・IndexError
Incorrect. IndexError is raised for out-of-range sequence indices, not for dict key lookups.
・The lookup silently returns None instead of raising any exception at all
Incorrect. Only dict.get() returns a default such as None; direct subscripting of a missing key raises an exception.
Explanation
Direct subscript access of a nonexistent dict key raises KeyError; use .get() to obtain a default instead.
Example3 · Strings and String Methods
A data tooling engineer stores the pipeline tag code = 'DATA-2024' and needs to extract just the year portion using slicing. Which expression returns '2024'?
✓code[5:]
Correct. Index 5 is the first digit '2', so slicing from index 5 to the end yields the four characters '2024'.
・code[-4]
Incorrect. This is a single-character index, not a slice, so it returns only the character '2' rather than the year.
・code[4:9]
Incorrect. Index 4 is the hyphen, so this slice returns '-2024' including the dash at the front.
・code[:5]
Incorrect. This takes the first five characters 'DATA-', which is the prefix rather than the year.
Explanation
In 'DATA-2024' the character at index 5 is the first digit of the year, so slicing from index 5 to the end extracts '2024'.
Example4 · Object-Oriented Programming
In a fintech scripting project you define a class Account with a constructor that assigns self.balance = balance. When you run a = Account() without passing any argument, the program raises an error. Which change to the constructor signature lets Account() succeed with a starting balance of 0?
✓def __init__(self, balance=0):
Correct. Giving balance a default of 0 makes the argument optional, so Account() uses 0.
・def __init__(self, balance):
Incorrect. Without a default, Python still requires a balance argument at call time.
・def __init__(balance=0):
Incorrect. The constructor must receive self as its first parameter.
・def __init__(self, *, balance): return the account object with its balance attribute initialized to zero
Incorrect. The keyword-only balance has no default, so it is still mandatory.
Explanation
A default value on a constructor parameter makes it optional while keeping self first.
Example5 · Miscellaneous (Generators, Closures, File Processing)
In a fintech reporting script, you need a function that lazily yields running balances one at a time from a list of daily deltas, so memory stays flat even for years of data. Which function definition produces a generator?
✓def balances(deltas):
total = 0
for d in deltas:
total += d
yield total
Correct. The presence of a yield statement turns the function into a generator that produces running totals lazily one value per iteration.
・def balances(deltas):
total = 0
result = []
for d in deltas:
total += d
result.append(total)
return result
Incorrect. Building and returning a full list keeps every balance in memory, which is exactly the behavior the lazy requirement is trying to avoid.
・def balances(deltas):
return sum(deltas)
Incorrect. This simply returns one aggregate number, not a sequence of running balances yielded individually.
・def balances(deltas):
return [sum(deltas[:i+1]) for i in range(len(deltas))]
Incorrect. The list comprehension eagerly materializes all balances into memory instead of yielding them lazily.
Explanation
A function becomes a generator the moment it contains a yield statement; such a function returns an iterator that computes values on demand.
Example6 · Modules and Packages
In a fintech scripting project, a developer writes 'from decimal import Decimal' at the top of a payment module. Which statement correctly describes what this import makes available?
✓The name Decimal, referenced directly without any prefix at all
Correct. The from...import form binds the specific name Decimal into the current namespace, so it is used directly.
・The name decimal.Decimal, which must still carry the module prefix
Incorrect. A module-name prefix is required only with the plain 'import decimal' form, not with from...import.
・Every public name defined inside decimal, each one usable without a prefix
Incorrect. Only the named object is imported here; importing every public name would require the asterisk form.
・Only a separate copy of the decimal module bound to the local name Decimal
Incorrect. The import binds the Decimal class object, not a copy of the whole module, under that local name.
Explanation
The 'from module import name' syntax binds just the named object into the current namespace, allowing unqualified use.
Example7 · Modules and Packages
A devops engineer writes a deployment helper and needs to call sqrt() from the math module. The team style guide forbids referencing the module name as a prefix in the body of this helper. Which import statement lets the engineer write sqrt(9) directly?
・import math
Incorrect. This binds the name math, so the call must be written as math.sqrt(9), not sqrt(9).
✓from math import sqrt
Correct. from math import sqrt binds sqrt into the current namespace, so sqrt(9) works without a prefix.
・import sqrt from math
Incorrect. The syntax is reversed; Python requires the from clause first and this line raises a SyntaxError.
・from math import sqrt as module and then reference it through the math namespace prefix
Incorrect. Aliasing to module and then using the math prefix contradicts the goal and still requires a qualified name.
Explanation
The from <module> import <name> form injects the specific name into the local namespace so it can be used unqualified.
Example8 · Modules and Packages
A devops team ships a module deploy.py that is both imported by a scheduler and run directly from the shell. The engineer wraps the CLI startup logic in if __name__ == '__main__':. What is the practical effect when the scheduler imports deploy?
✓The CLI startup block is skipped
Correct. On import, __name__ equals 'deploy', so the main-guard is False and the CLI block is skipped.
・The CLI startup block runs twice
Incorrect. The block does not run twice; on import it does not run at all.
・The import fails with an error
Incorrect. Importing the module does not raise an error from the guard.
・The guarded block runs every time regardless of how the module happens to be loaded into the interpreter
Incorrect. The guard exists precisely so the block does not run on every load; it only runs on direct execution.
Explanation
When a module is imported, its __name__ is its module name, so the __main__ guard prevents script-only code from executing.
Example9 · Modules and Packages
During a code audit, a devops engineer wants to list all names (functions and constants) exposed by an imported module named utils at runtime. Which built-in function returns that list of names?
・type(utils)
Incorrect. type() returns the object's type, not the list of its attribute names.
✓dir(utils)
Correct. dir(utils) returns a sorted list of the names defined in the module.
・len(utils)
Incorrect. len() cannot be applied to a module object this way and does not list names.
・help(utils) which prints formatted documentation about every member defined inside the module object
Incorrect. help() prints documentation text rather than returning a list of names.
Explanation
dir() returns a list of the identifiers (attributes) available in the given object or module.
Example10 · Modules and Packages
A researcher in the computing group needs only the sqrt function from the math module, and wants to call it as simply sqrt() inside the analysis script without any prefix. Which import statement achieves this?
✓from math import sqrt
Correct. from math import sqrt binds the name sqrt directly into the namespace, allowing it to be called as sqrt() with no prefix.
・import math.sqrt as sqrt
Incorrect. import math.sqrt as sqrt is invalid because import expects a module, not a function object.
・import sqrt from math as the only name available to the current script
Incorrect. The syntax import X from Y is not valid Python; the keyword order is reversed.
・import math, then afterwards write sqrt = math.sqrt in a separate line
Incorrect. This does work eventually but it is not a single import statement and uses an extra assignment, which the question rules out.
Explanation
The from module import name form binds the specified object directly into the current namespace so it can be used without the module prefix.
Example11 · Modules and Packages
The group's shared module stats.py contains if __name__ == '__main__': run_tests(). Another script imports stats with import stats. What happens to run_tests() at import time?
・It runs once
Incorrect. The guard prevents the call; run_tests() does not execute even a single time on import.
✓It is not called during the import
Correct. When stats is imported, its __name__ equals 'stats', so the guard is False and run_tests() is skipped.
・It runs repeatedly for every function defined inside the imported stats module file
Incorrect. The guarded block is evaluated once at most, never per function, and here it is skipped entirely because of the name check.
・It raises a NameError because __name__ is undefined when a module is imported by another
Incorrect. __name__ is always defined for any module; on import it holds the module's name rather than being missing.
Explanation
A module's __name__ equals '__main__' only when run directly; when imported it equals the module name, so the main guard block is skipped.
Example12 · Modules and Packages
On a web backend team, a developer keeps a shared helper file utils.py beside the service's main.py. The service must call the clean_slug() function defined there, but the team's style guide forbids binding the module name itself into the namespace. Which import statement satisfies this rule?
・import utils.clean_slug
Incorrect. This treats clean_slug as a submodule of a utils package, which fails for a plain module and still binds the name utils.
✓from utils import clean_slug
Correct. from utils import clean_slug imports only the function, binding clean_slug without binding the module name utils.
・import clean_slug from utils
Incorrect. The keyword order is invalid Python; the from clause must precede import.
・from the utils module please import the clean_slug function into the current namespace right now
Incorrect. This is prose, not valid Python syntax, and would raise a SyntaxError.
Explanation
The from <module> import <name> form brings a specific object into the current namespace without binding the module's own name.
Example13 · Modules and Packages
A backend engineer wants the file queue_worker.py to start its polling loop only when run directly as a script, but stay silent when another service imports it. Which condition guards the startup code correctly?
✓if __name__ == '__main__':
Correct. When a file runs directly, Python sets __name__ to '__main__', so this guard isolates script-only code.
・if __file__ == 'queue_worker':
Incorrect. __file__ holds the path, not the module name, and will not equal that string.
・if __main__ == __name__ and __name__ is not None:
Incorrect. This adds a needless comparison and __name__ is never None for a loaded module.
・if the module is being executed as the top level program by the interpreter now:
Incorrect. This is a plain-English sentence, not valid Python, and raises a SyntaxError.
Explanation
Python sets __name__ to '__main__' for the top-level script and to the module name on import, which is the standard run-vs-import guard.
Example14 · Modules and Packages
A QA automation engineer needs only the sleep function from the time module so test pacing code can call sleep(2) directly without a module prefix. Which import statement achieves this?
✓from time import sleep
Correct. The from-import form binds the name sleep in the current namespace, so sleep(2) can be called without the time prefix.
・import sleep from the time module so it is directly usable
Incorrect. This is prose, not valid Python syntax; there is no 'import X from the Y module' statement form.
・import time.sleep
Incorrect. import time.sleep is invalid because import expects a module, not a function inside it.
・from sleep import time
Incorrect. This reverses the operands and would look for a module named sleep, which does not exist.
Explanation
The 'from module import name' form imports a specific entity into the current namespace so it can be used unqualified.
Example15 · Modules and Packages
A QA team's helper module runner.py contains a guarded block that should start the test harness only when the file is executed directly, but stay silent when imported by other suites. Which condition correctly guards that block?
✓if __name__ == '__main__':
Correct. When a file is run directly, its __name__ equals '__main__', so this guard runs the harness only on direct execution.
・if the module is being executed as the top-level script right now:
Incorrect. This is a description, not valid Python; there is no natural-language conditional of this kind.
・if __file__ == '__main__':
Incorrect. __file__ holds the path string of the module, never the value '__main__'.
・if __main__ == __name__ and not imported:
Incorrect. There is no 'imported' variable, and this adds an invalid clause to the comparison.
Explanation
Python sets __name__ to '__main__' for the directly executed file and to the module name when imported, which is the basis of the standard guard idiom.
▶ Try 10 free questions (graded)