Courseiva

Python Institute Certified Professional in Python Programming 1 (PCPP1, PCPP-32-101) (PCPP1) (PCPP1) — Questions 76150

209 questions total · 3pages · All types, answers revealed

Page 1

Page 2 of 3

Page 3
76
MCQmedium

In the context of the Observer pattern, what is the benefit of an event-driven system over a direct-method-call approach?

A.Reduced memory usage.
B.Increased performance.
C.Decoupling between the subject and observers.
D.Automatic thread synchronization.
AnswerC

The subject maintains a generic interface for observers.

Why this answer

Decoupling is the primary benefit; the subject does not need to know the implementation details of the observers.

77
MCQmedium

You are writing to a CSV file. If your data contains the delimiter character itself (e.g., a comma in a text field), what does the csv module do by default?

A.It raises a csv.Error.
B.It quotes the field.
C.It ignores the delimiter.
D.It escapes the character with a backslash.
AnswerB

The default quoting behavior (QUOTE_MINIMAL) wraps fields containing special characters.

Why this answer

The csv module automatically wraps such fields in quotes.

78
MCQhard

When using the grid layout manager, which option allows a column to grow when the window is resized?

A.root.grid_grow(column=0, weight=1)
B.root.columnconfigure(0, weight=1)
C.root.grid_column(0, resizable=True)
D.root.set_grid(0, expand=True)
AnswerB

columnconfigure with weight > 0 makes the column resizable.

Why this answer

The columnconfigure() method is used to set the weight of a column, allowing it to expand.

79
Multi-Selecteasy

Which THREE of the following are valid HTTP request methods commonly used in RESTful API design?

Select 3 answers
A.SEND
B.DELETE
C.GET
D.POST
E.FETCH
AnswersB, C, D

Removes resources.

Why this answer

GET, POST, and DELETE are standard HTTP verbs used in RESTful interactions.

80
MCQmedium

You need to ensure your code is readable by other Python developers. Which naming style should be used for variable names?

A.UPPER_SNAKE_CASE.
B.camelCase.
C.snake_case.
D.PascalCase.
AnswerC

The standard Python convention for variables.

Why this answer

PEP 8 prescribes snake_case (lowercase with underscores) for variable and function names.

81
MCQhard

What is the purpose of the __set_name__ method in descriptors?

A.To set the name of the class.
B.To delete the attribute.
C.To rename the attribute.
D.To allow the descriptor to know its name in the owner class.
AnswerD

This is the purpose of the method.

Why this answer

__set_name__ is called at class creation time to inform the descriptor of its name in the owner class, allowing it to store values in a private attribute without needing to know the name beforehand.

82
MCQmedium

Why should you use super() instead of calling the parent class method directly by name?

A.It is required for private methods.
B.It correctly resolves the next method in the MRO.
C.It is faster.
D.It makes the code more verbose.
AnswerB

This is the correct architectural use of super().

Why this answer

super() respects the MRO and allows for cooperative multiple inheritance, whereas hard-coding the class name breaks if the hierarchy is modified.

83
Multi-Selectmedium

Which TWO of the following methods are commonly used to update a Tkinter widget's state or appearance dynamically?

Select 2 answers
A.widget.rebind()
B.widget.reload()
C.widget.refresh()
D.widget.config(state='disabled')
E.widget.insert(END, 'text')
AnswersD, E

config() is the primary method to modify widget attributes.

Why this answer

The config() method and specific widget methods like insert() are standard for updates.

84
Multi-Selecteasy

Which TWO of the following are commonly used for debugging REST API integrations?

Select 2 answers
A.Hardcoding all credentials
B.Deleting the socket library
C.Increasing the CPU clock speed
D.Using a proxy tool to inspect traffic
E.Logging the request and response headers
AnswersD, E

Tools like Wireshark/Fiddler are industry standards.

Why this answer

Logging and network monitoring tools like Wireshark/Charles are standard for identifying API issues.

85
Multi-Selectmedium

