Courseiva

PCAP · domain

scenario questions

Practise Certified Associate Python Programmer PCAP scenario questions practice questions — original exam-style scenarios with answer choices, explanations, and analysis of common mistakes.

169 questions32 easy67 medium70 hard

Focused practice

Practice scenario questions questions

Scored sessions drawing only from this domain — pick a length below.

Start 20-question practice test →

What this domain covers

What to know about scenario questions

scenario questions questions test whether you can apply the concept in context, not just recognise a definition.

How the topic appears in realistic exam-style scenarios.

Which detail in the question changes the correct answer.

How to eliminate plausible but wrong options.

How to connect the question back to the wider exam objective.

Watch out for

Common scenario questions exam traps

  • Answering from memory before reading the full scenario.
  • Missing a constraint such as cost, availability, security, scope or command context.
  • Choosing a broad answer when the question asks for the most specific fix.
  • Ignoring why the wrong options are tempting.

Question index

All scenario questions questions (169)

Click any question to see the full explanation, or start a practice session above.

1

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?

Hard
2

Refer to the exhibit. What happens when the code is executed?

Medium
3

A QA engineer needs to verify that a user input string contains at least one uppercase letter, one lowercase letter, and one digit. Which regex pattern can be used with re.search() to achieve this?

Hard
4

A junior developer writes a class 'Logger' that should only ever have one instance (singleton). They attempt to implement it by overriding __new__ to always return the same instance. However, when multiple threads attempt to create a Logger, they sometimes get different instances. Which modification will make the singleton thread-safe?

Easy
5

Which THREE of the following are immutable types in Python?

Medium
6

Refer to the exhibit. What is the output? (Note: actual MRO may vary; choose the one that matches Python 3 C3 linearization.)

Hard
7

Drag and drop the steps to handle an exception in Python using try-except-finally into the correct order.

Medium
8

Refer to the exhibit. What is the output of the code?

Medium
9

A programmer writes a class with a method that should be called on the class itself, not on instances. Which decorator is appropriate?

Easy
10

A team is developing a large application and wants to organize code into packages. Which of the following is a best practice for package design?

Medium
11

Which THREE of the following are valid ways to create a string in Python?

Hard
12

A Python script fails with 'ModuleNotFoundError: No module named 'myapp.config''. The environment variable PYTHONPATH is not set. Which of the following is the most likely cause?

Medium
13

You are a DevOps engineer managing a Python application that consists of multiple microservices. One microservice, 'data_processor', imports a shared library 'common_lib' which is also used by other microservices. The shared library is developed in a separate repository and is installed via pip in each microservice's virtual environment as an editable package (pip install -e). Recently, you updated 'common_lib' with new functions, but when you redeploy 'data_processor' (by restarting the container), the new functions are not available; the old version is still used. The container uses a Docker image built from a requirements file that specifies 'common_lib' from a Git repository. You verify that the Git commit hash in the requirements file points to the latest version. What is the most likely cause and what is the correct course of action?

Hard
14

A log processing script receives a multiline string log. The script needs to check if the string ends with the substring 'ERROR'. Which method should be used?

Medium
15

Which THREE of the following statements about Python's module search path are true?

Hard
16

Match each Python data structure to its mutability.

Medium
17

You are a developer at a company that processes customer feedback. Each feedback entry is stored as a string containing a rating (1-5) followed by a colon and then the comment. For example: '4: Great service'. You need to extract only the comments from feedback that have a rating of 4 or 5. You have a list of feedback strings. Which code snippet correctly implements this?

Hard
18

A data pipeline processes CSV lines that may contain quoted fields with commas inside double quotes. For example: 'John, "Doe, Jr.", 35'. The team needs to split such a line correctly. Which approach is best?

Hard
19

What is the output of the following code? try: exec('1/0') except: print('error') else: print('no error') finally: print('done')

Hard
20

Which of the following is the BEST practice for building a large string by concatenating many smaller strings in Python?

Easy
21

