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.

421 questions124 easy165 medium132 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 (421)

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

1

A developer is writing a function to reverse each word in a sentence while preserving the original order of the words. For example, 'Hello World' should become 'olleH dlroW'. The current implementation is: def reverse_words(s): return ' '.join(word[::-1] for word in s.split()). This works for simple cases. However, the input may contain multiple spaces between words (e.g., 'Hello World') and tabs. The requirement is to preserve the exact whitespace between words (including tabs and multiple spaces) in the output. Which of the following modifications will achieve this while keeping the approach efficient?

Medium
2

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

Medium
3

Given the following code: class Parent: def show(self): print('Parent') class Child(Parent): def show(self): print('Child') c = Child(); c.show(); super(Child, c).show(). What is the output?

Medium
4

A parent class defines a method `move()`. A child class overrides `move()` but also needs to call the parent's version inside it. Which syntax allows that?

Easy
5

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
6

A developer runs the following code in a script that is not part of a package: import sys sys.path.insert(0, '/custom/path') import mymodule print(mymodule.__name__) What is the output if 'mymodule' is found at '/custom/path/mymodule.py'?

Hard
7

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
8

Which THREE of the following are immutable types in Python?

Medium
9

A developer wants to use a function 'calculate' from a module 'math_ops' that is located in a sibling directory '../shared/' relative to the current script. What is the correct way to import it using an absolute import assuming the shared directory is a package with __init__.py and the project root is in sys.path?

Easy
10

What happens when you execute the following code? s = 'hello'; s[0] = 'H'

Hard
11

A programmer needs to write a function that reads a large binary file (over 1 GB) and returns its entire content as a bytes object. The function must handle the case where the path provided is actually a directory (IsADirectoryError) by returning an empty bytes object. Which implementation is most memory-efficient and correctly handles the directory case? Consider that reading the entire file into memory is acceptable for the business case.

Easy
12

A junior developer is parsing a log file where each line has comma-separated fields. However, some fields are enclosed in double quotes and contain commas inside, e.g., '2023-08-15 14:30:00,WARNING,"Disk space low, please clean up".'. They are required to parse these lines using only built-in string methods (no modules like csv or re). Which approach is the most reliable and efficient?

Hard
13

Which TWO of the following are valid ways to import a function named 'func' from a module 'mymod' that is in the same directory as the script?

Easy
14

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

Hard
15

Which method of a file object reads the entire content of a text file as a single string?

Easy
16

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

Medium
17

A script contains the following lines: import math from math import sqrt print(math.sqrt(16)) print(sqrt(25)) What is the output when the script is executed?

Easy
18

Drag and drop the steps to define and call a function with default arguments in Python into the correct order.

Medium
19

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

Easy
20

A company runs a data processing pipeline that reads CSV files from a network drive. Occasionally, the network drive is unreachable causing FileNotFoundError. The current code uses a bare except clause that catches all exceptions, which also masks programming errors like NameError. The lead developer wants to implement a more robust exception handling strategy. The requirement is to log the specific error (including the filename) and retry the operation up to 3 times with a 2-second delay between retries. If after 3 attempts the file is still inaccessible, the pipeline should skip the file and continue with the next one. Which approach best meets these requirements?

Medium
21

You are a network engineer troubleshooting a script that processes router configuration files. The script reads a configuration line from a file: 'interface GigabitEthernet0/1 ip address 192.168.1.1 255.255.255.0 no shutdown'. The script needs to extract the interface name and IP address. The current code uses string split operations but fails when the line has extra spaces or tabs. For example, when the line is 'interface GigabitEthernet0/1', the split returns ['interface', '', '', 'GigabitEthernet0/1'] and the script fails. You need to modify the script to robustly extract the interface name and IP address regardless of whitespace. Which approach should you take?

Hard
22

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
23

What is the cause of the error?

Medium
24

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?

Hard
25

Consider the following code: print(type('apple,banana,cherry'.split(','))) What type of value is printed?

Easy
26

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
27

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
28

A developer wants to ensure that an attribute 'balance' of a BankAccount class cannot be accessed directly from outside the class but can be accessed through a method. Which approach should be used?

Easy
29

A developer designs a plugin system where each plugin must implement a method 'execute'. Which code snippet correctly enforces that subclasses provide an implementation using the 'abc' module?

Medium
30

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
31

A developer needs to write a function that safely divides two numbers and returns None if division by zero occurs. Which implementation is most Pythonic?

Medium
32

Which TWO statements about exception handling in Python are correct? (Select exactly 2.)

Medium
33

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

Hard
34

Match each Python data structure to its mutability.

Medium
35

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
36

What is the result of 'PyThon'.lower()?

Easy
37

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
38

What is the result of the expression 'Hello' * 3?

Easy
39

Which THREE of the following string methods return a boolean value (True or False)? (Choose exactly 3 correct answers.)

Medium
40

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

Hard
41

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

Easy
42

Refer to the exhibit. What is printed?

Hard
43

