PCAP Certified Associate in Python Programming Exam — Questions and Answers
Question 1: 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 2: When iterating over a file object line by line with 'for line in file:', what is included in each line?
- The line without any newline character
- The line number followed by the text
- The line with its trailing newline character (Correct answer)
- Only the stripped whitespace-free content
Correct answer: The line with its trailing newline character
When iterating a file, each yielded string includes the trailing newline '\n', which you must strip manually if not needed.
Question 3: In Python, what does `__del__` define?
- The logic for the `del` keyword on the class itself
- A method to remove an item from a list attribute
- A destructor called when the object is about to be garbage collected (Correct answer)
- A method to delete a class attribute
Correct answer: A destructor called when the object is about to be garbage collected
`__del__` is the finalizer, invoked just before the interpreter destroys the object, though its exact timing is not guaranteed.
Question 4: Which built-in function is used to rename a file in Python?
- file.rename()
- shutil.rename()
- os.move()
- os.rename() (Correct answer)
Correct answer: os.rename()
os.rename(src, dst) renames the file or directory from src to dst.
Question 5: What is the value of `int(3.9)`?
- 4
- 3.9
- 3 (Correct answer)
- ValueError
Correct answer: 3
`int()` truncates toward zero, so `int(3.9)` is `3`, not 4.
Question 6: In Python, which of the following is a mutable data type?
- tuple
- str
- int
- list (Correct answer)
Correct answer: list
Lists are mutable — their elements can be changed after creation; int, tuple, and str are immutable.
Question 7: What does os.walk() yield for each directory it visits?
- A tuple of (dirpath, dirnames, filenames) (Correct answer)
- A dict with 'root', 'dirs', and 'files' keys
- A single Path object
- A list of file paths only
Correct answer: A tuple of (dirpath, dirnames, filenames)
os.walk() yields a 3-tuple (dirpath, dirnames, filenames) for each directory in the tree rooted at the given path.
Question 8: Where does `pip install` place packages by default?
- In a `packages/` folder next to the script
- In the `site-packages` directory of the active Python environment (Correct answer)
- In `/usr/local/lib/`
- In the current working directory
Correct answer: In the `site-packages` directory of the active Python environment
`pip install` places packages in the `site-packages` directory of the currently active Python interpreter or virtual environment.
Question 9: In Python, what is a first-class function?
- A function decorated with @classmethod
- A function that can be passed as an argument, returned, or assigned to a variable (Correct answer)
- A function defined at module level
- A built-in function
Correct answer: A function that can be passed as an argument, returned, or assigned to a variable
First-class functions are treated like any other object — they can be stored in variables, passed to other functions, and returned from functions.
Question 10: What does `'hello'.upper()` return?
- 'hello'
- 'HELLO' (Correct answer)
- 'Hello'
- None
Correct answer: 'HELLO'
upper() returns a new string with all characters converted to uppercase.
Question 11: What is the difference between a regular package and a namespace package?
- A regular package can only be imported once; a namespace package can be reloaded
- 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 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 12: How many times does this loop print? ``` for _ in range(3): for _ in range(2): print('x') ```
- 6 (Correct answer)
- 3
- 2
- 5
Correct answer: 6
The inner loop prints 2 times per outer iteration, and the outer runs 3 times: 3×2 = 6.
Question 13: Which of the following is a mutable data type in Python?
- str
- tuple
- frozenset
- list (Correct answer)
Correct answer: list
Lists are mutable — their elements can be changed after creation, unlike tuples, strings, and frozensets.
Question 14: How do you check if a string starts with a specific prefix in Python?
- str.prefix('py')
- str.begins('py')
- str[:2] == 'py' only
- str.startswith('py') (Correct answer)
Correct answer: str.startswith('py')
startswith() returns True if the string begins with the specified prefix.
Question 15: What is the effect of running Python with the `-O` (optimize) flag on `assert` statements?
- They become no-ops that return True
- They raise OptimizeWarning instead
- They are completely removed and never execute (Correct answer)
- They run faster
Correct answer: They are completely removed and never execute
With `-O`, Python strips all `assert` statements from the bytecode, so they never execute regardless of the condition.
Question 16: What does open(file, buffering=0) mean?
- Use a 1-byte buffer
- Use the default buffer size
- Use an unlimited buffer
- Disable buffering (only valid in binary mode) (Correct answer)
Correct answer: Disable buffering (only valid in binary mode)
Setting buffering=0 disables buffering; this is only permitted in binary mode and causes each read/write to go directly to the OS.
Question 17: What is the purpose of `PYTHONPATH` environment variable?
- It specifies the location of the Python executable
- It sets the default encoding for Python source files
- It adds directories to `sys.path` at interpreter startup (Correct answer)
- It controls which version of Python pip uses
Correct answer: It adds directories to `sys.path` at interpreter startup
Directories listed in `PYTHONPATH` (colon-separated on Unix) are prepended to `sys.path` when the interpreter starts.
Question 18: What is an 'editable install' (`pip install -e .`)?
- An install that places the package in a temporary directory
- An install that skips compiling `.pyc` bytecode files
- An install where the package source directory is linked so code changes take effect immediately without reinstalling (Correct answer)
- An install that allows editing the package's metadata after installation
Correct answer: An install where the package source directory is linked so code changes take effect immediately without reinstalling
Editable installs (development mode) add the source directory to `sys.path` via a `.pth` file so changes to the source are reflected instantly.
Question 19: Which of the following creates a set comprehension?
- set(x*2 for x in range(5) using {})
- {x*2 for x in range(5)} (Correct answer)
- (x*2 for x in range(5))
- [x*2 for x in range(5)]
Correct answer: {x*2 for x in range(5)}
Curly braces with a single expression and no colon create a set comprehension.
Question 20: What does `enumerate(['a','b','c'])` produce?
- [0, 1, 2]
- ['a','b','c']
- [(0,'a'),(1,'b'),(2,'c')] (Correct answer)
- [('a',0),('b',1),('c',2)]
Correct answer: [(0,'a'),(1,'b'),(2,'c')]
enumerate() wraps an iterable and yields (index, value) tuples starting at 0 by default.
Question 21: What does `'hello world'.title()` return?
- 'Hello World' (Correct answer)
- 'HELLO WORLD'
- 'Hello world'
- 'hello world'
Correct answer: 'Hello World'
title() capitalizes the first letter of every word and lowercases the rest.
Question 22: What is the output of `len('hello world')`?
- 12
- 11 (Correct answer)
- 9
- 10
Correct answer: 11
The string 'hello world' has 5 + 1 space + 5 = 11 characters.
Question 23: What is the purpose of the errors parameter in open()?
- Controls whether OSError is raised on write failure
- Sets the maximum number of read errors allowed
- Enables logging of I/O errors to stderr
- Specifies how encoding/decoding errors are handled (Correct answer)
Correct answer: Specifies how encoding/decoding errors are handled
The errors parameter (e.g., 'ignore', 'replace', 'strict') defines what happens when a character cannot be encoded or decoded.
Question 24: A function is designed to process a dictionary. If a specific key is not found, the function should stop its normal execution and signal this specific problem to the caller. Which built-in exception is most appropriate to `raise` in this scenario?
- AttributeError
- KeyError (Correct answer)
- ValueError
- IndexError
Correct answer: KeyError
`KeyError` is the specific exception raised when a dictionary key is not found. `IndexError` relates to sequences like lists when an index is out of bounds. `ValueError` is for when an argument has the right type but an inappropriate value. `AttributeError` occurs when an attribute reference or assignment fails.
Question 25: Which symbol is used in Python's decorator syntax?
- #
- $
- &
- @ (Correct answer)
Correct answer: @
The @ symbol placed before a function definition applies the decorator to that function.
Question 26: What is the output of the following Python code snippet? ```python temperature = 25 if temperature > 30: print("Hot") elif temperature > 20: print("Warm") else: print("Cold") ```
- No output will be generated.
- Cold
- Warm (Correct answer)
- Hot
Correct answer: Warm
The code first checks if `temperature` (25) is greater than 30, which is false. It then proceeds to the `elif` condition, checking if 25 is greater than 20. This is true, so it prints "Warm" and exits the conditional block. The `else` block is never reached.
Question 27: Which module provides `contextmanager` decorator for creating context managers that handle exceptions?
- functools
- exceptions
- contextlib (Correct answer)
- builtins
Correct answer: contextlib
`contextlib.contextmanager` lets you write a generator-based context manager where code before `yield` is setup and code after `yield` (with try/except) handles teardown and exceptions.
Question 28: What does `pkgutil.iter_modules()` return?
- A generator of module source code strings
- A dict of module names to file paths
- An iterator of `(finder, name, ispkg)` tuples for modules in given paths (Correct answer)
- A list of all installed package names
Correct answer: An iterator of `(finder, name, ispkg)` tuples for modules in given paths
`pkgutil.iter_modules(path)` yields named tuples describing each module or subpackage found in the given list of directories.
Question 29: Which statement about Python indentation is correct?
- Indentation is optional but recommended
- Indentation must use exactly 4 spaces
- Indentation defines code blocks and is syntactically required (Correct answer)
- Indentation is only required inside classes
Correct answer: Indentation defines code blocks and is syntactically required
Python uses indentation to delimit code blocks; incorrect or inconsistent indentation causes an `IndentationError`.
Question 30: In a context manager using `__exit__`, what should the method return to suppress an exception?
- True (Correct answer)
- False
- 0
- None
Correct answer: True
Returning `True` from `__exit__` tells Python to suppress the exception; any falsy return value lets the exception propagate.
Question 31: Which statement about `nonlocal` is correct?
- It is only available in Python 2
- It allows a nested function to assign to an enclosing (non-global) variable (Correct answer)
- It allows access to global variables
- It creates a new variable in the built-in scope
Correct answer: It allows a nested function to assign to an enclosing (non-global) variable
`nonlocal` lets an inner function rebind a variable in the nearest enclosing scope that is not the global scope.
Question 32: What does `'hello'.center(11, '*')` return?
- '**hello***'
- '***hello***' (Correct answer)
- '*****hello'
- 'hello*****'
Correct answer: '***hello***'
center() pads the string to the specified total width by placing fill characters equally on both sides.
Question 33: Consider the following code. What will be the final output printed to the console? ```python def check_value(): try: print("Start") raise ValueError print("After Raise") except ValueError: print("Caught") return "From Except" finally: print("Cleanup") print("End") print(check_value()) ```
- Start Caught Cleanup End From Except
- Start After Raise End None
- Start Caught Cleanup From Except (Correct answer)
- Start Caught From Except Cleanup
Correct answer: Start Caught Cleanup From Except
The `try` block starts and prints "Start". A `ValueError` is immediately raised, so "After Raise" is skipped. The `except ValueError` block is executed, printing "Caught". It then prepares to return "From Except". However, the `finally` block must execute before the function officially returns, so "Cleanup" is printed. After the `finally` block completes, the function returns the value from the `except` block, which is then printed. "End" is never reached because the return statement exits the function.
Question 34: Which of the following is a positional-only parameter syntax introduced in Python 3.8?
- def f(x, *, y):
- def f(@x, y):
- def f(x!, y):
- def f(x, /, y): (Correct answer)
Correct answer: def f(x, /, y):
The `/` separator in a parameter list marks all parameters before it as positional-only — they cannot be passed by keyword.
Question 35: What is PYTHONCASEOK, and how does it work?
- It is used to find the first case-insensitive match in a package statement
- It is used to find the first case-sensitive match in an import statement
- It is used to find the first case-insensitive match in an import statement (Correct answer)
- None of these
Correct answer: It is used to find the first case-insensitive match in an import statement
PYTHONCASEOK is an environment variable that influences how Python handles module imports on case-insensitive file systems, like Windows. When set, Python will attempt to find a module even if its filename's casing doesn't exactly match the import statement. It allows for a case-insensitive search for the module file, importing the first match it finds.
Question 36: What is printed? val = '' if val: print('has value') elif val is None: print('is None') else: print('empty')
- Error
- has value
- empty (Correct answer)
- is None
Correct answer: empty
An empty string is falsy but not None, so neither the if nor the elif match, and 'empty' is printed.
Question 37: Which f-string expression correctly formats a float to 2 decimal places?
- f'{value|2f}'
- f'{value:.2f}' (Correct answer)
- f'{value:2f}'
- f'{value:.2}'
Correct answer: f'{value:.2f}'
The format spec :.2f means fixed-point notation with 2 digits after the decimal.
Question 38: Which attribute stores the exception that caused another exception when using implicit exception chaining?
- __context__ (Correct answer)
- __reason__
- __cause__
- __traceback__
Correct answer: __context__
`__context__` is set automatically when an exception is raised while another exception is already being handled (implicit chaining).
Question 39: Which method checks if all characters in a string are digits?
- isdigit() (Correct answer)
- isinteger()
- isnumeric()
- isnum()
Correct answer: isdigit()
isdigit() returns True if every character in the string is a decimal digit (0–9).
Question 40: What does `yield from` do in a generator function?
- Creates a new generator function
- Delegates to a sub-generator, yielding all its values (Correct answer)
- Raises StopIteration immediately
- Returns all values at once as a list
Correct answer: Delegates to a sub-generator, yielding all its values
yield from sub_gen delegates to a sub-generator, yielding each of its values as if they were in the outer generator.
Question 41: Which of the following is an invalid variable name in Python?
- MYVAR
- myVar2
- 2myVar (Correct answer)
- _my_var
Correct answer: 2myVar
Python variable names must start with a letter (a-z, A-Z) or an underscore (_). They cannot begin with a digit. Therefore, '2myVar' is an invalid variable name. '_my_var', 'myVar2', and 'MYVAR' are all valid.
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