Refer to the exhibit. What is printed?

Hard
22

Refer to the exhibit. Which of the following fixes the error?

Medium
23

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?

Hard
24

A developer has a module 'config.py' with the following content: # config.py import os DATABASE_URL = os.getenv('DATABASE_URL', 'localhost') Another module 'app.py' imports config and uses DATABASE_URL. During testing, the environment variable is set correctly, but the import still uses the default value 'localhost'. What is the most likely reason?

Medium
25

A data analyst is cleaning a CSV file. They have a string variable containing a row of data: 'John,Doe,30,New York'. They need to extract the last name 'Doe' using string methods. The analyst writes: name = row.split(',')[1]. However, they are concerned about performance because the file contains millions of rows. They want to use a more efficient method that extracts the substring without creating a full list. Which approach should the analyst use?

Medium
26

Given that MyClass defines __private_attr in __init__, why does this error occur?

Medium
27

Which TWO of the following are valid ways to import a function 'foo' from a module 'bar' that is located in a package 'mypackage'?

Medium
28

A developer writes code to display a floating-point number with exactly two decimal places. Which f-string expression is correct for value = 3.14159?

Medium
29

You are a developer for a data science team. The team uses a shared module 'utilities' located at /team/shared/utilities.py. This module is not part of any package, and they want to import it from various project scripts without copying the file. Some projects are in /home/user/proj_A/ and others in /var/data/proj_B/. Currently, each script manually adds /team/shared/ to sys.path using sys.path.insert(0, '/team/shared/'). This works but is repetitive. The team wants a cleaner solution that also works when the script is run from different working directories. They consider creating a package 'utilities' by adding an __init__.py to the directory and using relative imports. However, the module currently uses absolute imports for some external libraries. What is the best course of action to allow clean imports of utilities from any location while minimizing changes to the module itself?

Hard
30

A function receives a file path like '/home/user/docs/file.txt' and needs to return the path without the file extension, e.g., '/home/user/docs/file'. Which code reliably removes only the last dot extension, even if the directory names contain dots?

Easy
31

You are developing a high-performance logging module that must handle thousands of log entries per second. Each entry is built by concatenating a timestamp, level, and message. Currently, your code uses a loop that repeatedly appends to a string using the += operator. This results in high memory usage and sluggish performance because each concatenation creates a new string object. The module must run on systems with limited memory and cannot rely on external libraries. Which course of action would best resolve the performance issue while maintaining readability and standard library compliance?

Hard
32

Which TWO statements about the 'from package import *' statement are correct?

Easy
33

Refer to the exhibit. A developer is writing a script to read this JSON configuration file. The script should write the logging configuration to a separate file called 'logging.conf'. Which file mode should be used to create the file if it doesn't exist, and overwrite it if it does?

Medium
34

Refer to the exhibit. What is printed?

Medium
35

A Python script reads a file containing text with non-ASCII characters like 'é' and 'ü'. The script must encode the string as UTF-8 then decode it back. Which of the following correctly handles this without error?

Hard
36

A developer creates classes `A`, `B(A)`, `C(A)`, and `D(B, C)`. When calling a method from `D` that is defined in `A`, which class's version is used according to Python's MRO?

Medium
37

A user wants to ensure that a custom module 'mymod' located at '/home/user/custom' takes precedence over a standard library module with the same name. Which operation on sys.path should be performed?

Hard
38

A team is using f-strings to format a report. They have a variable `value = 0.123456789` and want to display it with exactly 3 significant digits. They write `f"{value:.3g}"`. The output is '0.123'. They expected '0.123'. Is the output correct? If not, what change would produce '0.123'?

Hard
39

A network engineer processes a configuration file containing MAC addresses in the format 'aa:bb:cc:dd:ee:ff'. They need to convert each MAC address into a 6-byte bytes object for use in packet crafting. The current code is: mac_bytes = bytes([int(x, 16) for x in mac_str.split(':')]). This works correctly, but they need to process thousands of MAC addresses and want to optimize performance. They also need to handle invalid MAC addresses (e.g., non-hex characters) without crashing. Which of the following approaches is the most efficient and robust?