A developer opens a CSV file with open('data.csv', 'r', encoding='utf-8') and reads it with readline(). The first line contains a non-ASCII character that the file declares as UTF-8. Which exception is most likely raised if the file actually contains bytes that are not valid UTF-8?

Easy
44

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

Medium
45

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
46

A developer has a function that performs several operations and may raise different exceptions. The developer wants to catch a specific exception and then re-raise it after logging. Which code snippet correctly re-raises the same exception without losing its traceback?

Medium
47

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
48

Which TWO statements are true regarding strings in Python?

Medium
49

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
50

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

Medium
51

A developer writes a helper that copies lines from one text file to another. The helper opens both files with open() inside a try block and closes them in a finally block. If an exception occurs while writing, which statement about the finally block is correct?

Hard
52

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
53

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
54

A developer wants to replace all vowels in a string with their corresponding uppercase letters. They wrote: `s = 'hello world'`; `vowels = 'aeiou'`; `trans = str.maketrans(vowels, vowels.upper())`; `result = s.translate(trans)`. What is the value of `result`?

Medium
55

Which THREE of the following exception types are subclasses of OSError in Python 3?

Hard
56

A programmer wants to check whether a string `s` is a palindrome (reads the same forwards and backwards, ignoring case and non-alphanumeric characters). Which code snippet correctly implements this?

Easy
57

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
58

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
59

A Python project has the following directory structure: project/ __init__.py main.py subpackage/ __init__.py module.py Inside 'module.py', there is a function 'func' that needs to be imported in 'main.py'. The team wants to import 'func' using a relative import from 'main.py'. However, when they run 'python main.py' from the project root, they get an ImportError. What is the most likely reason?

Hard
60

Which TWO string methods are used to determine if a string begins or ends with a specified prefix or suffix? (Choose two.)

Easy
61

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

Medium
62

A developer is writing a function that reads a configuration file. The function must distinguish between a missing file, a permission problem, and a malformed file, and it must not leave the file open on any path. Which TWO techniques are appropriate for this requirement? (Choose two.)

Medium
63

A programmer wants to restrict a class to only allow specific attribute names and reduce memory usage. Which feature should they use?

Hard
64

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

Easy
65

Match each code snippet to its output.

Medium
66

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
67

Which THREE factors can cause an 'ImportError' when trying to import a module?

Hard
68

A script reads a binary file and decodes it as UTF-8. Some bytes are invalid UTF-8 sequences, causing a `UnicodeDecodeError`. The developer wants to replace invalid bytes with the replacement character U+FFFD. Which approach achieves this?

Hard
69

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
70

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
71

Refer to the exhibit. What happens when the last command is executed?

Hard
72

A developer wants to check if a string 'example.txt' ends with '.txt'. Which expression returns True?

Easy
73

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
74

What is the most likely cause of this error?

Medium
75

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
76

A developer is designing a class hierarchy for a library system. They want to ensure that a method 'borrow' in the base class 'Item' can be overridden by subclasses like 'Book' and 'DVD', but the base implementation should not be callable directly. Which approach best achieves this?

Medium
77

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
78

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
79

What will be printed?

Medium
80

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

Easy
81

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

Easy
82

What does the expression 'hello world'.title() return?

Medium
83

Match each string method to its purpose.

Medium
84

A Python script that processes log files uses the following code: with open('log.txt', 'r') as f: lines = f.readlines() for line in lines: # process What is a potential inefficiency in this code?

Medium
85

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

Easy
86

What is the value of matches?

Hard
87

Which TWO of the following statements about Python classes are true? (Select exactly 2.)

Medium
88

A junior developer is writing a helper that reads a small log file and returns its contents as a single string. The file is guaranteed to exist and be readable. The helper currently uses an explicit open, a try/finally block, and manual close call. A reviewer asks for the most idiomatic Python 3 replacement that guarantees closure. Which construct should be used?

Easy
89

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
90

Which TWO of the following string methods return a new string with all characters converted to lowercase? (Select exactly two.)

Medium
91

A class `Circle` has a class attribute `pi = 3.14`. An instance `c = Circle()` sets `c.pi = 3.14159`. What is the value of `Circle.pi` after this assignment?

Easy
92

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

Medium
93

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
94

Which THREE of the following are true about Python strings?

Medium
95

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

Hard
96

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
97

Drag and drop the steps to create and activate a virtual environment in Python into the correct order.

Medium
98

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
99

Refer to the exhibit. Which of the following Python code snippets would generate this error?

Medium
100

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

Hard
101

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?

Medium
102

A developer is working with a string `text = "The quick brown fox jumps over the lazy dog"`. They want to create a new string where every occurrence of the word 'the' (case-insensitive) is replaced with 'a'. However, they must not replace 'the' when it is part of another word, such as in 'then' or 'there'. Which approach correctly achieves this?

Hard
103

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

Easy
104

Which TWO of the following are correct statements about the 'with' statement in Python file I/O?

Easy
105

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
106

A class defines a variable `count = 0`. An instance modifies `self.count = 5`. What is the value of `count` in the class namespace?