Which THREE practices are recommended when handling external libraries?

Select 3 answers
A.Install libraries globally.
B.Import all libraries at the very end of the file.
C.Use a virtual environment for every project.
D.Document dependencies in a manifest file.
E.Pin your dependencies in a requirements.txt file.
AnswersC, D, E

This keeps dependencies isolated.

Why this answer

You should use virtual environments, pin your dependencies, and document your requirements.

86
MCQeasy

When parsing XML with ElementTree, how do you retrieve the text content of an element?

A.element.content
B.element.value
C.element.get_text()
D.element.text
AnswerD

The text attribute accesses the tag's inner text.

Why this answer

The .text attribute of the Element object holds the text content.

87
MCQeasy

When is it acceptable to ignore PEP 8 guidelines?

A.Only when you disagree with the stylistic choice.
B.Never.
C.When you are writing a script that will only be used once.
D.When necessary to maintain consistency with existing code or for legacy reasons.
AnswerD

Consistency is a key tenet of the style guide.

Why this answer

PEP 8 itself states that project consistency and backward compatibility may warrant exceptions to the rules.

88
MCQmedium

When designing a public API, how should you signal that a method is for internal use only?

A.By prepending a single underscore.
B.By raising a warning if called externally.
C.By adding a comment like '# INTERNAL'.
D.By using all caps.
E.By suffixing with an underscore.
AnswerA

This is the established convention in Python.

Why this answer

Prefixing a name with a single underscore is the conventional way to indicate internal use.

89
MCQmedium

What is the purpose of the 'type' function when called with three arguments?

A.To register a class.
B.To create a new class dynamically.
C.To inherit from multiple classes.
D.To check object type.
AnswerB

The three-argument form is the type constructor for classes.

Why this answer

It is used for dynamic class creation: type(name, bases, dict).

90
MCQmedium

When writing a library, what is the best practice for documenting the usage of a function?

A.Include the documentation as comments above the function definition.
B.Use docstrings to provide a clear summary and usage details.
C.Provide usage examples in the 'README.md' file only.
D.Wait for users to ask for documentation.
AnswerB

Docstrings are the built-in standard for Python documentation.

Why this answer

Docstrings provide the most standard and accessible form of documentation that can be integrated with tools like Sphinx.

91
MCQhard

In the context of writing robust error handling, what is the 'EAFP' principle?

A.Ensure All Functions Pass.
B.Exit All Files Properly.
C.Easier to Ask for Forgiveness than Permission.
D.Evaluate All Faults Promptly.
AnswerC

This is the fundamental philosophy behind Python's exception handling.

Why this answer

EAFP stands for 'Easier to Ask for Forgiveness than Permission', which encourages using try-except blocks instead of pre-checking states.

92
Multi-Selectmedium

Which THREE of the following are valid parameters for the csv.writer constructor?

Select 3 answers
A.lineterminator
B.encoding
C.buffer_size
D.quotechar
E.delimiter
AnswersA, D, E

Valid parameter.

Why this answer

delimiter, quotechar, and lineterminator are valid parameters.

93
MCQmedium

What does the @abstractmethod decorator do when applied to a method inside an ABC?

A.It requires the subclass to implement the method.
B.It prevents the method from being called.
C.It automatically generates a default implementation.
D.It makes the method faster.
AnswerA

This is the core requirement of ABCs.

Why this answer

It marks the method as requiring an override in any non-abstract concrete subclass.

94
MCQmedium

When using abstract base classes (ABCs) from the abc module, what happens if a class inherits from an ABC but fails to implement one of the abstract methods?

A.The class will be created, but calling the missing method will raise an AttributeError.
B.The class will be marked as abstract and will raise a TypeError upon instantiation.
C.The missing method will default to a 'pass' statement.
D.The parent ABC will automatically provide a NotImplementedError.
AnswerB

This is the core behavior of ABCs; they act as templates that must be fully realized.

Why this answer

Python will raise a TypeError when you attempt to instantiate the class, preventing the creation of an incomplete object.