Medium
40

A developer generates a report where numbers must be right-aligned in a 10-character column using f-strings: f'{value:>10}'. However, some values may be None, causing a TypeError. Which is the most robust way to handle None values without affecting other falsy values like 0?

Medium
41

Which of the following statements about the `finally` block is true?

Easy
42

A developer wants to create a class that logs every attribute access on an instance. Which special method should they override?

Easy
43

A class defines an __init__ method that takes optional arguments. What is the correct way to provide default values?

Easy
44

Which THREE factors influence Python's module search path (sys.path)?

Hard
45

Which of the following is a correct use of the @property decorator to create a getter and setter for an attribute named 'score' that ensures score stays between 0 and 100?

Hard
46

A class has both `@classmethod` and `@staticmethod` decorators. What is a key difference between them?

Medium
47

A senior developer in a team argues that using try-except blocks is slower than checking conditions with if statements. They propose replacing all try blocks that handle file I/O errors with existence checks using os.path.exists before opening files. During a code review, you recall that Python's official documentation and best practices prefer EAFP (Easier to Ask for Forgiveness than Permission) over LBYL (Look Before You Leap) in many cases, especially in concurrent environments. The team's application is a multi-threaded web server that serves static files from a shared directory. Which is the strongest counterargument against the senior developer's proposal?

Hard
48

What is the result of 'abcdef'[::-2]?

Hard
49

A Python script uses a third-party library 'requests'. The developer wants to ensure that the exact version 2.25.1 is installed in the project's environment. Which tool and command should be used?

Easy
50

During development, a programmer modifies a module that is already imported in the current Python session. To see the changes without restarting the interpreter, which function from the importlib module should be called?

Medium
51

Which of the following correctly uses `__slots__` to restrict attribute creation to only `x` and `y`?

Hard
52

A developer wants to convert a string 'Python' to all uppercase letters. Which string method should be used?

Easy
53

A team is using a shared Python environment where multiple projects have conflicting dependencies. Which approach is the best practice to isolate project dependencies?

Easy
54

A cloud infrastructure engineer is developing a Python script to parse large configuration files from a fleet of servers. Each file can be up to 500 MB. The script reads the file line by line using a file object, strips comment lines (those starting with '#'), and accumulates only the configuration directives into a single string for further processing. The current code is: ```python result = '' with open('config.cfg') as f: for line in f: if not line.startswith('#'): result += line.strip() ``` After processing just a few hundred lines of a large file, the script becomes extremely slow and consumes an excessive amount of memory. The engineer identifies that string concatenation using `+=` is inefficient because strings are immutable, causing repeated memory reallocation. Which approach should the engineer implement to resolve the performance issue without changing the final output?

Hard
55

A developer writes a script to read a configuration file that may not exist. The script should handle the error gracefully and continue. Which approach is most Pythonic?

Easy
56

You are developing a package 'analytics' that contains subpackages 'stats' and 'ml'. The __init__.py of 'analytics' imports a function 'normalize' from 'analytics.stats'. When a user runs `import analytics`, they get an ImportError. Which change ensures the package imports correctly?

Medium
57

A team is developing a data processing pipeline where each step is a class that implements a common interface. They have defined an abstract base class DataProcessor with an abstract method process(data). Several concrete subclasses implement process. Now they need to add a new step that logs the data before processing. They want to reuse the existing processing logic without modifying the original classes. Which design pattern should they apply?

Medium
58

A developer defines a class with an __init__ method that sets instance attributes. Which of the following is the correct way to call the parent class's __init__ from a child class?

Easy
59

Consider the code fragment: f = open('data.txt', 'r') data = f.read() process_data(data) f.close() What is the primary risk if an exception occurs during process_data(data)?

Hard
60

Which three statements about the Method Resolution Order (MRO) in Python are true? (Choose three.)

Medium
61