Easy
107

A developer wants to create a string that contains the current year and month in the format 'YYYY-MM'. The year and month are stored in integer variables year and month. Which expression would produce the desired result?

Easy
108

What is the output of `print('-'.join(['a', 'b', 'c']))`?

Easy
109

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
110

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
111

A subclass overrides a method but wants to call the parent class's version. Which keyword should be used?

Easy
112

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
113

Match each Python operator to its precedence level (1=highest).

Medium
114

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
115

A company has a shared internal library stored in a Git repository. Developers need to use this library in multiple projects without copying the code. Which approach is the most Pythonic and maintainable?

Medium
116

A developer is building a large string by concatenating many substrings in a loop using '+'. What is the main performance issue?

Hard
117

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
118

Match each Python module to its purpose.

Medium
119

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
120

Which TWO of the following are true about the 'with' statement in Python file I/O?

Medium
121

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

Medium
122

A package named 'utilities' contains a submodule 'strings'. Which import statement allows the use of the function 'reverse' defined in utilities.strings as reverse() without needing to prefix it?

Easy
123

A programmer writes a function to check if a string is a palindrome (ignoring case and non-alphanumeric characters). Which implementation correctly achieves this?

Medium
124

A developer wants a class 'Point' to have a readable string representation that returns 'Point(x, y)'. Which special method should be overridden?

Easy
125

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
126

An engineer is debugging an application that uses inheritance. The base class 'Vehicle' defines a method 'start()' that prints 'Vehicle started'. The subclass 'Car' overrides 'start()' to print 'Car started'. The code contains a function that accepts a Vehicle object and calls 'start()'. What is the output if a Car object is passed?

Medium
127

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
128

What is the output of the code?

Medium
129

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
130

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
131

Match each exception to its cause.

Medium
132

A developer is cleaning data from a CSV file. They have a string `record = "John,Doe,35,Engineer"` and want to replace all commas with semicolons. However, they also want to ensure that any leading or trailing whitespace in the entire string is removed before the replacement. Which expression produces the desired result?

Medium
133

A developer wants to remove all leading and trailing whitespace from a string, but preserve internal spaces. Which line of code accomplishes this?

Medium
134

Which TWO methods are valid ways to import a function named 'foo' from a module 'bar' that is part of a package 'pkg'?

Medium
135

Refer to the exhibit. If both data.txt and backup.txt do not exist, what is the output?

Hard
136

Given s = 'Python', which THREE of the following expressions evaluate to True? (Choose three.)

Hard
137

A beginner programmer writes: name = "Alice"; print("Hello " + name). Which string method alternative is more efficient and recommended for Python 3?

Easy
138

A developer is building a simulation of different types of vehicles. They have a base class Vehicle with an attribute speed initialized in __init__. They also have a subclass Car that inherits from Vehicle and adds an attribute fuel_type. The developer wants to ensure that every time a Car object is created, it also initializes the speed attribute from the Vehicle class. Which approach should the developer use?

Easy
139

A developer is designing a system where a `Car` class needs to reuse functionality from `Engine` and `Transmission` without creating a deep hierarchy. Which OOP principle should be applied?

Medium
140

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
141

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
142

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
143

A developer uses the .index() method on a string to find the position of a substring. If the substring is not found, what exception is raised?

Easy
144

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
145

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

Easy
146

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
147

Which TWO of the following methods return a boolean value?

Medium
148

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

Easy
149

A company is developing a scientific simulation framework where many different solvers must be interchangeable. The framework should enforce that each solver implements methods 'initialize' and 'step'. Developers want to use abstract base classes. Which approach should the team take to ensure that any subclass of 'Solver' cannot be instantiated unless it defines both methods?

Medium
150

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
151

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
152

A data entry application reads a CSV file where each line contains fields separated by commas. However, some fields are enclosed in double quotes and contain commas inside, e.g., 'John,"Doe, Jr.",30'. The developer currently uses line.split(',') to parse each line, which incorrectly splits the quoted field. The developer wants a solution using only the Python standard library (no third-party packages). Which of the following is the best approach?

Easy
153

A class `Point` has an `__init__` that sets `self.x` and `self.y`. They want to compare points by equality (i.e., `p1 == p2` should work correctly). Which method should they implement?

Easy
154

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

Hard
155

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

Medium
156

A programmer is writing a script to generate SQL queries safely. They need to escape single quotes in user-provided strings to prevent injection. Which approach is most robust?

Hard
157

Which TWO of the following are special methods in Python?

Easy
158

Refer to the exhibit. A developer runs 'pip install pandas==2.0.0' but gets an error stating that the required version is not available. Which command should be used to list all available versions of pandas?

Medium
159

Given s = 'Python', what is s[1:4]?

Medium
160

A developer is writing a script that processes user-uploaded CSV files. The script should attempt to read the file, and if a UnicodeDecodeError occurs, log a warning and skip the file. Which code snippet correctly achieves this without stopping the entire process?

