PCAP Certified Associate in Python Programming Exam — Questions and Answers
Question 1: Which file mode opens a file for appending without truncating existing content?
- 'x'
- 'w'
- 'a' (Correct answer)
- 'r+'
Correct answer: 'a'
Mode `'a'` opens a file for appending; writes go to the end without erasing existing data.
Question 2: What will be the result of the following code?br my_set = {1, 2, 3}br my_set.add(2)br print(my_set)
- {1, 2, 3} (Correct answer)
- {1, 2, 3, 2}
- {2, 3}
- {1, 3}
Correct answer: {1, 2, 3}
Sets do not allow duplicate elements, so adding an existing element does not change the set.
Question 3: Which exception is raised when a function receives an argument with an incorrect value?
- TypeError
- RuntimeError
- ValueError (Correct answer)
- AttributeError
Correct answer: ValueError
`ValueError` is raised when an operation receives an argument of the right type but an inappropriate value.
Question 4: What does `except (TypeError, ValueError):` do?
- Raises both exceptions
- Catches only ValueError
- Catches only TypeError
- Catches either TypeError or ValueError (Correct answer)
Correct answer: Catches either TypeError or ValueError
A tuple of exception types in an except clause catches any of those exception types.
Question 5: Which keyword is used to handle exceptions in Python?
- except (Correct answer)
- handle
- rescue
- catch
Correct answer: except
The `except` clause in a `try` block is used to catch and handle exceptions.
Question 6: What is the difference between a `return` and `yield` in a function?
- `yield` exits the function; `return` pauses it
- `yield` raises StopIteration
- `return` exits the function; `yield` pauses and resumes it (Correct answer)
- They are identical
Correct answer: `return` exits the function; `yield` pauses and resumes it
`return` terminates the function entirely while `yield` suspends it and can resume on the next call.
Question 7: Which built-in function returns the larger of two values?
- top()
- max() (Correct answer)
- greater()
- largest()
Correct answer: max()
`max()` returns the largest item in an iterable or the largest of two or more arguments.
Question 8: What does the `__name__ == '__main__'` guard do?
- Sets the module name
- Checks Python version
- Defines the main function
- Prevents code from running when the module is imported (Correct answer)
Correct answer: Prevents code from running when the module is imported
Code under `if __name__ == '__main__':` runs only when the script is executed directly, not when imported.
Question 9: What does the following code print?
- 1234
- 12 (Correct answer)
- 123
- 123
Correct answer: 12
The range(3) function generates numbers from 0 to 2, and the for loop prints each number in this range.
Question 10: What is the result of using `@staticmethod` decorator on a method?
- The method has no access to instance or class (Correct answer)
- The method has access to the class via cls
- The method is called automatically
- The method becomes private
Correct answer: The method has no access to instance or class
A static method does not receive an implicit first argument and cannot access instance or class state.
Question 11: What does the f-string `f'Hello {name}'` do?
- Inserts the value of `name` into the string (Correct answer)
- Formats a float
- Creates a raw string
- Encodes the string to bytes
Correct answer: Inserts the value of `name` into the string
f-strings (formatted string literals) evaluate expressions in `{}` and embed them in the string.
Question 12: Why should a decorator's wrapper function use `*args, **kwargs` instead of matching the wrapped function's exact signature?
- To prevent the wrapped function from receiving unintended arguments
- To make the wrapper behave as a generator function
- To convert all positional arguments into keyword arguments automatically
- So the decorator is generic and can wrap any function regardless of its parameter signature (Correct answer)
Correct answer: So the decorator is generic and can wrap any function regardless of its parameter signature
Using `*args, **kwargs` makes the wrapper transparent — it accepts and forwards any combination of arguments — so one decorator can work with functions of any signature.
Question 13: What is the purpose of the `__init__` method in a Python class?
- To define class variables
- To destroy an object
- To copy an object
- To initialize a new instance (Correct answer)
Correct answer: To initialize a new instance
`__init__` is the constructor method called automatically when a new object is created.
Question 14: Which of the following correctly defines a subclass `Dog` inheriting from `Animal`?
- class Dog extends Animal:
- class Dog(Animal): (Correct answer)
- class Dog: Animal
- class Dog inherits Animal:
Correct answer: class Dog(Animal):
Python uses parentheses after the class name to specify the parent class for inheritance.
Question 15: Which exception is raised when a variable is used before it is assigned?
- SyntaxError
- ReferenceError
- AttributeError
- NameError (Correct answer)
Correct answer: NameError
`NameError` is raised when a local or global name is not found.
Question 16: What will `print(greet.__name__)` output? import functools def my_decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @my_decorator def greet(): pass
- my_decorator
- None
- greet (Correct answer)
- wrapper
Correct answer: greet
Because `@functools.wraps(func)` is applied, the wrapper inherits the original function's `__name__`, so it prints `greet`.
Question 17: What is the `@my_decorator` syntax exactly equivalent to when placed above `def func(): ...`?
- my_decorator.apply(func)
- func = my_decorator(func) (Correct answer)
- func.__decorator__ = my_decorator
- func = func(my_decorator)
Correct answer: func = my_decorator(func)
`@my_decorator` is syntactic sugar: Python calls `my_decorator(func)` and rebinds the name `func` to whatever is returned.
Question 18: What mode string opens a file for writing, creating it if it does not exist and truncating if it does?
- 'a'
- 'r'
- 'w' (Correct answer)
- 'x'
Correct answer: 'w'
Mode `'w'` opens a file for writing, creating it if absent and clearing it if it exists.
Question 19: How do you split a string `s` by commas?
- s.divide(',')
- s.split(',') (Correct answer)
- s.cut(',')
- split(s, ',')
Correct answer: s.split(',')
`str.split(delimiter)` splits the string at each occurrence of the delimiter and returns a list.
Question 20: Which method would you use to add an item to the end of a list in Python?
- extend()
- append() (Correct answer)
- insert()
- add()
Correct answer: append()
The append() method adds an item to the end of a list.
Question 21: What is a recursive function?
- A function defined inside a class
- A function that calls itself (Correct answer)
- A function without parameters
- A function that imports itself
Correct answer: A function that calls itself
A recursive function is one that calls itself, with a base case to terminate the recursion.
Question 22: What does the `@classmethod` decorator do?
- Makes a method run at class creation
- Passes the class as the first argument instead of the instance (Correct answer)
- Prevents overriding
- Makes a method private
Correct answer: Passes the class as the first argument instead of the instance
A class method receives the class (`cls`) as its first argument instead of the instance (`self`).
Question 23: What does `@functools.wraps(func)` do when applied inside a decorator's wrapper function?
- Makes the wrapper function execute faster by bypassing Python's call overhead
- Copies the wrapped function's metadata (__name__, __doc__, __module__, etc.) onto the wrapper (Correct answer)
- Creates a deep copy of the original function's bytecode
- Prevents the decorator from being stacked with other decorators
Correct answer: Copies the wrapped function's metadata (__name__, __doc__, __module__, etc.) onto the wrapper
`@functools.wraps(func)` preserves the original function's identity attributes on the wrapper so introspection tools and documentation generators see the correct name and docstring.
Question 24: Which built-in function is used to open a file in Python?
- open() (Correct answer)
- read()
- load()
- file()
Correct answer: open()
The `open()` function opens a file and returns a file object for reading or writing.
Question 25: How do you raise a custom exception in Python?
- raise Exception('msg') (Correct answer)
- trigger Exception('msg')
- error Exception('msg')
- throw Exception('msg')
Correct answer: raise Exception('msg')
Python uses the `raise` keyword to manually throw an exception.
Question 26: What does `re.match()` do differently from `re.search()`?
- match() only matches at the beginning of the string (Correct answer)
- match() returns all matches
- match() uses extended regex
- match() is case-insensitive
Correct answer: match() only matches at the beginning of the string
`re.match()` only looks at the beginning of the string, while `re.search()` scans the entire string.
Question 27: What does the `copy` module's `deepcopy()` function do?
- Copies only primitive values
- Creates a reference to the original
- Copies only the top-level object
- Recursively copies an object and all objects it references (Correct answer)
Correct answer: Recursively copies an object and all objects it references
`deepcopy()` creates a completely independent copy of an object, recursively copying all nested objects.
Question 28: Which attribute of a function object holds the variables captured by its closure?
- __globals__
- __captured__
- __closure__ (Correct answer)
- __dict__
Correct answer: __closure__
`func.__closure__` is a tuple of cell objects, each holding the value of one variable captured from the enclosing scope.
Question 29: What will this code output? def make_counter(): count = 0 def counter(): nonlocal count count += 1 return count return counter c = make_counter() print(c(), c(), c())
- NameError: name 'count' is not defined
- 0 1 2
- 1 1 1
- 1 2 3 (Correct answer)
Correct answer: 1 2 3
Each call to `c()` increments the shared `count` variable via `nonlocal`, producing 1, 2, then 3.
Question 30: Which `json` function parses a JSON string into a Python object?
- json.decode()
- json.loads() (Correct answer)
- json.parse()
- json.load()
Correct answer: json.loads()
`json.loads()` deserializes a JSON string into a Python object (`loads` = load from string).
Question 31: What is a decorator in Python?
- A callable that takes a function as an argument, extends its behavior, and returns a new callable (Correct answer)
- A built-in design pattern that replaces multiple inheritance
- A special comment syntax that annotates function signatures for type checking
- A Python keyword that formats string output
Correct answer: A callable that takes a function as an argument, extends its behavior, and returns a new callable
A decorator is a higher-order function that wraps another function to add behavior before, after, or around the original call without modifying its source code.
Question 32: How do you create an instance of a class named `Car`?
- new Car()
- Car() (Correct answer)
- Car.new()
- instance(Car)
Correct answer: Car()
You instantiate a class by calling it like a function: `Car()`.
Question 33: What does `raise` without an argument do inside an `except` block?
- Creates a new exception chain
- Suppresses the exception
- Raises a new RuntimeError
- Re-raises the currently handled exception (Correct answer)
Correct answer: Re-raises the currently handled exception
A bare `raise` statement re-raises the most recently caught exception with its original traceback.
Question 34: What does the `zip()` function do?
- Creates a zipped archive
- Combines multiple iterables element-by-element into tuples (Correct answer)
- Sorts two lists together
- Compresses files
Correct answer: Combines multiple iterables element-by-element into tuples
`zip()` pairs elements from multiple iterables into tuples, stopping at the shortest iterable.
Question 35: How do you import only the `sqrt` function from the `math` module?
- import math.sqrt
- include math.sqrt
- from math import sqrt (Correct answer)
- import sqrt from math
Correct answer: from math import sqrt
The `from module import name` syntax imports a specific name from a module.
Question 36: What does `file.readlines()` return?
- A bytes object
- A single string
- A generator of lines
- A list of strings, one per line (Correct answer)
Correct answer: A list of strings, one per line
`readlines()` reads all lines and returns them as a list of strings including newline characters.
Question 37: How is a decorator that accepts its own arguments (a parameterized decorator) structured?
- Arguments are attached as attributes on the decorator function before applying it
- The decorator class uses __init__ to store arguments and __call__ to act as the wrapper directly
- Arguments are passed directly in the @decorator(args) call and the function takes them as *args
- An outer function accepts the arguments and returns a decorator function that accepts and wraps the target function (Correct answer)
Correct answer: An outer function accepts the arguments and returns a decorator function that accepts and wraps the target function
A parameterized decorator requires one extra nesting level: `@repeat(3)` means `repeat(3)` runs first and must return a regular (no-argument) decorator.
Question 38: How do you start a comment in Python?
- --
- /*
- B) # (Correct answer)
- A) //
Correct answer: B) #
In Python, comments are started with the # symbol.
Question 39: Which keyword is used in a generator function to produce a value?
- yield (Correct answer)
- send
- return
- emit
Correct answer: yield
`yield` suspends the function and sends a value to the caller, resuming on the next iteration.
Question 40: What does `os.path.join('folder', 'file.txt')` return on Linux?
- folder\file.txt
- folder:file.txt
- folder+file.txt
- folder/file.txt (Correct answer)
Correct answer: folder/file.txt
`os.path.join()` combines path components using the OS-appropriate separator (`/` on Unix/Linux).
Question 41: What is the `nonlocal` keyword used for inside a nested function?
- To declare a constant that cannot be reassigned
- To import names from an enclosing module's namespace
- To modify a variable defined in the nearest enclosing non-global scope (Correct answer)
- To access global variables without writing the global keyword
Correct answer: To modify a variable defined in the nearest enclosing non-global scope
`nonlocal` tells Python that an assignment in the nested function targets the variable in the enclosing scope rather than creating a new local variable.
PCAP Certified Associate in Python Programming Exam
The PCAP-31-03 exam by the Python Institute certifies intermediate Python programmers, assessing their ability to design, write, and debug multi-module programs using object-oriented programming, exception handling, string processing, modules, and file I/O.
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