95
MCQhard

You are refactoring code that performs sensitive operations. Which of the following is the most secure practice for handling secret keys?

A.Use environment variables to store sensitive configuration.
B.Encrypt the secrets and store them as constants in a module.
C.Store secrets in a private class attribute.
D.Hardcode them as strings inside a 'config.py' file and ignore it in Git.
AnswerA

Environment variables keep secrets out of the source code repository.

Why this answer

Hardcoding secrets is a major security vulnerability; using environment variables is the industry standard.

96
MCQmedium

You are implementing a Singleton pattern using the __new__ method. Why is it considered best practice to also define a __call__ method in the metaclass or use a decorator instead of just overriding __new__ in the base class?

A.It prevents the creation of multiple instances during the unpickling process.
B.The __new__ method cannot accept variable arguments in Python 3.
C.The __new__ method is reserved for static methods only.
D.It is required for thread-safe access to the instance variable.
AnswerA

Using a metaclass or a decorator ensures that the instance returned during deserialization is the same one already created, maintaining the Singleton property.

Why this answer

Overriding __new__ in a base class can lead to issues with pickling and deserialization, as __new__ is called every time an object is unpickled, potentially creating multiple instances.

97
MCQmedium

What is the consequence of not calling super().__init__() in a class with multiple inheritance?

A.The class will not be created.
B.All attributes will be lost.
C.The initialization chain for parent classes is interrupted.
D.Python will raise a RuntimeError.
AnswerC

Cooperative multiple inheritance depends on every class calling super().

Why this answer

The MRO chain will break, and sibling classes may not be initialized properly, potentially causing missing attributes or logic errors.

98
MCQeasy

Which widget is most appropriate if you need to display a read-only multi-line block of text to the user?

A.difficulty
B.Text
C.Message
D.Entry
E.Label
AnswerB

The Text widget supports multiple lines and can be made read-only by setting its state.

Why this answer

The Text widget is standard for multi-line text, and setting 'state' to 'disabled' makes it read-only.

99
MCQmedium

You have a list of options and want the user to select one using a dropdown menu. Which widget should you use?

A.tk.ComboBox()
B.tk.Select()
C.tk.Dropdown()
D.tk.OptionMenu()
AnswerD

OptionMenu is the correct class for dropdowns.

Why this answer

The OptionMenu widget is the standard tool for creating a dropdown selection list.

100
MCQhard

When implementing secure coding practices in a web-facing Python application, how should you handle raw user input to prevent command injection?

A.Pass the entire input string to os.system().
B.Concatenate the input string into a shell command for execution.
C.Pass input arguments as a list to subprocess.run(args, shell=False).
D.Sanitize input using a custom regex to remove special characters.
AnswerC

This approach treats the input as data rather than an executable command string.

Why this answer

Using the 'subprocess' module with 'shell=False' (the default) prevents the shell from interpreting user-provided strings as commands.

101
MCQmedium

You want to create a Menu that contains sub-menus. Which class or method is used to add a sub-menu to an existing menu?

A.difficulty
B.menu.add_menu()
C.menu.add_cascade()
D.menu.add_command()
E.menu.add_submenu()
AnswerC

add_cascade links a sub-menu object to a menu item.

Why this answer

The add_cascade method is used to create a menu item that opens a sub-menu.

102
Multi-Selectmedium

Which THREE of the following are valid parameters for the pack() layout manager?

Select 3 answers
A.row
B.expand
C.column
D.side
E.fill
AnswersB, D, E

Specifies whether to take up extra space.

Why this answer

side, fill, and expand are standard parameters for the pack() manager.

103
MCQmedium

You are writing a library that expects a custom exception. Which practice aligns best with Python's exception handling hierarchy?

A.Use a mixin class without inheritance.
B.Inherit from StandardError.
C.Inherit from BaseException.
D.Inherit from Exception.
AnswerD

Exception is the correct base class for user-defined exceptions.

Why this answer

