PCAP Certified Associate in Python Programming Exam — Questions and Answers
Question 1: Which exception is raised when dividing by zero in Python?
- ArithmeticError
- ValueError
- MathError
- ZeroDivisionError (Correct answer)
Correct answer: ZeroDivisionError
`ZeroDivisionError` is raised when attempting to divide a number by zero.
Question 2: Which keyword is used to handle exceptions in Python?
- rescue
- catch
- except (Correct answer)
- handle
Correct answer: except
The `except` clause in a `try` block is used to catch and handle exceptions.
Question 3: What does `sorted()` return?
- A sorted tuple
- The original list sorted in place
- A sorted iterator
- A new sorted list (Correct answer)
Correct answer: A new sorted list
`sorted()` returns a new sorted list without modifying the original iterable.
Question 4: Which method reads the entire file content as a single string?
- readline()
- fetch()
- readlines()
- read() (Correct answer)
Correct answer: read()
`file.read()` reads the entire file and returns it as a single string.
Question 5: What is a set comprehension in Python?
- [x for x in iterable]
- set(x for x in iterable)
- (x for x in iterable)
- {x for x in iterable} (Correct answer)
Correct answer: {x for x in iterable}
Set comprehensions use curly braces without key-value pairs: `{expression for item in iterable}`.
Question 6: Which block always executes regardless of whether an exception occurred?
- try
- else
- finally (Correct answer)
- except
Correct answer: finally
The `finally` block always runs whether or not an exception was raised, used for cleanup.
Question 7: What does `**kwargs` allow in a function definition?
- Variable keyword arguments as a dictionary (Correct answer)
- Variable positional arguments
- Forced keyword-only arguments
- Default arguments
Correct answer: Variable keyword arguments as a dictionary
`**kwargs` collects extra keyword arguments into a dictionary inside the function.
Question 8: What will the following code print? def outer(x): def inner(y): return x + y return inner add5 = outer(5) print(add5(3))
- 5
- TypeError: unsupported operand type
- 3
- 8 (Correct answer)
Correct answer: 8
`outer(5)` returns `inner` with `x` closed over as 5, so calling `add5(3)` computes 5 + 3 = 8.
Question 9: Which keyword is used to define a class in Python?
- class (Correct answer)
- def
- struct
- object
Correct answer: class
The `class` keyword is used to define a class in Python.
Question 10: How do you split a string `s` by commas?
- s.divide(',')
- split(s, ',')
- s.cut(',')
- s.split(',') (Correct answer)
Correct answer: s.split(',')
`str.split(delimiter)` splits the string at each occurrence of the delimiter and returns a list.
Question 11: Which method checks if a string starts with a given prefix?
- beginswith()
- startswith() (Correct answer)
- prefix()
- starts()
Correct answer: startswith()
`str.startswith(prefix)` returns True if the string starts with the specified prefix.
Question 12: What does the `@classmethod` decorator do?
- Makes a method private
- Makes a method run at class creation
- Prevents overriding
- Passes the class as the first argument instead of the instance (Correct answer)
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 13: Which attribute stores the name of a class in Python?
- __type__
- __classname__
- __name__
- __class__.__name__ (Correct answer)
Correct answer: __class__.__name__
`__class__.__name__` returns the name of the class of an object as a string.
Question 14: 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 15: What is encapsulation in object-oriented programming?
- Using multiple classes at once
- Overriding parent methods
- Bundling data and methods within a class (Correct answer)
- Inheriting methods from a parent class
Correct answer: Bundling data and methods within a class
Encapsulation bundles data (attributes) and behavior (methods) together inside a class.
Question 16: How do you create a custom exception class in Python?
- Inherit from object
- Use the @exception decorator
- Inherit from Exception (Correct answer)
- Inherit from BaseError
Correct answer: Inherit from Exception
Custom exceptions are created by subclassing `Exception` or one of its subclasses.
Question 17: Which string method counts non-overlapping occurrences of a substring?
- occurrences()
- find_all()
- frequency()
- count() (Correct answer)
Correct answer: count()
`str.count(sub)` returns the number of non-overlapping occurrences of the substring.
Question 18: How do you create an instance of a class named `Car`?
- Car.new()
- instance(Car)
- new Car()
- Car() (Correct answer)
Correct answer: Car()
You instantiate a class by calling it like a function: `Car()`.
Question 19: What is a generator function in Python?
- A function that returns a list
- A function using `yield` to produce a sequence lazily (Correct answer)
- A factory function
- A function that generates random numbers
Correct answer: A function using `yield` to produce a sequence lazily
A generator function uses `yield` to produce values one at a time, suspending state between calls.
Question 20: What is polymorphism in Python?
- Using multiple inheritance
- Multiple classes responding to the same interface (Correct answer)
- A method with default parameters
- A class with many attributes
Correct answer: Multiple classes responding to the same interface
Polymorphism allows different classes to be used through the same interface by implementing the same methods.
Question 21: What will be the output of the following code?
- Hello World (Correct answer)
- HelloWorld
- Hello + World
- HelloWorld
Correct answer: Hello World
The + operator concatenates strings in Python, and adding " " between x and y results in "Hello World".
Question 22: What does `except Exception as e:` allow you to do?
- Skip the except block
- Re-raise the exception
- Suppress all exceptions
- Access the exception object via the variable `e` (Correct answer)
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 23: What is a closure in Python?
- 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)
- A function that blocks access to global variables
- A function that returns multiple values using a tuple
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 24: Which attribute of a function object holds the variables captured by its closure?
- __dict__
- __globals__
- __captured__
- __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 25: What does `functools.wraps` do when used in a decorator?
- Prevents the decorator from running
- Preserves the original function's metadata (Correct answer)
- Speeds up function execution
- Adds logging automatically
Correct answer: Preserves the original function's metadata
`functools.wraps` copies the original function's `__name__`, `__doc__`, etc. to the wrapper function.
Question 26: Which method is called when an object is deleted or garbage collected?
- __end__
- __destroy__
- __del__ (Correct answer)
- __init__
Correct answer: __del__
`__del__` is the destructor method called when an object is about to be destroyed.
Question 27: Which data type is used to store text in Python?
- float
- int
- str (Correct answer)
- bool
Correct answer: str
The str data type is used to store text in Python
Question 28: Which module provides `namedtuple` for creating tuple subclasses with named fields?
- typing
- dataclasses
- collections (Correct answer)
- struct
Correct answer: collections
`collections.namedtuple` creates tuple subclasses with named fields for readable attribute access.
Question 29: Which file mode opens a file for appending without truncating existing content?
- 'r+'
- 'a' (Correct answer)
- 'x'
- 'w'
Correct answer: 'a'
Mode `'a'` opens a file for appending; writes go to the end without erasing existing data.
Question 30: What mode string opens a file for writing, creating it if it does not exist and truncating if it does?
- 'a'
- 'w' (Correct answer)
- 'x'
- 'r'
Correct answer: 'w'
Mode `'w'` opens a file for writing, creating it if absent and clearing it if it exists.
Question 31: Which of the following is the most common practical use case for closures in Python?
- Replacing class-based inheritance hierarchies entirely
- Speeding up loops by caching loop indices
- Catching exceptions without using try/except blocks
- Factory functions that return specialized functions with pre-configured parameters (Correct answer)
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 32: What does the f-string `f'Hello {name}'` do?
- Creates a raw string
- Formats a float
- Encodes the string to bytes
- Inserts the value of `name` into the string (Correct answer)
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 33: What is the result of `list(zip([1,2,3], [4,5]))`?
- [(1,4),(2,5)] (Correct answer)
- [(1,4),(2,5),(3,None)]
- [(1,4),(2,5),(3,5)]
- [(1,2,3),(4,5)]
Correct answer: [(1,4),(2,5)]
`zip()` stops at the shortest iterable, so only the first two pairs are produced.
Question 34: Which built-in function returns the sum of all elements in an iterable?
- total()
- reduce()
- sum() (Correct answer)
- add()
Correct answer: sum()
`sum(iterable)` returns the total of all numeric elements in the iterable.
Question 35: What does `itertools.chain([1,2], [3,4])` produce?
- [[1,2],[3,4]]
- An iterator yielding 1,2,3,4 (Correct answer)
- A zip of the two lists
- A combined sorted list
Correct answer: An iterator yielding 1,2,3,4
`itertools.chain()` creates a single iterator that yields elements from multiple iterables in sequence.
Question 36: What does `raise` without an argument do inside an `except` block?
- Suppresses the exception
- Creates a new exception chain
- 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 37: What is the output of the following code?
- 8 (Correct answer)
- 23
- 6
- 9
- print(2 ** 3)
Correct answer: 8
The ** operator in Python is used for exponentiation. 2 ** 3 equals 8.
Question 38: What does the `global` keyword do inside a function?
- Imports a global module
- Creates a new global variable
- Declares that a variable refers to the global scope (Correct answer)
- Prevents variable modification
Correct answer: Declares that a variable refers to the global scope
`global` tells Python that the variable inside the function refers to the global namespace, not a local one.
Question 39: Which of the following correctly defines a subclass `Dog` inheriting from `Animal`?
- class Dog inherits Animal:
- class Dog extends Animal:
- class Dog(Animal): (Correct answer)
- class Dog: Animal
Correct answer: class Dog(Animal):
Python uses parentheses after the class name to specify the parent class for inheritance.
Question 40: What does the `super()` function do in Python?
- Deletes the parent class
- Calls a method from the parent class (Correct answer)
- Converts to a supertype
- Creates a superclass
Correct answer: Calls a method from the parent class
`super()` returns a proxy object that delegates method calls to the parent class.
Question 41: Which keyword is used in a generator function to produce a value?
- send
- emit
- return
- yield (Correct answer)
Correct answer: yield
`yield` suspends the function and sends a value to the caller, resuming on the next iteration.
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
These practice questions were written with AI tools. They are not real exam questions. Exam facts are checked against the official sources listed below. Not reviewed by a subject-matter expert. Editorial policy
Sources & references
Exam facts on this page (fees, format, dates, passing scores) are checked against these official sources; the date is our last check. Editorial policy
- pythoninstitute.org — Eligibility, fees, exam format, passing score, retake fee, retake policy, score release, time limit, score validity, exam information · verified Oct 2026
- home.pearsonvue.com — Test delivery · verified Oct 2026