Medium
161

A developer writes a log message with variables: name = 'Alice' and age = 30. Which of the following uses an f-string correctly?

Medium
162

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

Hard
163

A production script opens a configuration file with `open('config.ini', 'r')`. During a recent maintenance window, the file was replaced by a directory of the same name. The script now terminates with `IsADirectoryError`. The developer wants to catch this specific condition separately from a missing file and log a distinct message. Which `except` clause should be added?

Medium
164

Consider the following code: name = "Alice" age = 30 print(f"{name} is {age} years old.") What is the output of the above code?

Easy
165

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
166

Which TWO of the following string methods return a boolean value (True or False)?

Medium
167

Which TWO string methods raise an exception when the searched substring is not found?

Easy
168

Which TWO statements about Python strings are correct? (Choose exactly 2 correct answers.)

Hard
169

Which TWO of the following statements about Python packages are true?

Medium
170

A developer wants to check if a string 'racecar' is a palindrome by comparing it to its reverse. Which code completes the task correctly?

Easy
171

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

Easy
172

Which of the following correctly raises a new exception while preserving the original traceback?

Hard
173

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
174

What is the likely outcome of running the following code? ```python with open("C:\Users\path\file.txt", "r") as f: print(f.read()) ```

Hard
175

Which TWO of the following are valid ways to import specific names from a module?

Easy
176

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
177

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
178

Which three of the following statements about Python strings are true? (Choose three.)

Hard
179

What is the output of the code in the exhibit?

Easy
180

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?

Medium
181

Which of the following is the correct way to open a file for writing in binary mode?

Easy
182

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
183

A junior developer is writing a script that processes user input. The script reads a line of text from the console and needs to remove any leading or trailing whitespace. The developer uses the strip() method but notices that it also removes other characters like newline. However, the requirement is to remove only spaces (not tabs or newlines). Which course of action should the developer take to remove only leading and trailing spaces?

Easy
184

Given the code: s = 'Python'; t = s; s = s + '3.0'. What is the value of t after these lines execute?

Hard
185

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
186

Which TWO of the following are built-in exceptions in Python? (Select exactly 2.)

Easy
187

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

Hard
188

What is the output?

Easy
189

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
190

Consider the following code: import json try: with open('config.json') as f: data = json.load(f) except FileNotFoundError: print("Missing config file") except json.JSONDecodeError: print("Invalid JSON") except: print("Unexpected error") If the file 'config.json' exists but contains invalid JSON, what is printed?

Easy
191

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

Medium
192

Refer to the exhibit. What is the output?

Hard
193

Which TWO of the following are valid ways to define a property in a Python class? (Select exactly 2.)

Easy
194

Which of the following expressions returns True if the string s contains only hexadecimal digits (0-9, a-f, A-F)?

Hard
195

A developer runs a script that reads records from a binary file. After a partial read, the storage device is unplugged, and the read() call raises OSError. The developer wants the script to retry the read a few times before giving up, but only for this transient I/O problem. Which exception should be caught to retry specifically on this failure?

Medium
196

An application needs to dynamically load a module whose name is provided at runtime (stored in a variable 'mod_name'). Which function from the importlib module should be used?

Hard
197

Which THREE statements about the Python method resolution order (MRO) are true? (Select exactly 3.)

Hard
198

Match each Python built-in function to its description.

Medium
199

A developer is formatting a log message and wants to ensure that a string variable `name` is centered within a field of width 20, padded with asterisks (`*`) on both sides. For example, if `name = "Alice"`, the result should be `*******Alice********` (7 asterisks on the left, 8 on the right). Which method call achieves this?

Easy
200

Which TWO statements about static methods (@staticmethod) are correct?

Easy
201

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

Hard
202

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
203

Which THREE of the following are true about Python's object-oriented programming features?

Hard
204

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
205

A data-import tool must read a UTF-8 CSV file that occasionally contains bytes invalid for UTF-8. The tool should not crash, but it must record that replacement occurred so the operator can review the source. The developer opens the file with `open('data.csv', encoding='utf-8', errors='replace')` and reads it. Which outcome matches this configuration?

Hard
206

Which THREE of the following are true about Python's exception hierarchy?

Hard
207

A developer wants to distribute a package that contains both Python code and data files (e.g., images, configs). Which file is used to specify dependencies and metadata for the package?

Easy
208

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

Medium
209

Which of the following statements about class inheritance in Python are true? (Choose two.)

Easy
210

A developer is implementing a simple counter class. The class should start at 0 and increment by 1 each time the 'increment' method is called. Which implementation is correct?

Easy
211

When importing a module, Python searches for it in a specific order. Which of the following lists the correct order of directories searched?

Medium
212

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

Hard
213

A developer wants to remove leading and trailing whitespace from a string. Which method should be used?

Medium
214

A programmer wants to ensure that a class attribute is the same for all instances and can be accessed via the class name. Which type of variable should be defined?

Easy
215

