PCAP Certified Associate in Python Programming Exam — Questions and Answers
Question 1: What is encapsulation in object-oriented programming?
- Using multiple classes at once
- Bundling data and methods within a class (Correct answer)
- Overriding parent methods
- 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 2: Which encoding is the default for text files opened with `open()` in Python 3?
- UTF-16
- Latin-1
- UTF-8 on most systems (locale-dependent) (Correct answer)
- ASCII
Correct answer: UTF-8 on most systems (locale-dependent)
Python 3 uses the platform's default encoding (typically UTF-8) unless explicitly specified.
Question 3: Which method would you use to combine two dictionaries in Python 3.9 or later?
- dict1 + dict2
- dict1.update(dict2)
- dict1.merge(dict2)
- dict1 | dict2 (Correct answer)
Correct answer: dict1 | dict2
The | operator is used to merge two dictionaries in Python 3.9 and later.
Question 4: What is polymorphism in Python?
- A class with many attributes
- A method with default parameters
- Using multiple inheritance
- Multiple classes responding to the same interface (Correct answer)
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 5: Which dunder method allows an object to be represented as a string when printed?
- Both __str__ and __repr__
- __str__ (Correct answer)
- __print__
- __repr__
Correct answer: __str__
`__str__` is called by `print()` and `str()` to return a human-readable string representation.
Question 6: Which attribute stores the name of a class in Python?
- __class__.__name__ (Correct answer)
- __name__
- __type__
- __classname__
Correct answer: __class__.__name__
`__class__.__name__` returns the name of the class of an object as a string.
Question 7: Which built-in function applies a function to every item in an iterable?
- apply()
- filter()
- map() (Correct answer)
- each()
Correct answer: map()
`map()` applies a function to each element of an iterable and returns a map object.
Question 8: What does `str.strip()` do?
- Converts to lowercase
- Reverses the string
- Removes leading and trailing whitespace (Correct answer)
- Splits the string
Correct answer: Removes leading and trailing whitespace
`strip()` removes whitespace (or specified characters) from both ends of the string.
Question 9: Which attribute of a function object holds the variables captured by its closure?
- __globals__
- __dict__
- __closure__ (Correct answer)
- __captured__
Correct answer: __closure__
`func.__closure__` is a tuple of cell objects, each holding the value of one variable captured from the enclosing scope.
Question 10: How do you create a custom exception class in Python?
- Use the @exception decorator
- Inherit from Exception (Correct answer)
- Inherit from object
- Inherit from BaseError
Correct answer: Inherit from Exception
Custom exceptions are created by subclassing `Exception` or one of its subclasses.
Question 11: What is the correct syntax to create a tuple in Python?
- tuple = {1, 2, 3}
- tuple = (1, 2, 3) (Correct answer)
- tuple = [1, 2, 3]
- tuple = <1, 2, 3>
Correct answer: tuple = (1, 2, 3)
Tuples in Python are created using parentheses.
Question 12: Which string method converts all characters to uppercase?
- capitalize()
- upper() (Correct answer)
- title()
- swapcase()
Correct answer: upper()
`str.upper()` returns a new string with all characters converted to uppercase.
Question 13: What mode string opens a file for writing, creating it if it does not exist and truncating if it does?
- 'a'
- 'r'
- 'x'
- 'w' (Correct answer)
Correct answer: 'w'
Mode `'w'` opens a file for writing, creating it if absent and clearing it if it exists.
Question 14: Which exception is raised when a variable is used before it is assigned?
- ReferenceError
- NameError (Correct answer)
- AttributeError
- SyntaxError
Correct answer: NameError
`NameError` is raised when a local or global name is not found.
Question 15: What is the base class for all built-in exceptions in Python?
- Error
- Exception
- BaseException (Correct answer)
- RuntimeError
Correct answer: BaseException
`BaseException` is the root of the Python exception hierarchy; `Exception` is its subclass for non-system-exiting exceptions.
Question 16: What does `except Exception as e:` allow you to do?
- Access the exception object via the variable `e` (Correct answer)
- Suppress all exceptions
- Skip the except block
- Re-raise the exception
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 17: What does `except (TypeError, ValueError):` do?
- Catches only TypeError
- Catches only ValueError
- Catches either TypeError or ValueError (Correct answer)
- Raises both exceptions
Correct answer: Catches either TypeError or ValueError
A tuple of exception types in an except clause catches any of those exception types.
Question 18: What does the following code print?
- 123
- 1234
- 12 (Correct answer)
- 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 19: Which keyword is used in a generator function to produce a value?
- emit
- send
- yield (Correct answer)
- return
Correct answer: yield
`yield` suspends the function and sends a value to the caller, resuming on the next iteration.
Question 20: What is the difference between a `return` and `yield` in a function?
- `yield` exits the function; `return` pauses it
- `return` exits the function; `yield` pauses and resumes it (Correct answer)
- `yield` raises StopIteration
- 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 21: How do you define a class variable (shared by all instances) in Python?
- Declare it inside __init__ using self
- Use the shared keyword
- Use the global keyword
- Declare it outside any method, inside the class body (Correct answer)
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 22: Which of the following correctly defines a subclass `Dog` inheriting from `Animal`?
- class Dog(Animal): (Correct answer)
- class Dog: Animal
- class Dog extends 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 23: Which of the following is a valid variable name in Python?
- variable-name
- variable_ name (Correct answer)
- variable name
- 2ndVariable
Correct answer: variable_ name
Variable names in Python must start with a letter or underscore and cannot contain spaces or hyphens.
Question 24: 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())
- 1 1 1
- 0 1 2
- 1 2 3 (Correct answer)
- NameError: name 'count' is not defined
Correct answer: 1 2 3
Each call to `c()` increments the shared `count` variable via `nonlocal`, producing 1, 2, then 3.
Question 25: What does `itertools.chain([1,2], [3,4])` produce?
- A zip of the two lists
- An iterator yielding 1,2,3,4 (Correct answer)
- A combined sorted list
- [[1,2],[3,4]]
Correct answer: An iterator yielding 1,2,3,4
`itertools.chain()` creates a single iterator that yields elements from multiple iterables in sequence.
Question 26: Which built-in function converts a string to an integer?
- to_int()
- int() (Correct answer)
- integer()
- parse()
Correct answer: int()
`int()` converts a string or number to an integer, raising `ValueError` for invalid input.
Question 27: What will the following code print? def outer(): x = 10 def inner(): print(x) x = 20 return inner f = outer() f()
- NameError: name 'x' is not defined
- None
- 20 (Correct answer)
- 10
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 28: How do you create an instance of a class named `Car`?
- instance(Car)
- Car() (Correct answer)
- new Car()
- Car.new()
Correct answer: Car()
You instantiate a class by calling it like a function: `Car()`.
Question 29: What is the result of using `@staticmethod` decorator on a method?
- The method becomes private
- The method is called automatically
- The method has access to the class via cls
- The method has no access to instance or class (Correct answer)
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 30: What does `**kwargs` allow in a function definition?
- Variable positional arguments
- Forced keyword-only arguments
- Default arguments
- Variable keyword arguments as a dictionary (Correct answer)
Correct answer: Variable keyword arguments as a dictionary
`**kwargs` collects extra keyword arguments into a dictionary inside the function.
Question 31: Which method reads the entire file content as a single string?
- readline()
- fetch()
- read() (Correct answer)
- readlines()
Correct answer: read()
`file.read()` reads the entire file and returns it as a single string.
Question 32: How do you import only the `sqrt` function from the `math` module?
- from math import sqrt (Correct answer)
- import sqrt from math
- include math.sqrt
- import math.sqrt
Correct answer: from math import sqrt
The `from module import name` syntax imports a specific name from a module.
Question 33: Which of the following is the most common practical use case for closures in Python?
- Factory functions that return specialized functions with pre-configured parameters (Correct answer)
- Replacing class-based inheritance hierarchies entirely
- 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 34: Which file mode opens a file for appending without truncating existing content?
- 'w'
- 'x'
- 'r+'
- 'a' (Correct answer)
Correct answer: 'a'
Mode `'a'` opens a file for appending; writes go to the end without erasing existing data.
Question 35: Which built-in function is used to open a file in Python?
- read()
- load()
- open() (Correct answer)
- file()
Correct answer: open()
The `open()` function opens a file and returns a file object for reading or writing.
Question 36: How do you start a comment in Python?
- /*
- A) //
- --
- B) # (Correct answer)
Correct answer: B) #
In Python, comments are started with the # symbol.
Question 37: What is the MRO (Method Resolution Order) used for in Python?
- Prioritizing static methods
- Ordering class attributes alphabetically
- Determining the order methods are inherited in multiple inheritance (Correct answer)
- Sorting methods by definition order
Correct answer: Determining the order methods are inherited in multiple inheritance
MRO determines the order in which Python searches parent classes for a method in multiple inheritance.
Question 38: Which of the following is true about tuples?
- They can have duplicate elements
- Both B and C (Correct answer)
- They are immutable
- They are mutable
Correct answer: Both B and C
Tuples are immutable and can have duplicate elements.
Question 39: Which block always executes regardless of whether an exception occurred?
- finally (Correct answer)
- try
- else
- except
Correct answer: finally
The `finally` block always runs whether or not an exception was raised, used for cleanup.
Question 40: What does `math.floor(3.9)` return?
- 4.0
- 4
- 3.9
- 3 (Correct answer)
Correct answer: 3
`math.floor()` returns the largest integer less than or equal to the given number.
Question 41: 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.
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
Practice questions written with AI assistance and published by Nathan Beja, founder of Practice Test Geeks. They are not real exam questions. Exam facts are checked against the official sources linked below. 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 — Time limit, exam information · verified Dec 2026