Refer to the exhibit. What is the output when this code is executed?

Medium
62

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?

Hard
63

In Python, if you have a try block followed by an except clause that catches all exceptions, which of the following is true about the else clause?

Easy
64

A developer creates a package named 'mypkg' with an __init__.py file. Inside the package, there is a module 'utils.py'. Which of the following is the correct way to import the function 'helper' from 'utils' from outside the package?

Easy
65

A programmer uses a class method to create an alternative constructor for a `Point` class. The method should parse a string like "10,20" and return a `Point` instance with x=10, y=20. Which code snippet correctly implements this?

Medium
66

Match each exception to its cause.

Medium
67

A developer needs to parse a log file where each line contains a timestamp followed by a message. The timestamp format is 'YYYY-MM-DD HH:MM:SS'. Which string method is most appropriate to split the timestamp from the message?

Medium
68

A 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?

Easy
69

Refer to the exhibit. Which statement about the output is true?

Hard
70

A developer wants a class 'LoggedDict' that behaves like a dict but logs all attribute access in the console. Which method override correctly implements this for getting an attribute?

Hard
71

A developer needs to combine a list of 10,000 strings into a single string. Which approach is most efficient in terms of memory and performance?

Medium
72

You are working on a legacy system that processes financial transactions. The system uses a class hierarchy: Transaction (base), Deposit, Withdrawal, Transfer. Each subclass overrides a method 'process()' to handle its specific logic. The code often runs in a multi-threaded environment and you notice intermittent errors where a transaction is processed twice. The logging shows that the same transaction object is being passed to the process method multiple times. The transaction objects are created from a factory function that caches recently used transactions. The errors seem to occur when two threads call the factory at the same time with the same parameters. After investigating, you find that the factory uses a class-level dictionary to cache objects. Which of the following is the most appropriate solution to prevent double processing?

Hard
73

Which TWO of the following statements about class attributes in Python are true?

Easy
74

You are designing a class that should behave like a sequence and support slicing. Which special methods must be implemented?

Hard
75

A development team is building a real-time chat application using Python. The application uses a class 'ChatRoom' that maintains a list of 'User' objects as active participants. Each User object holds a reference back to its ChatRoom to send messages. Over time, the application runs out of memory. Profiling reveals that User objects are not being garbage collected even after users disconnect. The team suspects circular references. Which solution would effectively resolve the memory leak without breaking the functionality?

Hard
76

Your company has two separate Python packages: 'app' and 'lib'. They are maintained by different teams. 'app' depends on 'lib', but 'lib' is still under development and its API changes frequently. To avoid breaking 'app', the team decides to use a virtual environment and install a specific version of 'lib'. However, during development, they need to test 'app' with the latest 'lib' changes from the Git repository. The current workflow is: (1) activate virtual env, (2) install 'lib' from local source using `pip install -e /path/to/lib`. This installs 'lib' as a development package. But one developer reports that after pulling latest 'lib' changes, importing 'lib' in 'app' still uses the old version even after re-running pip install -e. What is the most likely reason?

Medium
77

Which of the following correctly uses an abstract base class to enforce that all subclasses implement a 'make_sound' method? (Assume ABC imported)

Hard
78

Which method returns the lowest index where a specified substring is found, or -1 if not found?

Medium
79

Which TWO of the following are special methods in Python?

Easy
80

Refer to the exhibit. What is the effect of using 'from None' in the raise statement?

Hard
81

Refer to the exhibit. A script executes 'from mypackage import *'. Which functions are available in the global namespace?

Medium
82

Given: class A: def method(self): print('A'); class B(A): def method(self): super().method(); print('B'); class C(A): def method(self): super().method(); print('C'); class D(B, C): pass. What is printed by D().method()?

Medium
83

A developer needs to check if a string contains only alphanumeric characters. Which string method should be used?

Easy
84

A developer is tasked with validating user input that must be a 10-digit phone number. The input may contain spaces, dashes, and parentheses. Which approach best ensures the input contains exactly 10 digits?