Custom exceptions should inherit from the built-in Exception class to ensure they are catchable by standard error handlers.

104
Multi-Selecteasy

Which TWO of the following are valid ways to read sections in a configparser object?

Select 2 answers
A.for section in parser.get_all():
B.for section in parser.keys():
C.for section in parser.read():
D.for section in parser.sections():
E.for section in parser:
AnswersD, E

The sections() method returns a list of sections.

Why this answer

You can iterate over the object or use the sections() method.

105
MCQeasy

Which magic method is triggered when an object is deleted using the 'del' keyword?

A.__clear__
B.__del__
C.__remove__
D.__destroy__
AnswerB

This is the finalizer method.

Why this answer

The __del__ method is called when the object's reference count reaches zero.

106
MCQhard

What is the result of applying the @staticmethod decorator to a method inside a class that also defines a metaclass?

A.The metaclass must manually convert it back to a static method.
B.It raises a TypeError at class definition time.
C.The method is correctly bound as a static function regardless of the metaclass.
D.The metaclass will treat the method as an instance method.
AnswerC

The descriptor logic for @staticmethod operates independently of the class-level metaclass definition.

Why this answer

The @staticmethod decorator creates a static method object which is stored in the class dictionary; it is independent of the metaclass's __init__ logic for instance methods.

107
MCQmedium

Which widget is most appropriate for displaying a list of selectable items?

A.tk.Checkbutton()
B.tk.Listbox()
C.tk.OptionMenu()
D.tk.Menu()
AnswerB

Listbox is the correct widget for a list of items.

Why this answer

The Listbox widget is intended for displaying a list of strings that the user can select.

108
Multi-Selecteasy

Which THREE of the following are components of the logging module?

Select 3 answers
A.Formatter
B.Dispatcher
C.Logger
D.Manager
E.Handler
AnswersA, C, E

Core component.

Why this answer

Loggers, Handlers, and Formatters are core components.

109
Multi-Selecthard

Which TWO of these identify a potential 'code smell' in Python exception handling?

Select 2 answers
A.Using 'finally' for cleanup.
B.Swallowing exceptions with an empty 'except' block.
C.Catching specific exceptions.
D.Catching 'BaseException' instead of 'Exception'.
E.Raising custom exceptions.
AnswersB, D

Silently failing makes debugging nearly impossible.

Why this answer

Swallowing exceptions and catching BaseException are both poor practices.

110
MCQeasy

Which of the following is the correct way to handle whitespace around an operator according to PEP 8?

A.x= y +z
B.x = y + z
C.x = y + z
D.x=y+z
AnswerB

This follows the PEP 8 spacing rule.

Why this answer

PEP 8 dictates surrounding operators with a single space on both sides.

111
MCQmedium

You are using configparser and want to access a value that might not exist, but provide a default value if it is missing. Which method is most appropriate?

A.parser.get('section', 'option', fallback='val')
B.parser.get('section', 'option', default='val')
C.parser.get_or_default('section', 'option', 'val')
D.parser.exists('section', 'option') ? ...
E.parser.get('section', 'option') or 'val'
AnswerA

The fallback parameter handles missing options gracefully.

Why this answer

The get() method accepts a 'fallback' argument to return a default value if the option is missing.

112
MCQmedium

When executing a SQL query with parameters in sqlite3, why should you use placeholders (e.g., ?) rather than f-strings?

A.It is required for SELECT queries only.
B.It enables automatic commit behavior.
C.It is faster to execute.
D.It prevents SQL injection vulnerabilities.
AnswerD

Placeholders ensure that input is treated as data, not executable code.

Why this answer

Using placeholders prevents SQL injection attacks and allows the library to handle type conversions.

113
Multi-Selecteasy

Which TWO of the following are valid geometry managers in Tkinter?

Select 2 answers
A.pack
B.block
C.align
D.flow
E.grid
AnswersA, E

pack is a standard geometry manager.

Why this answer

pack, grid, and place are the three built-in geometry managers in Tkinter.

114
MCQhard

