Python Institute · Free Practice Questions · Last reviewed May 2026
24real exam-style questions organised by domain, each with the correct answer highlighted and a plain-English explanation of why it's right — and why the others are wrong.
A developer is working on a project that requires the use of a third-party package hosted on a private repository. The developer wants to ensure that the package can be imported without specifying the full repository URL each time. Which approach should be taken?
Append the repository path to sys.path in the script.
Place the package files in the site-packages directory manually.
Configure the repository URL in pip's configuration file or in requirements.txt.
pip configuration allows specifying extra index URLs for package resolution.
Use os.system to run a pip install command from within the script.
A Python script imports the module 'my_module'. The developer wants to ensure that when the script is run directly, it executes a specific function, but when imported as a module, that function is not executed. Which code snippet achieves this?
if __name__ == '__main__': run()
if __name__ == '__main__': run()
This is the standard Python idiom for executable scripts.
if os.environ.get('RUN_MAIN'): run()
if sys.argv[0] == 'my_module': run()
A developer creates a package named 'analytics' with the following structure:
analytics/ __init__.py stats.py models/ __init__.py regression.py
The developer wants the statement 'from analytics import *' to import only the functions 'mean' and 'std' from stats.py. What should be added to analytics/__init__.py?
Nothing; by default, all names are exported.
from analytics.stats import *
__all__ = ['stats.mean', 'stats.std']
__all__ = ['mean', 'std']
This defines the public API of the package.
A developer is troubleshooting an ImportError: 'No module named 'config''. The config module is located in a subdirectory 'utils' relative to the script. The script's current working directory is the parent of 'utils'. Which of the following lines, added to the script, will resolve the issue?
sys.path.append('utils/config.py')
sys.path.append('utils')
This adds the utils directory to the module search path.
sys.path = os.path.join(sys.path, 'utils')
os.chdir('utils')
A developer wants to import a specific function 'calculate' from a module named 'formulas' without importing the entire module. Which import statement should be used?
import formulas
import calculate from formulas
from formulas import calculate
This imports only the specified function.
import formulas as f
A developer notices that a custom package 'mypackage' is not being found when importing, even though it is installed in the site-packages directory. The developer suspects a conflict with another package of the same name. Which command should the developer run to diagnose the location from which Python is importing the package?
print(mypackage)
print(__file__)
print(mypackage.__file__)
This attribute contains the path to the module's file.
import os; print(os.getcwd())
Want more Modules and Packages practice?
Practice this domainA developer needs to count the number of occurrences of the substring 'is' in the string 'This is a test. Is this a test?'. Which code correctly performs the count?
'This is a test. Is this a test?'.split().count('is')
'This is a test. Is this a test?'.count('is')
Correctly counts overlapping? No, count does not count overlapping, but 'is' appears at positions 5 and 17, not overlapping, so returns 2.
'This is a test. Is this a test?'.index('is')
'This is a test. Is this a test?'.find('is')
A programmer writes a function to check if a string is a palindrome (ignoring case and non-alphanumeric characters). Which implementation correctly achieves this?
def is_pal(s): s = s.lower(); return s == ''.join(reversed(s))
def is_pal(s): s = ''.join(c for c in s if c.isalnum()).lower(); return s == s[::-1]
Correctly filters alphanumeric, lowercases, and compares reverse.
def is_pal(s): return s == s[::-1]
def is_pal(s): s = s.lower(); return s == s[::-1]
A log analysis script needs to extract all IP addresses from a string. The IPs are in dotted-decimal format. Which regex pattern will correctly extract them?
r'[0-9]+\. [0-9]+\.[0-9]+\.[0-9]+'
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}'
Matches three groups of 1-3 digits followed by dot, then one more group. Does not validate range beyond 999, but typical for IP extraction.
r'\d+\.\d+\.\d+\.\d+'
Which string method can be used to check if a string contains only digits?
str.isdigit()
Returns True if all characters are digits (0-9).
str.isalnum()
str.isdecimal()
str.isnumeric()
A developer needs to replace all occurrences of 'cat' with 'dog' in a string, but only if 'cat' is a whole word (not part of 'category'). Which code achieves this?
re.sub(r'\bcat\b', 'dog', s)
Word boundaries ensure whole word match.
s.replace('cat', 'dog')
re.sub('cat', 'dog', s)
s.replace('cat', 'dog', 1)
Given the string s = 'Hello World!', which expression returns a list of characters?
s.split('')
list(s)
Converts string to list of characters.
s.split()
s.split(' ')
Want more Strings practice?
Practice this domainA developer creates a Python class with a method that is intended to be overridden in subclasses. Which approach best ensures that the method is not accidentally called on the base class?
Use 'pass' as the method body
Delete the method from the base class using 'del'
Add a comment '# override in subclass' inside the method body
Raise NotImplementedError inside the method body
Raising NotImplementedError clearly signals the method must be overridden.
A developer wants to ensure that a class attribute is shared among all instances but cannot be modified from outside the class. Which approach is most appropriate?
Use a property decorator on a class method
Define a public class attribute and document it as read-only
Define an instance attribute inside __init__
Define a private class attribute (e.g., __shared) and provide a class method to access it
Name mangling discourages direct access; getter method controls read-only access.
A Python class 'BankAccount' has a method 'withdraw(amount)' that deducts 'amount' from 'self.balance'. A developer writes a subclass 'SavingsAccount' that overrides 'withdraw' to add a penalty if balance drops below minimum. Which design pattern is being used?
Composition
Aggregation
Method overriding
The subclass provides a specific implementation of the inherited method.
Inheritance
A team is developing a system that must handle different types of documents (PDF, Word, etc.). Each document type has a unique parsing method. To avoid massive conditional logic, which OOP concept should be applied?
Polymorphism
Polymorphism enables each subclass to provide its own implementation of a common interface.
Encapsulation
Inheritance
Abstraction
A developer writes a class 'Logger' with a class method 'log(msg)' that writes to a file. Another class 'AppLogger' inherits from 'Logger'. The developer expects both classes to share the same file handle. However, after creating an instance of 'AppLogger', the file handle is different. What is the most likely cause?
The 'log' method is defined as a class method using @classmethod
The file handle is opened in the __init__ method of the base class
Opening in __init__ creates a new handle per instance, not shared.
The file handle is stored as a private attribute __file
The subclass overrides the 'log' method
A class 'MyClass' has a method 'do_something' that uses 'self.__private'. A subclass 'MySubClass' tries to access 'self.__private' and gets an AttributeError. Why?
Because the attribute is defined as a class attribute, not instance attribute
Because the subclass overrides the method that uses the attribute
Because name mangling renames the attribute to _MyClass__private, and the subclass implicitly accesses _MySubClass__private
Each class gets its own name-mangled version.
Because the attribute is private and not inherited
Want more Object-Oriented Programming practice?
Practice this domainA developer writes a function that reads a configuration file and returns its contents as a string. The file might not exist. Which exception should be caught to handle a missing file?
FileNotFoundError
FileNotFoundError is specifically for missing files.
PermissionError
IOError
OSError
A Python script processes a log file line by line. If a line cannot be decoded due to an encoding error, the script should skip the line and continue. Which exception handling approach is best?
Wrap the entire file reading in a try-except block without specifying exception type.
Use a try-except-else block to handle success and failure separately, exiting on failure.
Inside the loop, wrap the line decoding in a try-except UnicodeDecodeError block and continue.
This isolates decoding issues and continues processing.
Catch Exception in the outer loop and break on error.
A developer implements a custom exception class `DataError` that inherits from `Exception`. Which method override is essential to ensure the exception message is properly displayed when caught?
Override __init__ to accept a message and call super().__init__(message).
This ensures the message is stored and displayed.
Set the __cause__ attribute in __init__.
Override __str__ to return a formatted string.
Override __repr__ to return a detailed representation.
Which of the following is the correct way to open a file for writing in text mode, ensuring that if the file already exists it will be overwritten?
open('file.txt', 'x')
open('file.txt', 'w')
'w' mode overwrites existing content.
open('file.txt', 'r+')
open('file.txt', 'a')
A script uses `with open('data.bin', 'rb') as f:` to read binary data. Within the block, which method should be used to read exactly 4 bytes?
f.read(4)
Reads up to 4 bytes.
f.seek(4)
f.readline()
f.read()
Consider the following code snippet:
try:
x = int(input()) y = 10 / x
print(y)
except ZeroDivisionError:
print('Division by zero')except ValueError:
print('Invalid integer')If the user enters '0', what is the output?
No output
Both 'Invalid integer' and 'Division by zero'
Division by zero
ZeroDivisionError is raised and caught.
Invalid integer
Want more Exceptions and File I/O practice?
Practice this domainThe PCAP exam has 40 questions and must be completed in 65 minutes. The passing score is 700/1000.
Scenario-based questions covering exam objectives with detailed answer explanations.
The exam covers 4 domains: Modules and Packages, Strings, Object-Oriented Programming, Exceptions and File I/O. Questions are weighted by domain — higher-weight domains appear more on your actual exam.
No. These are original exam-style practice questions written against the official Python Institute PCAP exam objectives. They are not copied from the real exam. Courseiva focuses on genuine understanding, not memorisation of braindumps.
Courseiva tracks your accuracy per domain and routes you toward weak areas automatically. Free, no account required.