A team is developing a banking system in Python. They have a base class Account with attributes account_number and balance, and a method __init__(self, account_number, balance) that initializes these attributes. They then create a subclass SavingsAccount that adds an attribute interest_rate. In SavingsAccount's __init__, they assign self.interest_rate = rate but do not call super().__init__. When they instantiate SavingsAccount('12345', 1000, 0.02) and attempt to print(balance), an AttributeError occurs: 'SavingsAccount' object has no attribute 'balance'. What is the most appropriate fix to ensure that the SavingsAccount includes balance and account_number without code duplication?

Hard
216

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
217

Which THREE of the following are true about the __pycache__ directory?

Medium
218

Which of the following is the correct way to format a string to include a variable value with two decimal places in Python?

Medium
219

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

Easy
220

A developer needs to check if a filename starts with the prefix 'report_'. Which string method should be used?

Easy
221

Which TWO of the following string methods return a boolean value?

Easy
222

A team wants a `Logger` class that can be used both as `Logger.log('msg')` on the class itself and as `logger.log('msg')` on an instance, with identical behaviour and no access to instance state. Which decorator should be applied to `log`?

Medium
223

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?

Easy
224

An abstract base class (ABC) defines an abstract method `process()`. Several subclasses implement it. A function accepts any subclass and calls `process()`. This demonstrates which OOP concept?

Hard
225

When should you raise a specific exception class rather than a generic Exception?

Hard
226

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
227

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?

Easy
228

A user runs script.py and gets the above error: ModuleNotFoundError: No module named 'mypackage'. Which of the following is the most likely cause?

Easy
229

Which THREE of the following are true about the `with` statement for file handling?

Hard
230

A file is opened with open('test.txt', 'r'). The file object's tell() method returns 0. After reading 10 characters, what does tell() return?

Medium
231

A backup utility writes a manifest with `with open('manifest.txt', 'w') as out:`. The developer needs to ensure that partial writes are not silently left in the file when an exception occurs mid-loop. Which two statements about using a try/except/else/finally structure around this write loop are correct? (Choose two.)

Medium
232

Which TWO statements about namespace packages are true?

Medium
233

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
234

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
235

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
236

A programmer writes a class with a static method using @staticmethod. What is the primary purpose of using a static method instead of a class method or instance method?

Medium
237

A programmer writes a context manager to manage a temporary file. The class implements __enter__ to open the file and return the handle, and __exit__ to close it. During the with body, an exception is raised. The programmer wants the exception to propagate after cleanup. What should __exit__ return in this case?

Hard
238

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
239

A programmer has a string 'apple,banana,orange' and wants to get a list ['apple', 'banana', 'orange']. Which method should be used?

Easy
240

A developer needs to add a custom directory '/home/user/mylibs' to Python's module search path so that modules in that directory can be imported. Which code snippet accomplishes this correctly?

Easy
241

A developer runs pip install package==1.0 and gets the above error. What is the most likely solution?

Medium
242

A programmer has a string s = 'Python programming is fun'. They want to extract the word 'programming'. Which slicing expression achieves this?

Medium
243

A developer writes a class `Vector` and wants `v1 + v2` to return a brand-new `Vector`, while `v1 += v2` should mutate `v1` in place and return it. Which pair of special methods achieves this behaviour?

Hard
244

A Python package 'analytics' contains a subpackage 'models' with module 'regression.py'. Inside 'regression.py', there is a function 'linear_fit' that depends on 'numpy'. The developer wants to ensure that 'numpy' is imported only once and available throughout the package. Where should the import 'import numpy as np' be placed?

Medium
245

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

Medium
246

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
247

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

Hard
248

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

Medium
249

What is the result of the expression 'aBc'.lower()?

Easy
250

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?

Medium
251

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
252

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

Medium
253

A programmer needs to replace every occurrence of 'cat' with 'dog' in a string s, but only if 'cat' is not preceded by 'big'. Which regex substitution would achieve this?

Medium
254

What is the output of the following code? try: print(1/0) except: print('err') finally: print('fin')

Medium
255

What is the output of 'hello'.count('l')?

Easy
256

Which of the following demonstrates that strings are immutable?

Medium
257

A developer defines a class 'A' with a method 'm' that uses 'self.a'. Class 'B' inherits from 'A' and defines __init__ that sets 'self.a = 10'. An instance of B is created and method m is called. What is the output?

Hard
258

A class `Vector` defines `__add__` to return a new `Vector`. A developer writes `v1 = Vector(1,2); v2 = Vector(3,4); v3 = v1 + v2`. What is the type of `v3`?

Medium
259

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
260

Which TWO of the following are valid uses for the '__name__' variable in a Python module?

Easy
261

Which TWO statements about the sys module are true?

Medium
262

What is the result of 'Python'.find('th')?

Medium
263

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
264

When a class defines both __getattr__ and __getattribute__, which one is called when accessing an attribute that exists in the instance?

Hard
265

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
266

A class MyClass defines __str__ and __repr__ methods. What is the purpose of __repr__?

Easy
267

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
268