What is the effect of setting __slots__ in a parent class on a child class that does not define its own __slots__?

A.The child class will have a __dict__ attribute, overriding the parent's optimization.
B.The child class will raise an error at instantiation.
C.The child class will inherit the memory savings automatically.
D.The child class will be unable to add new attributes.
AnswerA

By default, subclasses receive a __dict__.

Why this answer

The child class will receive an instance __dict__ unless it also defines __slots__, effectively defeating the memory optimization of the parent.

115
MCQeasy

Which class in xml.etree.ElementTree should you use to parse an XML file from a file object?

A.ElementTree.parse()
B.ElementTree.XML()
C.ElementTree.load()
D.ElementTree.read()
AnswerA

parse() reads the file into an ElementTree object.

Why this answer

The parse() function is the standard way to read XML from a file object.

116
MCQhard

When implementing a timeout in 'requests.get()', what is the consequence of setting it as a single float (e.g., timeout=5)?

A.It only limits the read phase
B.It causes an error because a tuple is expected
C.It only limits the connection phase
D.It limits both the connection and read time to 5 seconds
AnswerD

Requests interprets a single value as the timeout for both phases.

Why this answer

Providing a single value sets both the connect and read timeouts to that value.

117
MCQeasy

What is the result of using '?' as a placeholder in sqlite3 for a parameter that is a Python list?

A.It raises a ProgrammingError.
B.It automatically converts the list to a comma-separated string.
C.It works as expected.
D.It only takes the first element of the list.
AnswerA

Passing a list where a single value is expected (or using a single placeholder for multiple values) causes a mapping error.

Why this answer

sqlite3 does not automatically expand lists; you must use a tuple of values or construct the SQL dynamically.

118
MCQmedium

When working with raw sockets, what does the 'socket.SOCK_STREAM' constant represent?

A.UDP datagram sockets
B.Raw network sockets
C.TCP connection-oriented sockets
D.Unix domain sockets only
AnswerC

SOCK_STREAM provides sequenced, reliable, two-way byte streams.

Why this answer

SOCK_STREAM is used for TCP connections, which are connection-oriented and reliable.

119
MCQeasy

Which standard Python library module is used for lower-level networking and creating server/client sockets?

A.http.server
B.requests
C.networking
D.socket
AnswerD

This is the built-in networking module.

Why this answer

The 'socket' module is the standard low-level interface to the network stack.

120
Multi-Selecthard

Which THREE of the following are potential pitfalls of the Singleton pattern in Python?

Select 3 answers
A.They cannot be used with inheritance.
B.They introduce global state.
C.They cause difficulties in dependency injection.
D.They make unit testing more difficult.
E.They are always thread-safe.
AnswersB, C, D

Singletons are global by definition.

Why this answer

Singletons can be hard to test, cause hidden global state, and create difficulties in multi-threaded environments.

121
MCQmedium

You are parsing a JSON response that contains a large list of objects. Which technique is most memory-efficient for processing these objects?

A.Convert the entire JSON to a string then split
B.Use the 'json.loads()' method on the full response
C.Iterate through the list object after parsing
D.Use a custom regex to parse the JSON
AnswerC

Accessing the list is efficient, though the full structure is loaded.

Why this answer

If you have control over the response, streaming the JSON or processing it iteratively (if supported by the parser) saves memory.

122
Multi-Selecthard

Which THREE of the following widgets are part of the 'ttk' (Themed Tkinter) module?

Select 3 answers
A.ttk.Entry
B.ttk.Button
C.ttk.Label
D.ttk.Window
E.ttk.Canvas
AnswersA, B, C

Themed entry widget.

Why this answer

ttk.Button, ttk.Label, and ttk.Entry are part of the themed widget set, whereas standard tkinter widgets are in the top-level tkinter module.

123
MCQmedium

How do you implement the 'Strategy' pattern in Python?

A.By using a large switch-case statement.
B.By creating a metaclass for all strategies.
C.By passing strategy instances into the context constructor.
D.By using inheritance for every strategy.
AnswerC