Hard
85

A developer is creating a custom exception hierarchy for a library. The base exception is `LibraryError`. Which definition ensures that subclasses can be caught using the parent exception, but also allows distinguishing between different error types?

Hard
86

You are a data analyst working with a dataset of customer reviews. Each review is stored as a string in a list. You need to count how many reviews contain the word 'excellent' (case-insensitive). However, the word might appear as 'Excellent', 'EXCELLENT', or even with punctuation like 'excellent!'. The current code uses 'excellent' in review.lower(), but this fails if 'excellent' is part of another word like 'unexcellent'. You need to ensure that only the whole word 'excellent' is counted. Which code modification will correctly count whole word occurrences?

Medium
87

A developer is building a logging system that writes logs to a file. The system should handle disk-full situations gracefully without crashing the main application. Which approach is appropriate?

Medium
88

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?

Easy
89

What is the output of the Python code after reading the config.txt file?

Hard
90

A 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?

Medium
91

Refer to the exhibit. What is the output?

Hard
92

Which THREE are valid ways to create a multiline string in Python?

Medium
93

Given s = 'a1b2c3', which TWO of the following expressions return the string '123'?

Hard
94

A company has a large Python application that uses multiple packages from different directories. The application's main entry point is at /opt/app/main.py. There is a package 'common' located at /opt/app/common/ and another package 'services' at /opt/app/services/. Both packages have __init__.py files. Additionally, there is a third-party package 'utils' installed in the system site-packages. Recently, a developer added a new module 'helpers.py' to the 'common' package. When trying to import 'common.helpers' from a script inside 'services', an ImportError is raised: 'No module named common.helpers'. However, importing 'common' itself works. The sys.path includes /opt/app/ and the site-packages. What is the most likely cause of the import failure?

Hard
95

A developer creates a package 'mypackage' with the following structure: mypackage/ __init__.py module1.py module2.py The __init__.py contains: from mypackage.module1 import func1 from mypackage.module2 import func2 __all__ = ['func1', 'func2'] In a separate script, the developer writes: from mypackage import * print(func1()) This works as expected. However, when the developer runs the same script from a different directory (not the one containing mypackage), the import works but the script prints an error that func1 is not defined. What could be the problem?

Medium
96

Which TWO of the following can be used to remove leading whitespace (spaces, tabs, newlines) from a string? (Choose exactly 2 correct answers.)

Medium
97

Which TWO of the following statements about Python's `sys.path` are true?

Hard
98

A Python package 'mypackage' contains the following hierarchy: mypackage/ __init__.py subpackage1/ __init__.py module_a.py subpackage2/ __init__.py module_b.py From a script outside the package, a programmer writes: import mypackage.subpackage1.module_a Which statement is true about the import?

Hard
99

Which of the following is a valid way to import a module named 'math' and assign it an alias 'm'?

Easy
100

An application uses a class to represent a configuration object that reads settings from a file. The class has a class attribute config_cache that holds a dictionary of loaded configurations to avoid repeated file reads. However, the developer notices that when they modify the dictionary for one instance, it affects all instances. They want to ensure that each instance has its own copy of the configuration data upon initialization. Which change should they make?

Medium
101

A Python script placed in /opt/myapp/script.py fails with ImportError when run from a cron job with the command: python /opt/myapp/script.py. The script works when run manually from the /opt/myapp/ directory. The script contains the line: from . import config. The config module is located in /opt/myapp/lib/config.py with an __init__.py in /opt/myapp/lib/. What is the most likely cause of the failure?

Medium
102

A team is implementing a shape hierarchy with a base class `Shape` that should have an `area()` method. They want to ensure that every subclass must provide its own implementation of `area()`. Which approach should they use?

Medium
103

Consider a class `D` that inherits from multiple base classes `B` and `C`. The developer wants to call a method from a specific parent class while ensuring correct method resolution order (MRO). Which is the safest way?

Medium
104