Drag and drop the steps to debug a Python script using pdb into the correct order.

Medium
269

A developer wants to implement a read-only property for a class 'Temperature' that returns the temperature in Celsius but prevents external modification. Which code snippet correctly defines such a property?

Easy
270

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?

Medium
271

Refer to the exhibit. Which of the following correctly shows the MRO of class D?

Medium
272

A user entered a string ' Hello, World! '. Which expression returns 'Hello, World!'?

Easy
273

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

Hard
274

Which THREE methods return a boolean value?

Hard
275

A package 'tools' has the structure: tools/__init__.py, tools/calc.py, tools/io.py. In __init__.py, the developer writes: from . import calc. A user tries: import tools; print(tools.add(1,2)). This fails with AttributeError. Why?

Medium
276

A developer wants to ensure that a file is always closed after writing, even if an exception occurs. Which approach is considered best practice in Python?

Medium
277

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
278

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
279

A developer defines a class with a private attribute `_value` and wants to provide controlled access. Which approach is the most Pythonic?

Easy
280

Which THREE of the following are characteristics of Python's special methods (dunder methods)? (Select exactly three.)

Hard
281

A developer writes a class `Logger` with a method `log(self, message)`. They want to ensure that when `Logger` is subclassed, any override of `log` must call the parent's `log` method. Which technique best enforces this requirement in Python?

Hard
282

When processing a large text file, a developer notices that using str.replace() in a loop is slow. Which alternative is most efficient for multiple replacements?

Medium
283

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

Hard
284

Drag and drop the steps to create a simple HTTP server using the http.server module in Python into the correct order.

Medium
285

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

Hard
286

Which of the following expressions returns the string 'Hello' repeated three times?

Easy
287

Which mode should be used when opening a file for writing such that new content is appended to the end without truncating existing content?

Easy
288

Which expression returns the last character of string s?

Easy
289

Match each list method to its effect.

Medium
290

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

Hard
291

Which string method would you use to check if a string starts with a specified prefix?

Easy
292

Consider the following class hierarchy: class A: def method(self): return 'A'; class B(A): pass; class C(A): def method(self): return 'C'; class D(B, C): pass. What is the output of D().method() according to Python's MRO?

Medium
293

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

Medium
294

A developer writes a script that reads a configuration file. If the file does not exist, the program should print an error and continue. Which code snippet correctly implements this behavior?

Easy
295

Refer to the exhibit. What does the 'from None' clause do in the second raise statement?

Hard
296

Inside a package 'data', there is a subpackage 'io' and a module 'utils'. Which import statement inside the 'io' subpackage correctly imports the 'helper' function from the sibling module 'utils'?

Medium
297

Which of the following exception classes is NOT a direct subclass of Exception in Python?

Hard
298

Refer to the exhibit. If the file config.cfg exists but the user does not have read permission, what will be printed?

Easy
299

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

Medium
300

What is the result of the expression '123'.zfill(5)?

Hard
301

A developer is building an IoT application that reads temperature data from a sensor over a TCP socket. The sensor sends data as a stream of bytes encoded in UTF-8, with each reading terminated by a newline character. The developer uses the following code to receive data: ```python import socket s = socket.socket() s.connect(('sensor.local', 5000)) data = s.recv(1024) ``` The variable `data` is a bytes object. The developer needs to convert it to a string to parse the temperature value. Which of the following lines of code should the developer use to correctly obtain the string representation of the received data, assuming the data is valid UTF-8 and may contain non-ASCII characters?

Easy
302

Which TWO of the following are appropriate techniques for logging exception details in Python? (Select exactly 2)

Medium
303

Consider the following code snippet: 'class A: pass; class B(A): pass; class C(A): pass; class D(B, C): pass'. What is the Method Resolution Order (MRO) for class D according to the C3 linearization algorithm used by Python?

Hard
304

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

Medium
305

What will the above code output?

Medium
306

Given the code above, what is printed? Note: each backslash is a single character.

Hard
307

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
308

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
309

A developer is validating user input in a Python application. The string variable `input_str` is assigned the value `'Hello World'`. Which TWO of the following conditions evaluate to `True`? (Choose two.)

Medium
310

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

Hard
311

A web application receives a byte string b'\xc3\xa9' which represents the character 'é' in UTF-8. The developer wants to convert it to a Python string. Which operation should be used?

Hard
312

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
313

Which THREE of the following string methods can be used to split a string into a list of substrings? (Choose three.)

Medium
314

A programmer wants to create a package named 'analytics' with subpackages 'statistics' and 'ml'. Which directory structure correctly defines these packages?

Easy
315

A developer writes: print('{:,}'.format(1234567)). What is the output?

Hard
316

Refer to the exhibit. What is the output of the last line?

Hard
317

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

Hard
318

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
319

Which TWO of the following are valid string methods in Python?

Easy
320

Refer to the exhibit. What happens when the last line is executed?

Easy
321

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
322

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

Hard
323

