PCAP Certified Associate in Python Programming Exam — Questions and Answers
Question 1: What is the output of `s = {3, 1, 2}; print(min(s))`?
- 1 (Correct answer)
- 3
- TypeError
- Sets are unordered, so min() is undefined
Correct answer: 1
`min()` works on any iterable including sets and returns the smallest element, which is 1.
Question 2: What is the output of `' hello '.strip()`?
- 'hello' (Correct answer)
- 'hello '
- ' hello'
- ' hello '
Correct answer: 'hello'
strip() removes all leading and trailing whitespace characters, returning 'hello'.
Question 3: Which flag in open() prevents Windows from translating '\n' to '\r\n' on write?
- newline='' (Correct answer)
- errors='ignore'
- mode='rb'
- newline=None
Correct answer: newline=''
Passing newline='' disables universal newline translation so Python writes exactly the characters you provide without CR+LF conversion.
Question 4: How do you repeat a string 3 times in Python?
- 'ab' + 3
- repeat('ab', 3)
- 'ab' * 3 (Correct answer)
- 'ab'.repeat(3)
Correct answer: 'ab' * 3
The * operator with an integer repeats a string that many times: 'ab' * 3 == 'ababab'.
Question 5: Which statement about Python's `set` type is correct?
- Sets are unordered and contain unique elements (Correct answer)
- Sets preserve insertion order
- Sets are immutable
- Sets allow duplicate elements
Correct answer: Sets are unordered and contain unique elements
Python sets are unordered collections that automatically enforce uniqueness — duplicates are silently ignored.
Question 6: A developer needs to write a logging function that adds new entries to the end of a log file. If the log file does not exist, it should be created. The function also needs to be able to read from the file to check previous logs. Which file mode is the most appropriate for this scenario?
- 'a'
- 'w+'
- 'a+' (Correct answer)
- 'r+'
Correct answer: 'a+'
The 'a+' mode is ideal for this use case. The 'a' stands for append, which means the file pointer is placed at the end of the file for writing, and if the file doesn't exist, it will be created. The '+' signifies that the file is opened for updating (both reading and writing). 'w+' would truncate the file, 'r+' would raise an error if the file doesn't exist, and 'a' would not allow reading.
Question 7: What does `{1, 2, 3}.isdisjoint({4, 5, 6})` return?
- None
- False
- True (Correct answer)
- {}
Correct answer: True
`isdisjoint()` returns True when two sets share no common elements.
Question 8: What is the main goal of abstraction in object-oriented programming?
- To enable an object to be treated as an instance of its parent class.
- To bundle data and methods that work on the data within one unit.
- To hide complex implementation details and expose only the essential features of an object. (Correct answer)
- To allow a class to inherit properties and methods from another class.
Correct answer: To hide complex implementation details and expose only the essential features of an object.
Abstraction focuses on hiding the internal complexity of a system and exposing only the necessary parts. In OOP, this means creating classes that have a simple interface for interacting with them, without the user needing to know the intricate details of how their methods are implemented.
Question 9: What is the purpose of PYTHONSTARTUP?
- It is executed every time you start the compiler
- It is executed every time you start the interpreter (Correct answer)
- None of these
- It is needed while booting of a particular process
Correct answer: It is executed every time you start the interpreter
PYTHONSTARTUP is an environment variable that points to a Python script. When the Python interpreter starts in interactive mode, it automatically executes the commands in the script specified by this variable. This allows users to define custom functions, import modules, or set up a specific environment that is available every time they enter the interactive interpreter.
Question 10: What is the output of `[x**2 for x in range(4)]`?
- [0, 1, 4, 9] (Correct answer)
- [1, 2, 3, 4]
- [0, 1, 2, 3]
- [1, 4, 9, 16]
Correct answer: [0, 1, 4, 9]
range(4) produces 0, 1, 2, 3, and squaring each gives [0, 1, 4, 9].
Question 11: A developer is creating a large application with a directory structure for utilities like `my_app/utils/string_helpers.py`. To make `utils` a package and allow `string_helpers` to be imported from `my_app/main.py` using `from utils import string_helpers`, what crucial, often empty, file must exist inside the `my_app/utils/` directory?
- __main__.py
- setup.py
- __init__.py (Correct answer)
- package.cfg
Correct answer: __init__.py
For the Python interpreter to treat a directory as a package, it must contain a file named `__init__.py`. This file can be empty, or it can contain initialization code for the package. Without it, the directory is just a directory, and you cannot import modules from it in this manner.
Question 12: Which f-string expression correctly formats a float to 2 decimal places?
- f'{value|2f}'
- f'{value:2f}'
- f'{value:.2}'
- f'{value:.2f}' (Correct answer)
Correct answer: f'{value:.2f}'
The format spec :.2f means fixed-point notation with 2 digits after the decimal.
Question 13: A developer needs to handle both `ValueError` and `TypeError` in the same way. Which of the following code snippets demonstrates the correct syntax for catching multiple specific exceptions in a single `except` block?
- except ValueError or TypeError:
- except (ValueError, TypeError): (Correct answer)
- except [ValueError, TypeError]:
- except ValueError, TypeError:
Correct answer: except (ValueError, TypeError):
To catch multiple exceptions in a single `except` clause, the exceptions should be specified as a tuple enclosed in parentheses. The other syntaxes are invalid for this purpose.
Question 14: What does `'hello world'.title()` return?
- 'HELLO WORLD'
- 'Hello World' (Correct answer)
- 'hello world'
- 'Hello world'
Correct answer: 'Hello World'
title() capitalizes the first letter of every word and lowercases the rest.
Question 15: Which built-in function can be used to create an iterator from any iterable?
- next()
- enumerate()
- iter() (Correct answer)
- zip()
Correct answer: iter()
iter() returns an iterator object from any iterable, calling its __iter__ method.
Question 16: Which of the following correctly creates a shallow copy of a list `lst`?
- lst2 = list.clone(lst)
- lst2 = lst.copy() (Correct answer)
- lst2 = lst
- lst2 = deepcopy(lst)
Correct answer: lst2 = lst.copy()
`lst.copy()` creates a new list with the same top-level elements; nested objects are still shared.
Question 17: What does the `__all__` variable in a module control?
- Which functions are automatically called on import
- The order in which module attributes are loaded
- Which names are exported when `from module import *` is used (Correct answer)
- Which names are visible in `dir(module)`
Correct answer: Which names are exported when `from module import *` is used
`__all__` is a list of strings defining the public API exported by `from module import *`.
Question 18: What does `d.items()` return?
- A view of (key, value) tuples (Correct answer)
- A copy of the dictionary
- A list of keys
- A list of values
Correct answer: A view of (key, value) tuples
`dict.items()` returns a dynamic view object of (key, value) pairs that reflects changes to the dictionary.
Question 19: What does `enumerate()` return when iterating over a list?
- Only the indices
- A dictionary of index-value pairs
- Tuples of (index, value) (Correct answer)
- Only the values
Correct answer: Tuples of (index, value)
`enumerate()` yields `(index, element)` tuples, letting you track both position and value in a loop.
Question 20: What is the output of `'Python'.replace('P', 'J')`?
- 'JPython'
- 'Python'
- 'python'
- 'Jython' (Correct answer)
Correct answer: 'Jython'
replace() substitutes all occurrences of the first argument with the second, giving 'Jython'.
Question 21: What does the following code output? <br> def calculate (num1, num2=4): <br> res = num1 * num2 <br> print(res) <br> calculate(5, 6)
- The program executed with errors
- 30 (Correct answer)
- 20
Correct answer: 30
The `calculate` function is defined with a default argument `num2=4`. However, when `calculate(5, 6)` is called, the value `6` is explicitly passed for `num2`, overriding the default. So, `num1` becomes 5 and `num2` becomes 6. The function then calculates `res = 5 * 6`, which is 30, and prints this result.
Question 22: What is the correct order of execution for the blocks in a `try...except...else...finally` statement when no exception occurs within the `try` block?
- `try` -> `finally`
- `try` -> `else`
- `try` -> `except` -> `finally`
- `try` -> `else` -> `finally` (Correct answer)
Correct answer: `try` -> `else` -> `finally`
When a `try` block executes successfully without raising an exception, the `except` block is skipped. The `else` block is then executed because no error occurred. Finally, the `finally` block is always executed, regardless of whether an exception was raised or not.
Question 23: Which clause is executed only when no exception occurs in the `try` block?
- pass
- finally
- else (Correct answer)
- except
Correct answer: else
The `else` clause runs only if the `try` block completes without raising any exception.
Question 24: When creating a custom exception class, what is the best practice for the base class from which it should inherit?
- Inherit from the `Exception` class to avoid catching system-exit events. (Correct answer)
- Inherit from the `BaseException` class to catch all possible signals.
- Do not inherit from any class; a standalone class is sufficient.
- Inherit from the `Error` class for semantic clarity.
Correct answer: Inherit from the `Exception` class to avoid catching system-exit events.
It is best practice to inherit from the built-in `Exception` class when creating custom exceptions. Inheriting from `BaseException` is discouraged because it can catch system-level exceptions like `KeyboardInterrupt` or `SystemExit`, which are not typically intended to be handled by application code.
Question 25: What value does `__name__` hold when a module is imported (not run directly)?
- None
- The module's fully qualified name (Correct answer)
- '__main__'
- The filename without extension
Correct answer: The module's fully qualified name
When a module is imported, `__name__` is set to the module's fully qualified name (e.g., `'mypackage.mymodule'`), not `'__main__'`.
Question 26: A developer needs to save a Python dictionary to a file so it can be perfectly reconstructed into a dictionary object later. Which module and file mode should be used for this task?
- The `json` module with the `'w'` mode.
- The `pickle` module with the `'wb'` mode. (Correct answer)
- The `sys` module with the `'w'` mode.
- The `os` module with the `'wb'` mode.
Correct answer: The `pickle` module with the `'wb'` mode.
The `pickle` module is Python's standard library for serializing and de-serializing Python object structures (a process also called 'pickling'). To save a Python object like a dictionary, you should use `pickle.dump()`. This process requires the file to be opened in binary write mode, which is specified by `'wb'`.
Question 27: How do you check if variable `x` is of type `str` using the recommended approach?
- type(x) == str
- x.type() is str
- isinstance(x, str) (Correct answer)
- x.__class__ == 'str'
Correct answer: isinstance(x, str)
`isinstance(x, str)` is preferred because it also handles subclasses of `str`.
Question 28: What happens when an exception is raised inside a `finally` block?
- Python exits immediately
- It replaces any exception from the try block (Correct answer)
- It is caught by the nearest except clause
- It is silently ignored
Correct answer: It replaces any exception from the try block
An exception raised in a `finally` block replaces any exception that was propagating from the `try` or `except` block.
Question 29: A developer is building a package and wants to control which functions are imported when a user performs a wildcard import (`from my_package import *`). Which special variable should be defined within the package's `__init__.py` file to achieve this?
- __exports__
- __all__ (Correct answer)
- __public__
- __imports__
Correct answer: __all__
The `__all__` variable is a list of strings that defines the public API of a module. When `__all__` is defined in a package's `__init__.py`, a user who runs `from my_package import *` will only import the names listed in `__all__`, giving the package author explicit control over the namespace.
Question 30: What does shutil.copy2(src, dst) preserve that shutil.copy(src, dst) does not?
- File metadata (timestamps) (Correct answer)
- File ownership
- File permissions
- File content
Correct answer: File metadata (timestamps)
shutil.copy2() copies content and permissions like copy(), but also preserves the file's metadata such as modification timestamps.
Question 31: What is the output of: `print(1/0)` if wrapped with `except ZeroDivisionError as e: print(e)`?
- 0
- ZeroDivisionError
- None
- division by zero (Correct answer)
Correct answer: division by zero
The `str()` representation of a `ZeroDivisionError` is 'division by zero', which is what `print(e)` outputs.
Question 32: Which method removes leading and trailing whitespace from a string?
- trim()
- strip() (Correct answer)
- clean()
- lstrip()
Correct answer: strip()
strip() removes whitespace (or specified characters) from both ends of a string.
Question 33: What does file.seek(0) accomplish?
- Reads the first byte
- Closes the file
- Moves the file pointer to the beginning (Correct answer)
- Truncates the file to zero bytes
Correct answer: Moves the file pointer to the beginning
file.seek(0) moves the read/write position back to byte offset 0, which is the start of the file.
Question 34: Which of the following is NOT a built-in Python decorator?
- @staticmethod
- @classmethod
- @property
- @private (Correct answer)
Correct answer: @private
@private is not a built-in Python decorator; Python does not have built-in access modifier decorators, though @staticmethod, @classmethod, and @property are all built-in.
Question 35: What does `'hello'.center(11, '*')` return?
- '*****hello'
- '***hello***' (Correct answer)
- 'hello*****'
- '**hello***'
Correct answer: '***hello***'
center() pads the string to the specified total width by placing fill characters equally on both sides.
Question 36: Which of the following is a Python environment variable that isn't valid?
- PYTHONPATH
- PYTHONSTARTUP
- PYTHONLIBRARY (Correct answer)
- PYTHONCASEOK
Correct answer: PYTHONLIBRARY
Python uses several environment variables to configure its behavior, such as `PYTHONSTARTUP` (for an initialization script), `PYTHONPATH` (for module search paths), and `PYTHONCASEOK` (on Windows, for case-insensitive imports). `PYTHONLIBRARY` is not a standard or recognized environment variable used by the Python interpreter for its configuration or operation.
Question 37: Consider the following code intended to classify a number. What is a potential issue with its logic? ```python num = 0 if num >= 0: print("Positive or Zero") if num == 0: print("Zero") else: print("Negative") ```
- The code will raise a SyntaxError.
- The `else` statement will never be reached.
- It will incorrectly print "Negative" for an input of 0.
- It will print two lines for an input of 0. (Correct answer)
Correct answer: It will print two lines for an input of 0.
This code snippet uses two separate `if` statements, not an `if-elif-else` chain. When `num` is 0, the first condition `num >= 0` is true, printing "Positive or Zero". The program then moves to the second, independent `if` statement. Its condition `num == 0` is also true, so it prints "Zero". The `else` is attached only to the second `if` and is not executed. The result is two lines of output.
Question 38: Which statement correctly imports only the `sqrt` function from the `math` module?
- import sqrt from math
- from math import sqrt (Correct answer)
- include math.sqrt
- import math.sqrt
Correct answer: from math import sqrt
`from math import sqrt` binds the name `sqrt` directly in the current namespace without importing the full module.
Question 39: What does `yield from` do in a generator function?
- Delegates to a sub-generator, yielding all its values (Correct answer)
- Raises StopIteration immediately
- Creates a new generator function
- Returns all values at once as a list
Correct answer: Delegates to a sub-generator, yielding all its values
yield from sub_gen delegates to a sub-generator, yielding each of its values as if they were in the outer generator.
Question 40: What is the value of `bool(0) or bool(1)`?
- 0
- True (Correct answer)
- False
- 1
Correct answer: True
`bool(0)` is `False` and `bool(1)` is `True`; `False or True` evaluates to `True`.
Question 41: Which of the following code snippets correctly uses the ternary operator to assign 'Adult' to the `status` variable if `age` is 18 or greater, and 'Minor' otherwise?
- status = 'Adult' else 'Minor' if age >= 18
- status = 'Adult' if age >= 18 else 'Minor' (Correct answer)
- status = if age >= 18: 'Adult' else: 'Minor'
- status = age >= 18 ? 'Adult' : 'Minor'
Correct answer: status = 'Adult' if age >= 18 else 'Minor'
The correct syntax for Python's ternary conditional operator is `value_if_true if condition else value_if_false`. This allows for a concise, one-line conditional assignment.
PCAP Certified Associate in Python Programming Exam
The PCAP certification validates intermediate Python skills including object-oriented programming, modules, exceptions, string processing, and advanced control flow.
Exam Rules
- You can skip questions and return to them later
- Flag questions for review before submitting
- No feedback shown until you submit the entire exam
- Unanswered questions count as wrong — answer everything
- 10 pretest questions are mixed in and don't affect your score
- Timer auto-submits when time runs out
- Your progress is auto-saved every 30 seconds
Practice questions written with AI assistance and published by Nathan Beja, founder of Practice Test Geeks. They are not real exam questions. We have not yet matched this exam's facts to an official source, so confirm fees, dates and rules with the exam body. Editorial policy