You are a developer for an e-commerce platform. The system receives product descriptions from suppliers in various formats. One supplier sends descriptions with inconsistent capitalization, extra whitespace, and occasional leading/trailing punctuation. Your task is to write a function that normalizes these descriptions: convert to lowercase, remove leading/trailing whitespace and punctuation (.,!?;:), and replace multiple spaces with a single space. The function should return the cleaned string. Which implementation correctly performs all these steps?

Medium
105

Given package structure: pack/__init__.py, pack/subpack/__init__.py, pack/subpack/mod.py. Inside pack/__init__.py, which import statement correctly imports mod.py using a relative import?

Hard
106

Drag and drop the steps to perform unit testing with the unittest framework in Python into the correct order.

Medium
107

A logging module receives a message that may contain sensitive data. To comply with data privacy, all digits in the message should be replaced with 'X' before logging. Which approach correctly achieves this?

Medium
108

Which THREE of the following statements about Python's 'with' statement are true? (Select exactly 3)

Hard
109

Drag and drop the steps to serialize a Python object to JSON using the json module into the correct order.

Medium
110

A developer is working on a class hierarchy for geometric shapes. They have a base class Shape with an abstract method area(). They also have a mixin class Drawable that provides a method draw(). They want to create a class Rectangle that inherits from both Shape and Drawable. However, they encounter a TypeError when trying to instantiate Rectangle because the abstract method area() is not implemented. Which action should they take to resolve this?

Hard
111

Which THREE of the following are true about the `__init__` method in Python?

Medium
112

Which of the following demonstrates that strings are immutable?

Medium
113

A package 'pkg' is installed as an egg-link in development mode. Inside the package, there is a module 'submod.py' that uses relative imports. When a developer modifies 'submod.py', they find that changes are not always reflected on import. What is the most likely reason?

Hard
114

A developer writes a function that reads a file and processes its content. The function should handle the case where the file does not exist without catching other I/O errors. Which exception should be caught?

Easy
115

A developer installs a third-party package using pip, but when they try to import it in their script, Python raises a ModuleNotFoundError. The package is definitely installed (pip list shows it). What is the most likely cause?

Medium
116

A developer runs 'pip install mypackage' but gets a 'PermissionError'. Which command should be used to install the package for the current user only?

Hard
117

Which TWO statements about Python's name mangling are correct?

Hard
118

Which THREE methods return a boolean value?

Hard
119

A developer is working on a logging system where dynamic values are inserted into a template string. The template is 'User %s logged in at %s'. The developer has the username and timestamp as separate variables. Which approach is most Pythonic (PEP 498) and recommended for new code?

Medium
120

A Python class 'Shape' defines an abstract method 'area'. Subclasses 'Circle' and 'Square' implement 'area'. A function 'calculate_area(shape)' expects a 'Shape' instance. Which principle ensures that the function works correctly without knowing the specific subclass?

Hard
121

A developer writes: s = 'abc'; s[0] = 'x'. What happens?

Hard
122

Which THREE of the following escape sequences are valid in a Python string and represent a single character? (Select exactly three.)

Hard
123

Refer to the exhibit. Which of the following is the most likely cause of this error?

Medium
124

Refer to the exhibit. Given the project structure, which of the following import statements in main.py would cause an ImportError?

Medium
125

You are a Python developer working on a project with the following structure: myapp/ __init__.py main.py modules/ __init__.py utils.py helpers.py The file main.py contains: from modules import utils from modules import helpers utils.some_function() helpers.another_function() When you run main.py, you get an ImportError: No module named 'modules'. However, the modules directory exists and both __init__.py files are present. The directory myapp is not installed as a package; you are running main.py directly from the myapp directory. What is the most likely cause and how should you fix it?

Medium
126

