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.
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.
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?
Medium2Refer to the exhibit. What happens when the code is executed?
Medium3Given 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?
Medium4A 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?
Easy5A 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?
Hard6A 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'?
Hard7A 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?
Easy8Which THREE of the following are immutable types in Python?
Medium9A 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?
Easy10What happens when you execute the following code? s = 'hello'; s[0] = 'H'
Hard11A 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.
Easy12A 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?
Hard13Which 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?
Easy14Refer to the exhibit. What is the output? (Note: actual MRO may vary; choose the one that matches Python 3 C3 linearization.)
Hard15Which method of a file object reads the entire content of a text file as a single string?
Easy16Drag and drop the steps to handle an exception in Python using try-except-finally into the correct order.
Medium17A 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?
Easy18Drag and drop the steps to define and call a function with default arguments in Python into the correct order.
Medium19A programmer writes a class with a method that should be called on the class itself, not on instances. Which decorator is appropriate?
Easy20A 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?
Medium21You 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?
Hard22A team is developing a large application and wants to organize code into packages. Which of the following is a best practice for package design?
Medium23What is the cause of the error?
Medium24A class 'MyClass' has a method 'do_something' that uses 'self.__private'. A subclass 'MySubClass' tries to access 'self.__private' and gets an AttributeError. Why?
Hard25Consider the following code: print(type('apple,banana,cherry'.split(','))) What type of value is printed?
Easy26A 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?
Medium27You 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?
Hard28A 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?
Easy29A 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?
Medium30A 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?
Medium31A developer needs to write a function that safely divides two numbers and returns None if division by zero occurs. Which implementation is most Pythonic?
Medium32Which TWO statements about exception handling in Python are correct? (Select exactly 2.)
Medium33Which THREE of the following statements about Python's module search path are true?
Hard34Match each Python data structure to its mutability.
Medium35You 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?
Hard36What is the result of 'PyThon'.lower()?
Easy37A 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?
Hard38What is the result of the expression 'Hello' * 3?
Easy39Which THREE of the following string methods return a boolean value (True or False)? (Choose exactly 3 correct answers.)
Medium40What is the output of the following code? try: exec('1/0') except: print('error') else: print('no error') finally: print('done')
Hard41Which of the following is the BEST practice for building a large string by concatenating many smaller strings in Python?
Easy42Refer to the exhibit. What is printed?
Hard43A 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?
Easy44Refer to the exhibit. Which of the following fixes the error?
Medium45A 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?
Hard46A 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?
Medium47A 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?
Medium48Which TWO statements are true regarding strings in Python?
Medium49A 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?
Medium50Given that MyClass defines __private_attr in __init__, why does this error occur?
Medium51A 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?
Hard52A developer writes code to display a floating-point number with exactly two decimal places. Which f-string expression is correct for value = 3.14159?
Medium53You 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?
Hard54A 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`?
Medium55Which THREE of the following exception types are subclasses of OSError in Python 3?
Hard56A 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?
Easy57A 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?
Easy58You 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?
Hard59A 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?
Hard60Which TWO string methods are used to determine if a string begins or ends with a specified prefix or suffix? (Choose two.)
Easy61Refer to the exhibit. What will be the output when the code is executed?
Medium62A 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.)
Medium63A programmer wants to restrict a class to only allow specific attribute names and reduce memory usage. Which feature should they use?
Hard64Which TWO statements about the 'from package import *' statement are correct?
Easy65Match each code snippet to its output.
Medium66Refer 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?
Medium67Which THREE factors can cause an 'ImportError' when trying to import a module?
Hard68A 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?
Hard69A 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?
Hard70A 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?
Medium71Refer to the exhibit. What happens when the last command is executed?
Hard72A developer wants to check if a string 'example.txt' ends with '.txt'. Which expression returns True?
Easy73A 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?
Hard74What is the most likely cause of this error?
Medium75A 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'?
Hard76A 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?
Medium77A 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?
Medium78A 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?
Medium79What will be printed?
Medium80Which of the following statements about the `finally` block is true?
Easy81A developer wants to create a class that logs every attribute access on an instance. Which special method should they override?
Easy82What does the expression 'hello world'.title() return?
Medium83Match each string method to its purpose.
Medium84A 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?
Medium85A class defines an __init__ method that takes optional arguments. What is the correct way to provide default values?
Easy86What is the value of matches?
Hard87Which TWO of the following statements about Python classes are true? (Select exactly 2.)
Medium88A 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?
Easy89Which 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?
Hard90Which TWO of the following string methods return a new string with all characters converted to lowercase? (Select exactly two.)
Medium91A 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?
Easy92A class has both `@classmethod` and `@staticmethod` decorators. What is a key difference between them?
Medium93A 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?
Hard94Which THREE of the following are true about Python strings?
Medium95What is the result of 'abcdef'[::-2]?
Hard96A 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?
Easy97Drag and drop the steps to create and activate a virtual environment in Python into the correct order.
Medium98During 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?
Medium99Refer to the exhibit. Which of the following Python code snippets would generate this error?
Medium100Which of the following correctly uses `__slots__` to restrict attribute creation to only `x` and `y`?
Hard101A 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?
Medium102A 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?
Hard103A developer wants to convert a string 'Python' to all uppercase letters. Which string method should be used?
Easy104Which TWO of the following are correct statements about the 'with' statement in Python file I/O?
Easy105A team is using a shared Python environment where multiple projects have conflicting dependencies. Which approach is the best practice to isolate project dependencies?
Easy106A class defines a variable `count = 0`. An instance modifies `self.count = 5`. What is the value of `count` in the class namespace?
Easy107A 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?
Easy108What is the output of `print('-'.join(['a', 'b', 'c']))`?
Easy109A 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?
Hard110A 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?
Easy111A subclass overrides a method but wants to call the parent class's version. Which keyword should be used?
Easy112You 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?
Medium113Match each Python operator to its precedence level (1=highest).
Medium114A 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?
Medium115A 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?
Medium116A developer is building a large string by concatenating many substrings in a loop using '+'. What is the main performance issue?
Hard117A 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?
Easy118Match each Python module to its purpose.
Medium119Consider 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)?
Hard120Which TWO of the following are true about the 'with' statement in Python file I/O?
Medium121Which three statements about the Method Resolution Order (MRO) in Python are true? (Choose three.)
Medium122A 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?
Easy123A programmer writes a function to check if a string is a palindrome (ignoring case and non-alphanumeric characters). Which implementation correctly achieves this?
Medium124A developer wants a class 'Point' to have a readable string representation that returns 'Point(x, y)'. Which special method should be overridden?
Easy125A 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?
Hard126An 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?
Medium127In 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?
Easy128What is the output of the code?
Medium129A 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?
Easy130A 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?
Medium131Match each exception to its cause.
Medium132A 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?
Medium133A developer wants to remove all leading and trailing whitespace from a string, but preserve internal spaces. Which line of code accomplishes this?
Medium134Which TWO methods are valid ways to import a function named 'foo' from a module 'bar' that is part of a package 'pkg'?
Medium135Refer to the exhibit. If both data.txt and backup.txt do not exist, what is the output?
Hard136Given s = 'Python', which THREE of the following expressions evaluate to True? (Choose three.)
Hard137A beginner programmer writes: name = "Alice"; print("Hello " + name). Which string method alternative is more efficient and recommended for Python 3?
Easy138A 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?
Easy139A 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?
Medium140A 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?
Medium141A 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?
Easy142A 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?
Hard143A 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?
Easy144A 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?
Medium145A developer wants to check if a string contains only alphabetic characters. Which string method should be used?
Easy146You 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?
Hard147Which TWO of the following methods return a boolean value?
Medium148Which TWO of the following statements about class attributes in Python are true?
Easy149A 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?
Medium150A 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?
Hard151Your 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?
Medium152A 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?
Easy153A 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?
Easy154Which of the following correctly uses an abstract base class to enforce that all subclasses implement a 'make_sound' method? (Assume ABC imported)
Hard155Which method returns the lowest index where a specified substring is found, or -1 if not found?
Medium156A 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?
Hard157Which TWO of the following are special methods in Python?
Easy158Refer 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?
Medium159Given s = 'Python', what is s[1:4]?
Medium160A 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?
Medium161A developer writes a log message with variables: name = 'Alice' and age = 30. Which of the following uses an f-string correctly?
Medium162Refer to the exhibit. What is the effect of using 'from None' in the raise statement?
Hard163A 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?
Medium164Consider the following code: name = "Alice" age = 30 print(f"{name} is {age} years old.") What is the output of the above code?
Easy165Given: 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()?
Medium166Which TWO of the following string methods return a boolean value (True or False)?
Medium167Which TWO string methods raise an exception when the searched substring is not found?
Easy168Which TWO statements about Python strings are correct? (Choose exactly 2 correct answers.)
Hard169Which TWO of the following statements about Python packages are true?
Medium170A developer wants to check if a string 'racecar' is a palindrome by comparing it to its reverse. Which code completes the task correctly?
Easy171A developer needs to check if a string contains only alphanumeric characters. Which string method should be used?
Easy172Which of the following correctly raises a new exception while preserving the original traceback?
Hard173A 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?
Hard174What is the likely outcome of running the following code? ```python with open("C:\Users\path\file.txt", "r") as f: print(f.read()) ```
Hard175Which TWO of the following are valid ways to import specific names from a module?
Easy176A 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?
Hard177You 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?
Medium178Which three of the following statements about Python strings are true? (Choose three.)
Hard179What is the output of the code in the exhibit?
Easy180A 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?
Medium181Which of the following is the correct way to open a file for writing in binary mode?
Easy182A 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?
Medium183A 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?
Easy184Given the code: s = 'Python'; t = s; s = s + '3.0'. What is the value of t after these lines execute?
Hard185A 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?
Easy186Which TWO of the following are built-in exceptions in Python? (Select exactly 2.)
Easy187What is the output of the Python code after reading the config.txt file?
Hard188What is the output?
Easy189A 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?
Medium190Consider 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?
Easy191Which THREE are valid ways to create a multiline string in Python?
Medium192Refer to the exhibit. What is the output?
Hard193Which TWO of the following are valid ways to define a property in a Python class? (Select exactly 2.)
Easy194Which of the following expressions returns True if the string s contains only hexadecimal digits (0-9, a-f, A-F)?
Hard195A 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?
Medium196An 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?
Hard197Which THREE statements about the Python method resolution order (MRO) are true? (Select exactly 3.)
Hard198Match each Python built-in function to its description.
Medium199A 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?
Easy200Which TWO statements about static methods (@staticmethod) are correct?
Easy201Given s = 'a1b2c3', which TWO of the following expressions return the string '123'?
Hard202A 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?
Hard203Which THREE of the following are true about Python's object-oriented programming features?
Hard204A 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?
Medium205A 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?
Hard206Which THREE of the following are true about Python's exception hierarchy?
Hard207A 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?
Easy208Which TWO of the following can be used to remove leading whitespace (spaces, tabs, newlines) from a string? (Choose exactly 2 correct answers.)
Medium209Which of the following statements about class inheritance in Python are true? (Choose two.)
Easy210A 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?
Easy211When importing a module, Python searches for it in a specific order. Which of the following lists the correct order of directories searched?
Medium212Which TWO of the following statements about Python's `sys.path` are true?
Hard213A developer wants to remove leading and trailing whitespace from a string. Which method should be used?
Medium214A 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?
Easy215A 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?
Hard216A 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?
Hard217Which THREE of the following are true about the __pycache__ directory?
Medium218Which of the following is the correct way to format a string to include a variable value with two decimal places in Python?
Medium219Which of the following is a valid way to import a module named 'math' and assign it an alias 'm'?
Easy220A developer needs to check if a filename starts with the prefix 'report_'. Which string method should be used?
Easy221Which TWO of the following string methods return a boolean value?
Easy222A 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`?
Medium223A developer wants to import a specific function 'calculate' from a module named 'formulas' without importing the entire module. Which import statement should be used?
Easy224An 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?
Hard225When should you raise a specific exception class rather than a generic Exception?
Hard226An 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?
Medium227A 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?
Easy228A user runs script.py and gets the above error: ModuleNotFoundError: No module named 'mypackage'. Which of the following is the most likely cause?
Easy229Which THREE of the following are true about the `with` statement for file handling?
Hard230A file is opened with open('test.txt', 'r'). The file object's tell() method returns 0. After reading 10 characters, what does tell() return?
Medium231A 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.)
Medium232Which TWO statements about namespace packages are true?
Medium233A 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?
Medium234Consider 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?
Medium235You 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?
Medium236A 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?
Medium237A 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?
Hard238Given 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?
Hard239A programmer has a string 'apple,banana,orange' and wants to get a list ['apple', 'banana', 'orange']. Which method should be used?
Easy240A 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?
Easy241A developer runs pip install package==1.0 and gets the above error. What is the most likely solution?
Medium242A programmer has a string s = 'Python programming is fun'. They want to extract the word 'programming'. Which slicing expression achieves this?
Medium243A 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?
Hard244A 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?
Medium245Drag and drop the steps to perform unit testing with the unittest framework in Python into the correct order.
Medium246A 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?
Medium247Which THREE of the following statements about Python's 'with' statement are true? (Select exactly 3)
Hard248Drag and drop the steps to serialize a Python object to JSON using the json module into the correct order.
Medium249What is the result of the expression 'aBc'.lower()?
Easy250A 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?
Medium251A 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?
Hard252Which THREE of the following are true about the `__init__` method in Python?
Medium253A 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?
Medium254What is the output of the following code? try: print(1/0) except: print('err') finally: print('fin')
Medium255What is the output of 'hello'.count('l')?
Easy256Which of the following demonstrates that strings are immutable?
Medium257A 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?
Hard258A 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`?
Medium259A 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?
Hard260Which TWO of the following are valid uses for the '__name__' variable in a Python module?
Easy261Which TWO statements about the sys module are true?
Medium262What is the result of 'Python'.find('th')?
Medium263A 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?
Easy264When a class defines both __getattr__ and __getattribute__, which one is called when accessing an attribute that exists in the instance?
Hard265A 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?
Medium266A class MyClass defines __str__ and __repr__ methods. What is the purpose of __repr__?
Easy267A developer runs 'pip install mypackage' but gets a 'PermissionError'. Which command should be used to install the package for the current user only?
Hard268Drag and drop the steps to debug a Python script using pdb into the correct order.
Medium269A 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?
Easy270A 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?
Medium271Refer to the exhibit. Which of the following correctly shows the MRO of class D?
Medium272A user entered a string ' Hello, World! '. Which expression returns 'Hello, World!'?
Easy273Which TWO statements about Python's name mangling are correct?
Hard274Which THREE methods return a boolean value?
Hard275A 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?
Medium276A 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?
Medium277A 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?
Medium278A 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?
Hard279A developer defines a class with a private attribute `_value` and wants to provide controlled access. Which approach is the most Pythonic?
Easy280Which THREE of the following are characteristics of Python's special methods (dunder methods)? (Select exactly three.)
Hard281A 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?
Hard282When 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?
Medium283A developer writes: s = 'abc'; s[0] = 'x'. What happens?
Hard284Drag and drop the steps to create a simple HTTP server using the http.server module in Python into the correct order.
Medium285Which THREE of the following are valid ways to create a string in Python?
Hard286Which of the following expressions returns the string 'Hello' repeated three times?
Easy287Which mode should be used when opening a file for writing such that new content is appended to the end without truncating existing content?
Easy288Which expression returns the last character of string s?
Easy289Match each list method to its effect.
Medium290Which THREE of the following escape sequences are valid in a Python string and represent a single character? (Select exactly three.)
Hard291Which string method would you use to check if a string starts with a specified prefix?
Easy292Consider 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?
Medium293Refer to the exhibit. Which of the following is the most likely cause of this error?
Medium294A 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?
Easy295Refer to the exhibit. What does the 'from None' clause do in the second raise statement?
Hard296Inside 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'?
Medium297Which of the following exception classes is NOT a direct subclass of Exception in Python?
Hard298Refer to the exhibit. If the file config.cfg exists but the user does not have read permission, what will be printed?
Easy299Refer to the exhibit. Given the project structure, which of the following import statements in main.py would cause an ImportError?
Medium300What is the result of the expression '123'.zfill(5)?
Hard301A 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?
Easy302Which TWO of the following are appropriate techniques for logging exception details in Python? (Select exactly 2)
Medium303Consider 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?
Hard304Refer to the exhibit. What is the output of the code?
Medium305What will the above code output?
Medium306Given the code above, what is printed? Note: each backslash is a single character.
Hard307A 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?
Hard308Refer 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)?
Hard309A 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.)
Medium310Consider the following code snippet: s = 'abcdefgh'; result = s[7:3:-2]; print(result). What is the output?
Hard311A 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?
Hard312You 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?
Medium313Which THREE of the following string methods can be used to split a string into a list of substrings? (Choose three.)
Medium314A programmer wants to create a package named 'analytics' with subpackages 'statistics' and 'ml'. Which directory structure correctly defines these packages?
Easy315A developer writes: print('{:,}'.format(1234567)). What is the output?
Hard316Refer to the exhibit. What is the output of the last line?
Hard317A script runs: import sys; print(sys.path[0]). The output is an empty string. What does this indicate?
Hard318A 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?
Medium319Which TWO of the following are valid string methods in Python?
Easy320Refer to the exhibit. What happens when the last line is executed?
Easy321A 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?
Medium322Which THREE of the following statements about Python packages and modules are true?
Hard323Refer 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?
Easy324Refer 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) ```
Hard325A 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?
Medium326A 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?
Hard327A developer needs to extract the file extension from a filename like 'document.pdf'. Which expression returns 'pdf'?
Hard328What is the result of the expression '12345'[:10]?
Easy329A 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?
Hard330A 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?
Easy331Which of the following best describes the use of the @abstractmethod decorator in Python?
Hard332A 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?
Hard333A 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?
Easy334A class 'Point' is defined with __slots__ = ['x', 'y']. A developer creates an instance p = Point() and tries to set p.z = 10. What happens?
Medium335Refer to the exhibit. If /var/data/in.csv does not exist, what exception is raised?
Medium336Given the string 'Python', what is the result of 'Python'[::-1]?
Hard337A 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?
Hard338A 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?
Easy339A 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?
Easy340Consider 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?
Medium341Which TWO of the following expressions evaluate to `True`? (Select exactly two.)
Easy342Which string method can be used to check if a string contains only digits?
Easy343Consider the following code: result = ' '.join(['a', 'b', 'c']) print(repr(result)) What is the output?
Hard344Refer to the exhibit. A Python script uses re.split with a regex pattern. What is the output?
Hard345A 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?
Hard346A 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?
Hard347Consider the following code: print('"age": 30,')
Hard348Which TWO of the following string methods return a new string without modifying the original?
Easy349Which TWO of the following are valid ways to read a file line by line without loading the entire file into memory?
Medium350What is the output of the following code? s = 'Hello'; print(s.find('l'))
Medium351Refer to the exhibit. What is the root cause of the error?
Hard352You 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?
Medium353A programmer wants to create a class that cannot be instantiated directly, only through a factory method. Which approach should be used?
Medium354Which THREE of the following expressions return the string "Python"? (Choose three.)
Hard355Which TWO of the following are immutable in Python?
Easy356Consider 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?
Hard357A 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?
Easy358A 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?
Hard359A 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?
Easy360What will be the output of the following code? try: print(1/0) except: print('error') else: print('no error') finally: print('done')
Easy361Which TWO of the following string methods modify the string in place? (Note: Python strings are immutable.)
Medium362Which 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?
Easy363A 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?
Easy364A 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?
Medium365Which THREE are valid escape sequences in Python strings?
Hard366Which TWO statements about method overriding in Python are correct?
Medium367Which THREE of the following are valid string methods in Python? (Choose three.)
Medium368What is the result of the expression 'Hello'[1:3]?
Easy369What is the output of the following code? try: raise ValueError('a') except ValueError as e: print(e.args[0]) finally: print('b')
Hard370A 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?
Hard371A developer wants to ensure that the 'radius' attribute of a Circle class is always non-negative. Which implementation using @property is correct?
Hard372A 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?
Hard373A 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)
Medium374Which TWO of the following are built-in Python exceptions?
Easy375Which TWO statements about the __init__.py file in a Python package are true?
Medium376Which of the following expressions raises a ValueError?
Hard377A 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?
Easy378Refer to the exhibit. Which THREE statements about the class hierarchy are correct?
Hard379Which two of the following are valid ways to create a multiline string in Python source code? (Choose two.)
Easy380Match each variable scope to its description.
Medium381A 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?
Medium382A 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?
Medium383Which TWO of the following operations can be performed on a string?
Easy384A 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?
Easy385A 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?
Medium386A 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?
Hard387Which TWO of the following are true about importing modules using the import statement?
Hard388A developer wants to check if a string ends with a specific suffix. Which method should be used?
Easy389A programmer wants to catch both `FileNotFoundError` and `PermissionError` with a single except clause. Which tuple is correct?
Medium390A programmer wants to use the sqrt function from the math module. Which import statement is most efficient?
Easy391A 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?
Hard392Which TWO of the following are valid ways to define a class method in Python? (Select exactly two.)
Medium393A 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?
Medium394A 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?
Hard395Consider 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?
Medium396Refer to the exhibit. What will happen when the code is executed?
Medium397A developer tries to modify a string: s = 'hello'; s[0] = 'H'. What happens when this code runs?
Medium398A developer needs to extract the file extension from a string like 'report.pdf'. Which string method is most appropriate?
Easy399A 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?
Easy400A class has an attribute that should be computed on access and cached for subsequent accesses. Which pattern is most appropriate?
Easy401Which THREE of the following are valid escape sequences in Python strings?
Medium402A 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?
Hard403In a performance-critical application, you need to concatenate many strings in a loop. Which TWO approaches are most efficient?
Hard404A 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?
Medium405Which TWO of the following are valid ways to define a class attribute that is shared among all instances?
Hard406A developer is implementing a custom exception for invalid data. Which class should the custom exception inherit from?
Medium407A 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?
Easy408A 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?
Medium409Under CPython, what is the result of the following code? a = 'hello'; b = 'hello'; print(a is b)
Hard410A 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?
Hard411Which of the following best describes the immutability of strings in Python?
Medium412Which two methods can be used to remove leading whitespace from a string? (Choose two.)
Medium413A developer wants to ensure that a class attribute is shared across all instances. Which approach should be used?
Easy414A programmer writes a function that expects a string and returns it reversed. Which code snippet correctly reverses the string 'stressed' to 'desserts'?
Easy415Which of the following is true regarding Python's method resolution order (MRO) in multiple inheritance?
Hard416Which TWO of the following are valid ways to use string formatting in Python? (Choose two.)
Easy417A team is using inheritance but wants to prevent a method from being overridden in subclasses. What Python feature can enforce this?
Medium418Which TWO of the following are correct ways to raise a custom exception in Python? (Assume CustomError and CustomException are user-defined.)
Easy419A 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'.)
Medium420Which 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'?
Hard421Which of the following statements about the __init__.py file in a package is true?
EasyOther domains
All PCAP exam domains
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.