Dependency injection is a key part of the Strategy pattern.

Why this answer

By injecting different strategy objects into a context class, which then delegates operations to the injected object.

124
MCQeasy

Which module must be imported to utilize Tkinter in a Python script?

A.import tkinter
B.import gui
C.from python import gui
D.import tk
AnswerA

This is the correct module name.

Why this answer

The 'tkinter' module is the standard Python interface to the Tk GUI toolkit.

125
MCQmedium

When designing a class hierarchy, what is the best way to prevent a method from being overridden by subclasses?

A.Defining it as a private method.
B.Defining it as a static method.
C.Using the @final decorator from typing.
D.Using the 'final' keyword.
AnswerC

The @final decorator is the standard way to indicate that a method should not be overridden.

Why this answer

Python does not have a native 'final' keyword, but naming conventions (e.g., __method) or raising errors in the subclass can be used, though it is often discouraged in favor of clear documentation.

126
MCQeasy

You have a Button widget and want to trigger a function named 'process_data' when the user clicks it. Which is the standard way to associate the function with the button?

A.button = Button(root, event=process_data)
B.button.bind('<Button-1>', process_data)
C.button = Button(root, command=process_data)
D.button.set_action(process_data)
AnswerC

The 'command' parameter is designed specifically for triggering functions on button clicks.

Why this answer

The 'command' parameter is the standard way to bind a callback function to a button click event.

127
Multi-Selecthard

Which THREE of the following are valid methods of the xml.etree.ElementTree.Element class?

Select 3 answers
A.find()
B.write()
C.append()
D.set()
E.to_string()
AnswersA, C, D

Valid method for searching children.

Why this answer

The methods find(), set(), and append() are part of the Element API.

128
Multi-Selectmedium

Which TWO of the following are potential pitfalls when using multithreading for network operations in Python?

Select 2 answers
A.Race conditions when accessing shared state
B.The GIL prevents true parallelism for CPU-bound tasks
C.Threads always execute slower than single-threaded code
D.Threads consume more memory than processes
E.Socket objects are automatically thread-safe
AnswersA, B

Shared memory across threads often requires locking.

Why this answer

Global Interpreter Lock (GIL) limitations and race conditions on shared objects are common issues in Python multithreading.

129
MCQhard

How should one handle the 'KeyboardInterrupt' exception if it must be caught for cleanup purposes?

A.Catch it, clean up resources, and then use 'raise'.
B.Prevent it by setting a signal handler for SIGINT.
C.Use a bare 'except:' clause.
D.Catch it and ignore it to keep the app running.
AnswerA

This pattern allows for cleanup while respecting the user's intent to exit.

Why this answer

You should catch it, perform the cleanup, and then re-raise it so the application still shuts down gracefully.

130
MCQmedium

How do you correctly call a method from a sibling class in a diamond inheritance structure using super()?

A.Call the grandparent class directly.
B.Use super() in each class to delegate to the next class in the MRO.
C.Use the __bases__ attribute to iterate through parents.
D.Explicitly call the sibling class method by name.
AnswerB

super() ensures that each class in the MRO is initialized exactly once.

Why this answer

super() follows the Method Resolution Order (MRO), which correctly handles diamond inheritance by delegating calls to the next class in the chain, not just the parent.

131
MCQmedium

You are using the sqlite3 module to manage a database. You need to ensure that database changes are permanently saved even if your script terminates unexpectedly. Which method should you call after an INSERT operation?

A.connection.save()
B.cursor.flush()
C.connection.close()
D.connection.commit()
AnswerD

The commit() method persists changes to the database.

Why this answer

The commit() method on a connection object is required to save changes permanently in sqlite3.

132
Multi-Selecteasy

Which TWO of the following are valid ways to create a connection in the sqlite3 module?