You are a developer at a company that builds a data processing pipeline. The pipeline consists of several Python modules organized in a package called 'pipeline'. The package structure is: pipeline/ __init__.py load.py transform.py analyze.py The pipeline is deployed on a server where Python 3.8 is installed. The server also has a globally installed package called 'pipeline' (from a different project) in the site-packages directory. When you run your scripts that import 'pipeline', you get unexpected behavior because Python is importing the wrong package. You need to ensure that your local 'pipeline' package is used instead of the global one. You cannot uninstall the global package because it is used by another application. You have the following options: A) Modify the PYTHONPATH environment variable to include the directory containing your 'pipeline' package before the site-packages directory. B) Rename your local 'pipeline' package to something else and update all imports. C) Use a virtual environment specific to your project and install your package there. D) Add an __init__.py file with a special import hook to override the global package. Which course of action is the most appropriate and reliable?

Hard
127

A class has a class attribute that is a list. A developer modifies this list via one instance, and the change is reflected in all other instances. What is the best practice to avoid this unintended sharing?

Hard
128

Refer to the exhibit. A developer ran the script and saw the above traceback. The intended behavior was to load a JSON configuration file, and if the file is missing, create a default config. What is the most likely root cause of the second exception (NameError)?

Hard
129

Consider the following code snippet: s = 'abcdefgh'; result = s[7:3:-2]; print(result). What is the output?

Hard
130

You are developing a Python application that processes financial transactions. The application is structured as a package named `finance`. Inside `finance`, there are subpackages: `models`, `services`, and `utils`. The `services` subpackage contains a module `validator.py` that defines a function `validate_transaction()`. This function uses a helper function `check_amount()` defined in `utils.helpers`. The package is used by multiple other projects, and you want to ensure that importing `finance` does not accidentally expose internal helper functions. You also want to allow users to easily import the main validation function via `from finance import validate_transaction`. Which of the following approaches best achieves these goals?

Medium
131

A script runs: import sys; print(sys.path[0]). The output is an empty string. What does this indicate?

Hard
132

Which of these is NOT a characteristic of Python's descriptor protocol?

Hard
133

A team uses virtual environments to manage dependencies. They need to ensure that a script runs with the exact same module versions across different environments. Which approach is best?

Medium
134

A developer is writing a package that contains multiple modules. The package should allow users to import it directly and have all commonly used functions available at the package level. For example, after `import mypackage`, the user should be able to call `mypackage.func1()` without needing to import submodules. Which is the best way to achieve this?

Medium
135

Refer to the exhibit. What is the output?

Hard
136

Which THREE of the following statements about Python packages and modules are true?

Hard
137

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?

Medium
138

A developer needs to extract the file extension from a filename like 'document.pdf'. Which expression returns 'pdf'?

Hard
139

What is the result of the expression '12345'[:10]?

Easy
140

A company needs to model different types of employees. They have a base class `Employee` with a method `calculate_pay()`. For hourly employees, pay = hours * rate; for salaried employees, pay = salary. Which design approach is most appropriate?

Easy
141

Refer to the exhibit. What is the output and why?

Hard
142

A package 'mypackage' has subpackages 'sub1' and 'sub2'. In sub1/__init__.py, there is: from sub2 import helper. When importing mypackage, an ImportError occurs: No module named 'sub2'. What is the most likely cause?

Hard
143

A junior developer wrote a class representing a bank account with a private attribute balance. They used double underscore prefix (__balance) to make it private. However, in a test script, they are still able to access the attribute using the mangled name _Account__balance. The developer is confused about why encapsulation is not enforced. Which statement best explains this behavior?

Easy
144

Which TWO of the following are valid ways to define a class attribute that is shared by all instances?

Easy
145

Which TWO of the following are valid ways to import a module named 'math' and give it an alias 'm'?

Medium
146

A developer has two separate directories on sys.path: /home/user/libs and /opt/libs. Both directories contain a subdirectory 'mypackage' without an __init__.py file. The developer wants to import a module from 'mypackage' that exists only in one of the directories. What concept allows Python to treat these two directories as a single namespace package?

Hard
147

Consider the following code: print('"age": 30,')

Hard
148

Which TWO of the following file modes will create a new file if it doesn't exist? (Select exactly 2)