Refer to the exhibit. The above log shows an unhandled exception that caused the program to crash. The developer wants to handle this exception and log the error without crashing. Which exception type should be caught in the main code to capture this specific error?

Easy
324

Refer to the exhibit. A Python script uses the following code to load the policy. However, it fails with a JSONDecodeError. What is the most likely cause? ```python import json with open('policy.json', 'r') as f: policy = json.load(f) ```

Hard
325

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
326

A Python project uses namespace packages spread across multiple directories. The package structure is: project/ and lib/ both contain subdirectories 'mypkg/'. Each has an __init__.py file. When importing 'mypkg', which directory's contents are used?

Hard
327

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

Hard
328

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

Easy
329

A Python application processes user-uploaded files. The requirement is to catch any I/O-related exception while reading the file, but not to catch KeyboardInterrupt or SystemExit. Which exception type should be caught?

Hard
330

A module 'config.py' contains a variable 'settings' that is a dictionary. Another script does: from config import settings. Then the script modifies settings['key'] = 'new_value'. What happens?

Easy
331

Which of the following best describes the use of the @abstractmethod decorator in Python?

Hard
332

A developer is creating a Python package named 'utils' and wants to control what is imported when a user writes 'from utils import *'. Which file and variable should be defined?

Hard
333

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
334

A class 'Point' is defined with __slots__ = ['x', 'y']. A developer creates an instance p = Point() and tries to set p.z = 10. What happens?

Medium
335

Refer to the exhibit. If /var/data/in.csv does not exist, what exception is raised?

Medium
336

Given the string 'Python', what is the result of 'Python'[::-1]?

Hard
337

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
338

A developer defines a class 'Car' with an attribute 'wheels = 4'. They create two instances: car1 = Car() and car2 = Car(). Then they set car1.wheels = 3. What is the value of car2.wheels?

Easy
339

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
340

Consider the following code: class A: x = 1; class B(A): pass; class C(A): x = 2; class D(B, C): pass. What is D.x?

Medium
341

Which TWO of the following expressions evaluate to `True`? (Select exactly two.)

Easy
342

Which string method can be used to check if a string contains only digits?

Easy
343

Consider the following code: result = ' '.join(['a', 'b', 'c']) print(repr(result)) What is the output?

Hard
344

Refer to the exhibit. A Python script uses re.split with a regex pattern. What is the output?

Hard
345

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
346

A data scientist needs to count the occurrences of a substring in a long DNA sequence (e.g., 1 million bases). However, the count must include overlapping occurrences. For example, in 'AAAA', the substring 'AA' appears three times overlapping. The built-in count() method does not count overlapping matches. The scientist needs a function to count overlapping substrings efficiently without using third-party libraries. Which of the following approaches is the most efficient for this task?

Hard
347

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

Hard
348

Which TWO of the following string methods return a new string without modifying the original?

Easy
349

Which TWO of the following are valid ways to read a file line by line without loading the entire file into memory?

Medium
350

What is the output of the following code? s = 'Hello'; print(s.find('l'))

Medium
351

Refer to the exhibit. What is the root cause of the error?

Hard
352

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
353

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

Medium
354

Which THREE of the following expressions return the string "Python"? (Choose three.)

Hard
355

Which TWO of the following are immutable in Python?

Easy
356

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?

Hard
357

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
358

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
359

A class has a method that does not access any instance or class data. What decorator should be used to define it as a utility method that can be called on the class itself without requiring an instance?

Easy
360

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

Easy
361

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

Medium
362

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?

Easy
363

A developer needs to write binary data to a file. Which file mode should be used to open the file for writing in binary mode without truncating it if it already exists?

Easy
364

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?

Medium
365

Which THREE are valid escape sequences in Python strings?

Hard
366

Which TWO statements about method overriding in Python are correct?

Medium
367

Which THREE of the following are valid string methods in Python? (Choose three.)

Medium
368

What is the result of the expression 'Hello'[1:3]?

Easy
369

What is the output of the following code? try: raise ValueError('a') except ValueError as e: print(e.args[0]) finally: print('b')

Hard
370

A package 'mypkg' has the following structure: mypkg/ __init__.py submod1.py submod2.py The __init__.py file contains: from . import submod1, submod2. A user runs 'import mypkg' and then 'mypkg.submod1.func()'. However, the user got an AttributeError. What is the most likely cause?

Hard
371

A developer wants to ensure that the 'radius' attribute of a Circle class is always non-negative. Which implementation using @property is correct?

Hard
372

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
373

A class named Counter has a class variable count and an instance method increment. The method is defined as def increment(self): Counter.count += 1. What will be the output after executing the following code? c1 = Counter(); c2 = Counter(); c1.increment(); c2.increment(); print(Counter.count, c1.count, c2.count)

Medium
374

Which TWO of the following are built-in Python exceptions?

Easy
375

Which TWO statements about the __init__.py file in a Python package are true?

Medium
376

Which of the following expressions raises a ValueError?

Hard
377

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
378

Refer to the exhibit. Which THREE statements about the class hierarchy are correct?