Select 2 answers
A.sqlite3.connect(':memory:')
B.sqlite3.Connection('my_db.sqlite')
C.sqlite3.connect('my_db.sqlite')
D.sqlite3.new_db('my_db.sqlite')
E.sqlite3.open('my_db.sqlite')
AnswersA, C

Creates an in-memory database.

Why this answer

You can connect using a path string or the special ':memory:' string.

133
Multi-Selecteasy

Which THREE of the following are standard ways to handle API authentication?

Select 3 answers
A.OAuth 2.0
B.API Keys
C.Public IP Whitelisting
D.Basic Authentication
E.Hardcoding passwords in code
AnswersA, B, D

Standard for delegated authorization.

Why this answer

API Keys, OAuth tokens, and Basic Authentication are the most common methods for securing REST APIs.

134
MCQhard

When documenting a complex function, which approach is most compliant with Google Style Python Docstrings regarding parameter types?

A.Use the 'Args:' section followed by the parameter name, type, and description.
B.Embed the types directly in the function name.
C.Include type hints in the docstring but omit them from the function signature.
D.Avoid documenting types to prevent redundancy with type hints.
AnswerA

This is the standard format for Google-style docstrings.

Why this answer

Google Style requires explicit listing of types in the Args section to improve readability for static analysis tools.

135
Multi-Selectmedium

Which TWO of the following are correct regarding the 'with' statement in Python?

Select 2 answers
A.It works by implicit __init__ calling.
B.It only works with file objects.
C.It can be used with any object.
D.It requires the class to define __enter__ and __exit__.
E.It guarantees that __exit__ is called even if an exception occurs.
AnswersD, E

These are the mandatory methods.

Why this answer

The 'with' statement handles setup and teardown, and it requires both __enter__ and __exit__.

136
MCQhard

You are investigating a network bottleneck in your Python application using `requests`. If you aren't using a `Session` object, what performance-related behavior should you expect?

A.Each request will perform a full TCP handshake
B.The application will use more memory
C.Connection pooling will be enabled by default
D.The server will block your IP immediately
AnswerA

Creating new connections is expensive.

Why this answer

Without a Session, each request creates a new TCP connection, incurring the cost of a three-way handshake every time.

137
MCQmedium

In the context of the Factory pattern, what does a concrete factory implement?

A.The registration logic for all factories.
B.The creation interface for specific product variants.
C.The logic for the singleton pattern.
D.The product logic.
AnswerB

This is the essence of a concrete factory.

Why this answer

A concrete factory implements the interface defined by the abstract factory to produce specific products.

138
MCQmedium

In the csv module, how do you specify that the CSV file uses a semicolon (;) as a delimiter?

A.csv.reader(f, char=';')
B.csv.reader(f, sep=';')
C.csv.reader(f, quotechar=';')
D.csv.reader(f, delimiter=';')
AnswerD

This sets the correct field delimiter.

Why this answer

The delimiter parameter in the csv.reader or csv.writer function is used for this purpose.

139
MCQmedium

When implementing the Singleton pattern, what is the advantage of using a module-level instance over a class-based Singleton?

A.It is more secure.
B.It allows multiple instances if needed.
C.It is simpler and leverages Python's built-in module caching mechanism.
D.It supports lazy loading.
AnswerC

Modules are cached in sys.modules, making them thread-safe and singular by design.

Why this answer

Python modules are naturally Singletons because they are initialized only once upon the first import.

140
MCQeasy

What is the purpose of the __repr__ method?

A.To be called by print().
B.User-friendly output.
C.To store the object in memory.
D.Unambiguous representation for debugging.
AnswerD

This is the intended goal of __repr__.

Why this answer

It provides a formal, unambiguous string representation of an object, ideally suitable for re-creating the object.

141
MCQmedium

What is the primary benefit of using 'logging' over 'print' statements for application diagnostics?

A.It is faster for small scripts.
B.It prevents the application from crashing on errors.
C.It allows setting severity levels and routing logs to different handlers.
D.It automatically cleans up log files.
AnswerC

This is the core advantage of a structured logging system.

Why this answer