Easy
149

You maintain a Python library 'myutils' that is installed as a package in the system. The library has a submodule 'config' that reads configuration from a file. Recently, a user reported that after updating the library, their application still uses the old configuration values. They confirmed that the config file on disk has been updated. The library's __init__.py does: from .config import load_config. The user's application imports load_config from myutils and calls it each time they need configuration. What is the most likely cause of the issue?

Medium
150

A programmer wants to create a class that cannot be instantiated directly, only through a factory method. Which approach should be used?

Medium
151

A module 'shapes.py' defines several classes: Circle, Square, Triangle. The developer wants to allow users to import only Circle and Square when they use 'from shapes import *'. Which mechanism should be used?

Easy
152

A class `ServerConfig` has a class attribute `port = 8080`. After deployment, a developer runs `ServerConfig.port = 9090` in one module, and unexpectedly all existing instances now use port 9090. What concept explains this behavior?

Hard
153

Which TWO of the following expressions yield the substring 'Py' from the string s = 'Python'?

Hard
154

Which TWO of the following string methods modify the string in place? (Note: Python strings are immutable.)

Medium
155

A Python developer is implementing a class that should behave like a sequence and support indexing. Which pair of special methods must be defined to achieve this?

Hard
156

Which THREE of the following are true about method overriding in Python?

Hard
157

A Python script is written to be used both as a standalone program and as an imported module. Which condition should the script use to execute code only when run directly?

Easy
158

A class inherits from two parent classes that both have a method with the same name. When calling the method on the child, only one parent's version is executed. What Python mechanism determines which one?

Medium
159

A developer is working on a data pipeline that processes files from untrusted sources. The pipeline should catch and log any exception, but also ensure that sensitive information from the exception (e.g., file paths) is not exposed to end users. Which approach balances security and debugging?

Hard
160

A developer wants to check if a string ends with a specific suffix. Which method should be used?

Easy
161

Refer to the exhibit. What is the output?

Hard
162

A developer tries to modify a string: s = 'hello'; s[0] = 'H'. What happens when this code runs?

Medium
163

A developer is implementing a custom exception for invalid data. Which class should the custom exception inherit from?

Medium
164

A team is developing a large Python application with multiple modules. They encounter an ImportError when module A tries to import from module B, and module B tries to import from module A. What is the most likely cause and best practice to resolve this?

Medium
165

Which THREE statements about inheritance in Python are correct?

Medium
166

A developer creates a metaclass 'Meta' that modifies class creation by adding a class attribute 'created_by' set to 'Meta'. Which code snippet correctly defines and uses this metaclass?

Hard
167

An application uses a heavy-weight class DatabaseConnection that establishes a network connection upon instantiation. The class is used in multiple places, and the developer wants to ensure that only one instance of DatabaseConnection exists throughout the application. They implement a Singleton pattern using a class attribute _instance and a class method get_instance(). However, they notice that the network connection is being established multiple times. After debugging, they find that the singleton is not being enforced because the __init__ method is called every time the class is instantiated, even if the same instance is returned. They want to fix this so that the connection is established only once. Which modification should they make?

Hard
168

A programmer writes a function that expects a string and returns it reversed. Which code snippet correctly reverses the string 'stressed' to 'desserts'?

Easy
169

Which of the following statements about the __init__.py file in a package is true?

Easy

Frequently asked questions

What does the scenario questions domain cover on the PCAP exam?
scenario questions questions test whether you can apply the concept in context, not just recognise a definition.
How many questions are in this domain?
This page lists all 169 scenario questions questions in the PCAP question bank. The actual exam draws from this domain proportionally to its weighting in the official exam blueprint.
What is the best way to practise this domain?
Start with a short focused session (10 questions) to identify gaps, then work through explanations. Repeat with a longer session once the weak areas feel solid.
Can I practise only scenario questions questions?
Yes — the session launcher on this page filters questions to this domain only. Choose any session length for inline explanations and scoring.