PCAP Certified Associate in Python Programming Exam — Questions and Answers
Question 1: How do you define a class variable (shared by all instances) in Python?
- Use the global keyword
- Declare it outside any method, inside the class body (Correct answer)
- Use the shared keyword
- Declare it inside __init__ using self
Correct answer: Declare it outside any method, inside the class body
Class variables are defined in the class body outside any method and are shared by all instances.
Question 2: Which of the following statements will correctly check if a variable a is equal to 10?
- if (a == 10)
- if a === 10:
- if a = 10:
- if a == 10: (Correct answer)
Correct answer: if a == 10:
The == operator is used to check equality, and the correct syntax for an if statement in Python ends with a colon.
Question 3: Which of the following is the most common practical use case for closures in Python?
- Replacing class-based inheritance hierarchies entirely
- Factory functions that return specialized functions with pre-configured parameters (Correct answer)
- Speeding up loops by caching loop indices
- Catching exceptions without using try/except blocks
Correct answer: Factory functions that return specialized functions with pre-configured parameters
Closures are frequently used as factory functions (e.g., `make_adder(n)` returns a function that adds `n`) to produce families of related functions that carry private state.
Question 4: What does the f-string `f'Hello {name}'` do?
- Inserts the value of `name` into the string (Correct answer)
- Formats a float
- Encodes the string to bytes
- Creates a raw string
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 5: What does `raise` without an argument do inside an `except` block?
- Creates a new exception chain
- Raises a new RuntimeError
- Re-raises the currently handled exception (Correct answer)
- Suppresses the exception
Correct answer: Re-raises the currently handled exception
A bare `raise` statement re-raises the most recently caught exception with its original traceback.
Question 6: What is the `nonlocal` keyword used for inside a nested function?
- To access global variables without writing the global keyword
- To import names from an enclosing module's namespace
- To declare a constant that cannot be reassigned
- To modify a variable defined in the nearest enclosing non-global scope (Correct answer)
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.
Question 7: What happens if no exception is raised in a `try` block that has an `else` clause?
- The else block is executed (Correct answer)
- A warning is issued
- The else block is skipped
- The program restarts
Correct answer: The else block is executed
The `else` block runs only when no exception is raised in the `try` block.
Question 8: Which attribute of a function object holds the variables captured by its closure?
- __captured__
- __globals__
- __dict__
- __closure__ (Correct answer)
Correct answer: __closure__
`func.__closure__` is a tuple of cell objects, each holding the value of one variable captured from the enclosing scope.
Question 9: What is the `@my_decorator` syntax exactly equivalent to when placed above `def func(): ...`?
- my_decorator.apply(func)
- func = func(my_decorator)
- func = my_decorator(func) (Correct answer)
- func.__decorator__ = 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 10: What is a closure in Python?
- A function that returns multiple values using a tuple
- A function that blocks access to global variables
- A class that implements the __call__ method to behave like a function
- An inner function that captures and remembers variables from the enclosing scope even after the outer function has returned (Correct answer)
Correct answer: An inner function that captures and remembers variables from the enclosing scope even after the outer function has returned
A closure is a nested function that retains access to variables from its enclosing scope, allowing those variables to persist beyond the outer function's lifetime.
Question 11: What does the `self` parameter represent in a Python class method?
- A global variable
- The current instance (Correct answer)
- The parent class
- The class itself
Correct answer: The current instance
`self` refers to the current object instance on which the method is being called.
Question 12: Which method joins a list of strings with a separator?
- list.join(sep)
- merge(list, sep)
- str.concat(list, sep)
- sep.join(list) (Correct answer)
Correct answer: sep.join(list)
`separator.join(iterable)` concatenates iterable elements using the separator string.
Question 13: Which module provides `namedtuple` for creating tuple subclasses with named fields?
- struct
- typing
- dataclasses
- collections (Correct answer)
Correct answer: collections
`collections.namedtuple` creates tuple subclasses with named fields for readable attribute access.
Question 14: What is the correct file extension for Python files?
- .pyt
- .python
- .py (Correct answer)
- .pt
Correct answer: .py
Python files have the extension .py
Question 15: Which file mode opens a file for appending without truncating existing content?
- 'w'
- 'x'
- 'a' (Correct answer)
- 'r+'
Correct answer: 'a'
Mode `'a'` opens a file for appending; writes go to the end without erasing existing data.
Question 16: Which of the following correctly defines a subclass `Dog` inheriting from `Animal`?
- class Dog(Animal): (Correct answer)
- class Dog: Animal
- class Dog inherits Animal:
- class Dog extends Animal:
Correct answer: class Dog(Animal):
Python uses parentheses after the class name to specify the parent class for inheritance.
Question 17: What is the purpose of the `assert` statement in Python?
- To assign default values
- To test a condition and raise AssertionError if false (Correct answer)
- To skip code blocks
- To raise a KeyError
Correct answer: To test a condition and raise AssertionError if false
`assert` tests a condition and raises `AssertionError` if the condition evaluates to False.
Question 18: What is method overriding in Python OOP?
- Calling a method twice
- Defining a method with the same name in a subclass (Correct answer)
- Adding extra parameters to a method
- Deleting a parent class method
Correct answer: Defining a method with the same name in a subclass
Method overriding means redefining a parent class method in a child class with the same name.
Question 19: Which method replaces occurrences of a substring in a string?
- swap()
- replace() (Correct answer)
- substitute()
- change()
Correct answer: replace()
`str.replace(old, new)` returns a new string with all occurrences of `old` replaced by `new`.
Question 20: Which exception is raised when dividing by zero in Python?
- ValueError
- ZeroDivisionError (Correct answer)
- ArithmeticError
- MathError
Correct answer: ZeroDivisionError
`ZeroDivisionError` is raised when attempting to divide a number by zero.
Question 21: Which built-in function is used to open a file in Python?
- read()
- file()
- open() (Correct answer)
- load()
Correct answer: open()
The `open()` function opens a file and returns a file object for reading or writing.
Question 22: Which method would you use to add an item to the end of a list in Python?
- insert()
- append() (Correct answer)
- extend()
- add()
Correct answer: append()
The append() method adds an item to the end of a list.
Question 23: What does the `zip()` function do?
- Sorts two lists together
- Compresses files
- Creates a zipped archive
- Combines multiple iterables element-by-element into tuples (Correct answer)
Correct answer: Combines multiple iterables element-by-element into tuples
`zip()` pairs elements from multiple iterables into tuples, stopping at the shortest iterable.
Question 24: Which module provides tools for working with dates and times in Python?
- calendar
- time
- datetime (Correct answer)
- clock
Correct answer: datetime
The `datetime` module provides classes for manipulating dates and times.
Question 25: What is the purpose of the `__init__` method in a Python class?
- To initialize a new instance (Correct answer)
- To copy an object
- To define class variables
- To destroy an object
Correct answer: To initialize a new instance
`__init__` is the constructor method called automatically when a new object is created.
Question 26: Which built-in function applies a function to every item in an iterable?
- filter()
- apply()
- map() (Correct answer)
- each()
Correct answer: map()
`map()` applies a function to each element of an iterable and returns a map object.
Question 27: What will the following code print? def decorator(func): calls = [] def wrapper(*args, **kwargs): calls.append(args) return func(*args, **kwargs) wrapper.call_log = calls return wrapper @decorator def add(a, b): return a + b add(1, 2) add(3, 4) print(len(add.call_log))
- 1
- 0
- 2 (Correct answer)
- AttributeError: 'function' object has no attribute 'call_log'
Correct answer: 2
`calls` is a mutable list captured in the closure and also attached to `wrapper` as `call_log`; after two calls, both references point to the same list with 2 entries.
Question 28: What is a closure in Python?
- A function that captures variables from its enclosing scope (Correct answer)
- A decorator pattern
- A class with private attributes
- A module with restricted access
Correct answer: A function that captures variables from its enclosing scope
A closure is a function that remembers the variables from its enclosing scope even after that scope has exited.
Question 29: What does `except Exception as e:` allow you to do?
- Skip the except block
- Access the exception object via the variable `e` (Correct answer)
- Re-raise the exception
- Suppress all exceptions
Correct answer: Access the exception object via the variable `e`
The `as e` clause binds the caught exception object to the name `e` for inspection.
Question 30: When the following decorators are applied, in what order are they executed? @decorator_a @decorator_b def func(): pass
- decorator_b wraps func first (innermost), then decorator_a wraps the result (outermost) (Correct answer)
- Both decorators are applied simultaneously in an unspecified order
- decorator_a is applied first, then decorator_b is applied to that result
- The order is determined by each decorator's priority attribute
Correct answer: decorator_b wraps func first (innermost), then decorator_a wraps the result (outermost)
Decorators are applied bottom-up: `decorator_b(func)` is evaluated first, and then `decorator_a` receives that result.
Question 31: Which exception is raised when a variable is used before it is assigned?
- NameError (Correct answer)
- SyntaxError
- ReferenceError
- AttributeError
Correct answer: NameError
`NameError` is raised when a local or global name is not found.
Question 32: Which of the following is used to define a function in Python?
- function
- define
- def (Correct answer)
- func
Correct answer: def
The def keyword is used to define a function in Python.
Question 33: Which string method converts all characters to uppercase?
- swapcase()
- upper() (Correct answer)
- capitalize()
- title()
Correct answer: upper()
`str.upper()` returns a new string with all characters converted to uppercase.
Question 34: What does the `super()` function do in Python?
- Converts to a supertype
- Calls a method from the parent class (Correct answer)
- Creates a superclass
- Deletes the parent class
Correct answer: Calls a method from the parent class
`super()` returns a proxy object that delegates method calls to the parent class.
Question 35: What does a generator expression return compared to a list comprehension?
- A lazy iterator evaluated on demand (Correct answer)
- A tuple
- A set
- A list evaluated immediately
Correct answer: A lazy iterator evaluated on demand
A generator expression (using parentheses) returns an iterator that yields values lazily, using less memory.
Question 36: What does `**kwargs` allow in a function definition?
- Variable keyword arguments as a dictionary (Correct answer)
- Default arguments
- Forced keyword-only arguments
- Variable positional arguments
Correct answer: Variable keyword arguments as a dictionary
`**kwargs` collects extra keyword arguments into a dictionary inside the function.
Question 37: What does the `'b'` flag in `open('file', 'rb')` indicate?
- Backup mode
- Block mode
- Buffered mode
- Binary mode (Correct answer)
Correct answer: Binary mode
The `'b'` flag opens the file in binary mode, reading/writing raw bytes instead of text.
Question 38: What will the following code print? def outer(): x = 10 def inner(): print(x) x = 20 return inner f = outer() f()
- None
- NameError: name 'x' is not defined
- 10
- 20 (Correct answer)
Correct answer: 20
Closures capture the variable binding (a reference to the cell), not a snapshot of the value at definition time, so `x` is 20 when `inner` runs.
Question 39: What does `sorted()` return?
- A sorted tuple
- A sorted iterator
- The original list sorted in place
- A new sorted list (Correct answer)
Correct answer: A new sorted list
`sorted()` returns a new sorted list without modifying the original iterable.
Question 40: What does `__all__` in a module control?
- The module's docstring
- All global variables
- All function signatures
- Which names are exported when `from module import *` is used (Correct answer)
Correct answer: Which names are exported when `from module import *` is used
`__all__` is a list that defines the public interface of a module for wildcard imports.
Question 41: How do you import only the `sqrt` function from the `math` module?
- from math import sqrt (Correct answer)
- import sqrt from math
- import math.sqrt
- include math.sqrt
Correct answer: from math import sqrt
The `from module import name` syntax imports a specific name from a module.
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