The 'logging' module provides granular control over levels, destinations, and output formatting without changing the source code.

142
MCQmedium

Which logging configuration would effectively suppress all log messages?

A.logging.disable(logging.CRITICAL + 1)
B.logging.basicConfig(level=0)
C.logging.disable(logging.CRITICAL)
D.logging.getLogger().setLevel(logging.NOTSET)
AnswerA

This disables all logs below the provided level.

Why this answer

Setting the level to logging.CRITICAL + 1 (or any value higher than the highest defined level) suppresses all logs.

143
MCQhard

Why does the 'abc' module provide the 'ABCMeta' metaclass?

A.To allow private methods.
B.To improve method resolution speed.
C.To enforce abstract method implementation at instantiation.
D.To support multiple inheritance.
AnswerC

This is the core purpose of ABCMeta.

Why this answer

ABCMeta is the metaclass that implements the logic to prevent instantiation of classes with abstract methods.

144
MCQmedium

Which method in the xml.dom.minidom module is used to retrieve the value of a specific attribute of an element?

A.element.attr('attr_name')
B.element.getAttribute('attr_name')
C.element.getAttributeNode('attr_name').value
D.element.value('attr_name')
E.element['attr_name']
AnswerB

This is the correct method for accessing attributes in DOM nodes.

Why this answer

The getAttribute() method is used to retrieve the value of an attribute by its name.

145
MCQmedium

You want to execute multiple SQL statements at once in sqlite3. Which method should you use?

A.cursor.executescript()
B.connection.execute_all()
C.cursor.execute_script()
D.cursor.execute_many()
AnswerA

executescript() executes a script containing multiple SQL statements.

Why this answer

The executescript() method allows executing multiple SQL statements separated by semicolons.

146
MCQmedium

When using the 'socket' module, what is the effect of calling 'socket.settimeout(5.0)' on a socket object?

A.It sets the send buffer size to 5.0 bytes
B.It causes the operation to raise a socket.timeout after 5 seconds
C.It blocks the thread for exactly 5 seconds
D.It forces the socket to close after 5 seconds of inactivity
AnswerB

This is the correct behavior for blocking operations.

Why this answer

The settimeout() method sets a timeout in seconds for subsequent socket operations. If the operation does not complete within the time, a socket.timeout exception is raised.

147
Multi-Selectmedium

Which THREE of the following are valid states/modes for the csv.QUOTE_* constants?

Select 3 answers
A.csv.QUOTE_NONE
B.csv.QUOTE_ALL
C.csv.QUOTE_EVERYTHING
D.csv.QUOTE_AUTO
E.csv.QUOTE_MINIMAL
AnswersA, B, E

Valid constant.

Why this answer

QUOTE_ALL, QUOTE_MINIMAL, and QUOTE_NONE are valid constants.

148
MCQhard

In Python socket programming, what does the 'SO_REUSEADDR' socket option achieve?

A.It speeds up data transmission
B.It allows the address to be reused immediately after the server stops
C.It enables broadcasting on the socket
D.It prevents the socket from closing
AnswerB

This avoids 'Address already in use' errors.

Why this answer

It allows the socket to bind to a port that is in a TIME_WAIT state, commonly used to restart servers quickly.

149
Multi-Selecteasy

Which THREE elements are essential for a good Python docstring?

Select 3 answers
A.A detailed description of the logic.
B.A list of all possible variable types in the code.
C.A brief summary of the object's purpose.
D.A blank line following the summary line.
E.The full source code of the function.
AnswersA, C, D

Helps clarify complex behavior.

Why this answer

A summary line, a blank line, and a detailed description are standard.

150
MCQeasy

According to PEP 8, what is the maximum recommended length for a line of code?

A.79 characters.
B.80 characters.
C.No limit.
D.120 characters.
AnswerA

This is the exact PEP 8 recommendation.

Why this answer

PEP 8 suggests limiting lines to 79 characters to allow multiple files to be opened side-by-side.

Page 1

Page 2 of 3

Page 3

All pages