PCAP Certified Associate in Python Programming Exam — Questions and Answers
Question 1: What is the output of `print(10 // 3)`?
- 3 (Correct answer)
- 4
- 3.0
- 3.33
Correct answer: 3
Floor division `//` divides and rounds down to the nearest integer, giving 3.
Question 2: 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 `pickle` module with the `'wb'` mode. (Correct answer)
- The `sys` module with the `'w'` mode.
- The `os` module with the `'wb'` mode.
- The `json` module with the `'w'` 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 3: What is the purpose of PYTHONSTARTUP?
- It is needed while booting of a particular process
- None of these
- It is executed every time you start the interpreter (Correct answer)
- It is executed every time you start the compiler
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 4: What does the with statement guarantee when used with open()?
- The file is closed automatically when the block exits (Correct answer)
- No exceptions can occur inside the block
- The file is read into memory entirely
- The file is opened in binary mode
Correct answer: The file is closed automatically when the block exits
The with statement invokes the file object's __exit__ method, which closes the file even if an exception is raised.
Question 5: What is the result of calling a function that has no `return` statement?
- None (Correct answer)
- Raises RuntimeError
- 0
- An empty string
Correct answer: None
Python functions implicitly return `None` when execution reaches the end without a `return` statement.
Question 6: What problem does a circular import cause in Python?
- Python raises an ImportError and refuses to run either module
- The second module is silently skipped and not imported
- One module may see an incomplete version of the other because it is still being initialized (Correct answer)
- Python imports both modules twice, causing duplicate definitions
Correct answer: One module may see an incomplete version of the other because it is still being initialized
During a circular import, the partially initialized module is placed in `sys.modules`, so the second module may access attributes that haven't been defined yet.
Question 7: What is encapsulation in OOP?
- Bundling data and methods that operate on that data within a class, restricting direct access (Correct answer)
- Defining a class inside another class
- Using decorators to wrap methods
- Inheriting behavior from a parent class
Correct answer: Bundling data and methods that operate on that data within a class, restricting direct access
Encapsulation hides internal state and exposes only what's necessary through a public interface, protecting the object's integrity.
Question 8: What does `d.items()` return?
- A list of keys
- A list of values
- A copy of the dictionary
- A view of (key, value) tuples (Correct answer)
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 9: What is the output of: `i = 0 while True: i += 1 if i == 3: break print(i)`?
- 2
- Infinite loop
- 4
- 3 (Correct answer)
Correct answer: 3
The loop breaks when `i` becomes 3, so `print(i)` outputs 3.
Question 10: How can a custom exception class pass additional data to the handler?
- By using a global variable
- By printing to stderr before raising
- By overriding __init__ to store extra attributes (Correct answer)
- Custom exceptions cannot carry extra data
Correct answer: By overriding __init__ to store extra attributes
Override `__init__` in your custom exception to accept and store extra attributes that handlers can access via the exception object.
Question 11: Which of the following is NOT a built-in Python decorator?
- @staticmethod
- @property
- @classmethod
- @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 12: What is the primary difference in the return value between the `read()` and `readlines()` file methods in Python?
- `read()` returns a generator object for iterating over lines, while `readlines()` loads all lines into memory at once.
- `read()` returns a list of lines, while `readlines()` returns a single string containing the entire file content.
- Both methods return a list of strings, but `readlines()` includes newline characters while `read()` does not.
- `read()` returns a single string containing the entire file content, while `readlines()` returns a list of strings, where each string is a line from the file. (Correct answer)
Correct answer: `read()` returns a single string containing the entire file content, while `readlines()` returns a list of strings, where each string is a line from the file.
The `file.read()` method, when called without an argument, reads the entire content of a file and returns it as a single string. In contrast, the `file.readlines()` method reads all lines from the file and returns them as a list of strings, with each string in the list representing one line and including the trailing newline character.
Question 13: What is `ExceptionGroup` introduced in Python 3.11 used for?
- Raising multiple unrelated exceptions simultaneously (Correct answer)
- Nesting try blocks
- Grouping exception classes in a single except clause
- Logging multiple warnings
Correct answer: Raising multiple unrelated exceptions simultaneously
`ExceptionGroup` allows raising and handling multiple concurrent exceptions at once, primarily useful in async/concurrent code.
Question 14: What is the effect of deleting a module from `sys.modules` and then reimporting it?
- Python raises an ImportError because the module no longer exists
- The old module object is returned from cache
- The module's source file is re-executed and a fresh module object is created (Correct answer)
- The module is reloaded in place without re-executing its code
Correct answer: The module's source file is re-executed and a fresh module object is created
Removing a module from `sys.modules` causes the next import to treat it as never loaded, re-executing its code and producing a new module object.
Question 15: How do you make a class attribute read-only for instances?
- Use `@staticmethod`
- Define it in `__slots__`
- Use `@property` with only a getter and no setter (Correct answer)
- Prefix it with `__`
Correct answer: Use `@property` with only a getter and no setter
A `@property` with only a getter raises `AttributeError` on assignment, effectively making the attribute read-only from outside.
Question 16: What is the output of `len('hello world')`?
- 10
- 9
- 11 (Correct answer)
- 12
Correct answer: 11
The string 'hello world' has 5 + 1 space + 5 = 11 characters.
Question 17: What does json.dump(obj, fp) do versus json.dumps(obj)?
- dump() writes to a file object; dumps() returns a string (Correct answer)
- They are identical in behavior
- dump() is for binary files; dumps() is for text files
- dump() returns a string; dumps() writes to a file
Correct answer: dump() writes to a file object; dumps() returns a string
json.dump() serializes obj and writes directly to a file-like object fp, while json.dumps() returns the JSON string.
Question 18: What does `'hello'.upper()` return?
- 'Hello'
- None
- 'hello'
- 'HELLO' (Correct answer)
Correct answer: 'HELLO'
upper() returns a new string with all characters converted to uppercase.
Question 19: What is the result of `type(3.0)` in Python?
- <class 'float'> (Correct answer)
- <class 'number'>
- <class 'int'>
- <class 'double'>
Correct answer: <class 'float'>
3.0 is a floating-point literal, so its type is `float`.
Question 20: Which Python built-in returns the memory address of an object?
- addr()
- ref()
- id() (Correct answer)
- mem()
Correct answer: id()
`id()` returns the unique integer identity (memory address) of an object.
Question 21: Which syntax is used in Python 3.11+ to handle individual exceptions from an ExceptionGroup?
- catch TypeError
- multi-except TypeError
- except* TypeError (Correct answer)
- except[] ExceptionGroup
Correct answer: except* TypeError
`except*` (star-except) is new syntax in Python 3.11 for handling specific exception types within an `ExceptionGroup`.
Question 22: What is the precedence order (highest to lowest) for these operators: `+`, `**`, `*`?
- **, +, *
- +, *, **
- **, *, + (Correct answer)
- *, **, +
Correct answer: **, *, +
Python's operator precedence places `**` (exponentiation) highest, then `*` (multiplication), then `+` (addition).
Question 23: What is the difference between a regular package and a namespace package?
- A regular package is a `.zip` archive; a namespace package is a directory
- A namespace package is installed via pip; a regular package is local only
- A regular package can only be imported once; a namespace package can be reloaded
- A regular package has `__init__.py`; a namespace package does not and can span multiple directories (Correct answer)
Correct answer: A regular package has `__init__.py`; a namespace package does not and can span multiple directories
Regular packages require `__init__.py`; namespace packages (PEP 420) lack it and allow merging directories across multiple locations into one logical package.
Question 24: Which of the following correctly defines a class method in Python?
- @staticmethod def method(cls):
- @classmethod def method(cls): (Correct answer)
- @classmethod def method(self):
- def method(self):
Correct answer: @classmethod def method(cls):
Class methods are decorated with `@classmethod` and receive the class itself as the first argument, conventionally named `cls`.
Question 25: Which file must exist in a directory for Python 2 to treat it as a package?
- setup.py
- package.py
- __main__.py
- __init__.py (Correct answer)
Correct answer: __init__.py
In Python 2, a directory must contain `__init__.py` to be recognized as a package; Python 3 introduced namespace packages that don't require it.
Question 26: What is the purpose of `__new__` in Python classes?
- To allocate and return a new instance before `__init__` is called (Correct answer)
- To define class-level variables
- To initialize instance attributes after creation
- To clone an existing instance
Correct answer: To allocate and return a new instance before `__init__` is called
`__new__` is a static method that creates and returns the new object; `__init__` then initializes it.
Question 27: Which of the following statements about the `raise` keyword in Python is true?
- Using `raise` by itself inside an `except` block re-raises the active exception, preserving its original traceback. (Correct answer)
- The `raise` keyword can only be used with built-in exception types.
- The `raise` keyword is used to create a new exception class.
- Using `raise` by itself inside an `except` block is invalid syntax.
Correct answer: Using `raise` by itself inside an `except` block re-raises the active exception, preserving its original traceback.
When `raise` is used without an exception object inside an `except` block, it re-raises the exception that was just caught. This is useful for logging an error before passing it up the call stack. This action preserves the original error's traceback, which is crucial for debugging.
Question 28: What does `'a,b,c'.split(',')` return?
- {'a','b','c'}
- 'a b c'
- ('a','b','c')
- ['a','b','c'] (Correct answer)
Correct answer: ['a','b','c']
split() divides a string on the given separator and returns a list of substrings.
Question 29: Which Python data structure guarantees FIFO (first-in, first-out) ordering?
- dict
- list
- set
- collections.deque used as a queue (Correct answer)
Correct answer: collections.deque used as a queue
`collections.deque` with `append()` and `popleft()` provides O(1) FIFO queue operations.
Question 30: Which built-in Python module provides the lru_cache decorator for automatic memoization?
- itertools
- collections
- functools (Correct answer)
- operator
Correct answer: functools
functools.lru_cache is a built-in decorator that implements memoization with a Least Recently Used eviction strategy to limit cache size.
Question 31: What is the output of `[x**2 for x in range(4)]`?
- [1, 2, 3, 4]
- [1, 4, 9, 16]
- [0, 1, 4, 9] (Correct answer)
- [0, 1, 2, 3]
Correct answer: [0, 1, 4, 9]
range(4) produces 0, 1, 2, 3, and squaring each gives [0, 1, 4, 9].
Question 32: What does a `try/except/finally` block guarantee about the `finally` clause?
- It runs only if an exception occurs
- It runs only if no exception occurs
- It always runs regardless of exceptions (Correct answer)
- It runs only after `except` handles an error
Correct answer: It always runs regardless of exceptions
The `finally` block always executes whether an exception was raised or not, making it ideal for cleanup.
Question 33: What does `'hello world'.title()` return?
- 'Hello world'
- 'hello world'
- 'HELLO WORLD'
- 'Hello World' (Correct answer)
Correct answer: 'Hello World'
title() capitalizes the first letter of every word and lowercases the rest.
Question 34: How do you re-raise the currently-handled exception without losing the original traceback?
- raise (Correct answer)
- raise Exception()
- raise Exception from None
- throw
Correct answer: raise
A bare `raise` statement inside an `except` block re-raises the current exception while preserving its original traceback.
Question 35: 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 36: What is the purpose of the `raise ... from ...` syntax introduced in Python 3?
- To chain exceptions and explicitly set the cause (Correct answer)
- To silence the original exception
- To convert one exception type to another silently
- To re-raise the same exception
Correct answer: To chain exceptions and explicitly set the cause
`raise NewException() from original` explicitly chains exceptions, setting `__cause__` so the traceback shows the causal relationship.
Question 37: Which f-string expression correctly formats a float to 2 decimal places?
- f'{value:.2}'
- f'{value:.2f}' (Correct answer)
- f'{value:2f}'
- f'{value|2f}'
Correct answer: f'{value:.2f}'
The format spec :.2f means fixed-point notation with 2 digits after the decimal.
Question 38: Which method checks if all characters in a string are digits?
- isdigit() (Correct answer)
- isnum()
- isnumeric()
- isinteger()
Correct answer: isdigit()
isdigit() returns True if every character in the string is a decimal digit (0–9).
Question 39: Which of the following is the LAST place the Python interpreter will look when trying to resolve an `import my_module` statement?
- The directory containing the script that is running.
- Directories listed in the `PYTHONPATH` environment variable.
- A randomly selected user-created directory.
- Installation-dependent default directories, such as `site-packages`. (Correct answer)
Correct answer: Installation-dependent default directories, such as `site-packages`.
Python's module search path, accessible via `sys.path`, has a defined order. It first checks the directory of the currently running script, then the directories in the `PYTHONPATH` environment variable, and finally, it checks the standard library and installation-dependent default locations like `site-packages`. A random directory is never checked.
Question 40: Which io class should you use to work with in-memory text streams?
- io.BytesIO
- io.StringIO (Correct answer)
- io.BufferedReader
- io.FileIO
Correct answer: io.StringIO
io.StringIO provides an in-memory stream for text, implementing the same interface as a regular text file.
Question 41: Which method returns the index of the first occurrence of a substring, or -1 if not found?
- search()
- find() (Correct answer)
- index()
- locate()
Correct answer: find()
find() returns the lowest index where the substring is found, or -1 if absent; index() raises ValueError instead.
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