Hard
379

Which two of the following are valid ways to create a multiline string in Python source code? (Choose two.)

Easy
380

Match each variable scope to its description.

Medium
381

A developer is building a configuration parser. They have a string `line = " key = value "` and need to remove the leading and trailing spaces, then split the line at the equals sign into a list of exactly two elements: the key and the value, with any spaces around the equals sign removed. Which expression achieves this?

Medium
382

A developer wants to ensure that a file is always closed, even if an exception occurs, without using the 'with' statement. Which approach correctly achieves this?

Medium
383

Which TWO of the following operations can be performed on a string?

Easy
384

A developer writes a class `Circle` with `def __init__(self, radius): self.radius = radius` and wants printing a `Circle` instance to produce a readable description such as `Circle(5)`. Which method should be implemented, and why over the alternative?

Easy
385

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
386

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
387

Which TWO of the following are true about importing modules using the import statement?

Hard
388

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

Easy
389

A programmer wants to catch both `FileNotFoundError` and `PermissionError` with a single except clause. Which tuple is correct?

Medium
390

A programmer wants to use the sqrt function from the math module. Which import statement is most efficient?

Easy
391

A developer needs to format a floating-point number 123.456789 with exactly 2 decimal places and a width of 10 characters, right-aligned. Which format specifier accomplishes this?

Hard
392

Which TWO of the following are valid ways to define a class method in Python? (Select exactly two.)

Medium
393

A developer has a project structure with 'my_package/' containing '__init__.py', 'module_a.py', and 'sub_package/' (with its own '__init__.py'). They want to import function 'foo' from 'module_a' inside a script in 'sub_package' using a relative import. Which statement is correct?

Medium
394

A developer writes a function to reverse a string: def reverse_str(s): return s[::-1]. Which of the following statements about this function is true?

Hard
395

Consider the following directory structure: project/ main.py pkg/ __init__.py mod1.py subpkg/ __init__.py mod2.py From main.py, you write: from pkg.subpkg import mod2 Which THREE of the following are true regarding relative imports?

Medium
396

Refer to the exhibit. What will happen when the code is executed?

Medium
397

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

Medium
398

A developer needs to extract the file extension from a string like 'report.pdf'. Which string method is most appropriate?

Easy
399

A small web application allows users to download files from a server. The code uses open() without any exception handling. When a user requests a non-existent file, the server crashes with a traceback and returns a 500 Internal Server Error to the client. The team needs to modify the code to handle this situation gracefully: if the file does not exist, the application should return a 404 Not Found response (by calling a function send_404()). The application should not catch unrelated exceptions like KeyboardInterrupt. Which modification is the most appropriate?

Easy
400

A class has an attribute that should be computed on access and cached for subsequent accesses. Which pattern is most appropriate?

Easy
401

Which THREE of the following are valid escape sequences in Python strings?

Medium
402

A pipeline processes many small binary records. The developer writes a custom exception `class RecordError(Exception)` with an `__init__` that stores a record identifier and calls `super().__init__(message)`. A validation function raises `RecordError` for a corrupt record, and a worker catches it to log the identifier. The worker also wants the raw message to be available via `str(e)`. Which statement about this design is correct?

Hard
403

In a performance-critical application, you need to concatenate many strings in a loop. Which TWO approaches are most efficient?

Hard
404

A developer defines a class hierarchy with multiple inheritance: class A, class B(A), class C(A), class D(B,C). The method 'm' is defined only in A. What is the method resolution order for D according to the C3 linearization algorithm?

Medium
405

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

Hard
406

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

Medium
407

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

Easy
408

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
409

Under CPython, what is the result of the following code? a = 'hello'; b = 'hello'; print(a is b)

Hard
410

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
411

Which of the following best describes the immutability of strings in Python?

Medium
412

Which two methods can be used to remove leading whitespace from a string? (Choose two.)

Medium
413

A developer wants to ensure that a class attribute is shared across all instances. Which approach should be used?

Easy
414

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

Easy
415

Which of the following is true regarding Python's method resolution order (MRO) in multiple inheritance?

Hard
416

Which TWO of the following are valid ways to use string formatting in Python? (Choose two.)

Easy
417

A team is using inheritance but wants to prevent a method from being overridden in subclasses. What Python feature can enforce this?

Medium
418

Which TWO of the following are correct ways to raise a custom exception in Python? (Assume CustomError and CustomException are user-defined.)

Easy
419

A data scientist writes a script to parse a configuration file that contains lines in 'key=value' format. Some lines may have malformed data that cause a ValueError when trying to convert the value to an integer. The requirement is to process all valid lines and skip any that cause a ValueError, but continue processing subsequent lines. The script should log a warning for each skipped line, including the line number. Which implementation correctly fulfills this requirement? (Assume the file is opened with 'with open(...) as f'.)

Medium
420

Which THREE of the following are valid ways to import a function named 'calculate' from a module named 'math_ops' located in a subpackage 'operations' of a package 'app'?

Hard
421

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 421 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.