Courseiva

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

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

Page 2

Page 3 of 3

151
Multi-Selecthard

Which THREE of the following represent common issues when using __slots__?

Select 3 answers
A.Subclasses must define their own __slots__ to avoid creating a __dict__.
B.They make it impossible to add new attributes dynamically.
C.They are incompatible with all decorators.
D.They prevent the use of multiple inheritance.
E.Classes with __slots__ cannot have a __dict__ by default.
AnswersA, B, E

Otherwise, the child gets a dictionary.

Why this answer

Slots can break pickling in some cases, make multiple inheritance tricky, and prevent adding attributes dynamically.

152
MCQmedium

In a Tkinter grid layout, you want a button to span across two columns. Which parameter should you use?

A.columnspan=2
B.span_cols=2
C.merge=2
D.cols=2
AnswerA

columnspan is the correct parameter for merging grid columns.

Why this answer

The columnspan parameter in the grid() method manager allows a widget to occupy multiple columns.

153
MCQmedium

You are building a Tkinter application and need to ensure that a Label widget expands to fill any extra horizontal space when the parent window is resized. Which configuration for the grid() layout manager achieves this?

A.widget.pack(fill='x', expand=True)
B.widget.grid(sticky='nsew')
C.widget.grid(padx=10, pady=10)
D.parent.columnconfigure(0, weight=1) and widget.grid(sticky='ew')
AnswerD

Setting the column weight allows expansion, and sticky='ew' forces the widget to fill that space.

Why this answer

The sticky parameter with 'ew' (east and west) ensures the widget stretches horizontally, while columnconfigure with weight > 0 allows the column to expand.

154
MCQmedium

You are implementing the Observer pattern. Why should you avoid using a strong reference to the observers in the subject's list?

A.It causes circular dependency issues.
B.It makes the notify method thread-unsafe.
C.It violates the principle of encapsulation.
D.It prevents the observer from being garbage collected when it is no longer needed.
AnswerD

Weak references allow the garbage collector to reclaim the observer even if it's in the subject's list.

Why this answer

Strong references prevent garbage collection of the observers, leading to memory leaks if observers are meant to be temporary.

155
MCQeasy

What is the primary difference between @classmethod and @staticmethod?

A.@staticmethod can access instance variables.
B.@classmethod receives the class as the first argument; @staticmethod does not.
C.@classmethod is for private methods.
D.@classmethod is slower.
AnswerB

This is the fundamental distinction.

Why this answer

@classmethod receives the class as the first argument, while @staticmethod receives no implicit class or instance argument.

156
MCQeasy

What is the correct way to specify the title of a Tkinter window?

A.root.set_title('My App')
B.root.title('My App')
C.root.name = 'My App'
D.root.set_header('My App')
AnswerB

title() sets the window header text.

Why this answer

The title() method is called on the root window object.

157
MCQhard

Which method on a widget instance causes it to be removed from the display, but not destroyed?

A.widget.hide()
B.widget.remove()
C.widget.delete()
D.widget.pack_forget()
AnswerD

pack_forget() removes the widget from the display.

Why this answer

The pack_forget() (or grid_forget()) method hides a widget from the layout manager.

158
Multi-Selectmedium

Which THREE of the following are valid ways to configure a widget's appearance after it has been created?

Select 3 answers
A.widget['bg'] = 'blue'
B.widget.config(bg='blue')
C.widget.configure(bg='blue')
D.widget.set_bg('blue')
E.widget.style = 'blue'
AnswersA, B, C

Dictionary-style access is supported for configuration.

Why this answer

Widget appearance can be configured via the config() method, using dictionary-style access, or by directly calling attribute-specific methods if they exist (though config is standard).

159
MCQhard

When using configparser, how do you handle multiline values?

A.Use a backslash at the end of each line.
B.Indent the subsequent lines.
C.Wrap them in triple quotes ('''...''').
D.Use the '\n' escape character.
AnswerB

Indentation is the standard way to signify continuation of a value.

Why this answer

You indent lines following the initial line within the option.

160
MCQeasy

When using sqlite3.Row, what is the primary benefit over using a standard tuple?

A.It automatically commits transactions.
B.It provides dictionary-like access to columns by name.
C.It is faster to execute.
D.It supports multi-threading natively.
AnswerB

This feature makes code more readable and robust against schema changes.

Why this answer

sqlite3.Row allows accessing column values by name (string keys) instead of just numerical indices.

161
MCQeasy

Which magic method enables index access (e.g., obj[i])?

A.__getitem__
B.__index__
C.__setitem__
D.__access__
AnswerA

This is for retrieval.

Why this answer

The __getitem__ method allows an object to support indexing.

162
MCQeasy

Which comment style is preferred for block comments in Python?

A.Using a string literal (triple quotes) at the top level.
B.Using block comments inside a single line.
C.Each line starting with a single '#' and a space.
D.Using a single '#' at the end of every line.
AnswerC

This is the PEP 8 standard for block comments.

Why this answer

Block comments should consist of paragraphs of text, each starting with a # and a single space.

163
Multi-Selectmedium

Which TWO of the following are true about magic methods?

Select 2 answers
A.They are only available for built-in types.
B.They provide hooks into Python language operators.
C.They always start and end with '__'.
D.They cannot be overridden.
E.They are intended for direct calling by the user.
AnswersB, C

They are the standard hooks for operators like +, -, etc.

Why this answer

Magic methods start and end with double underscores, and they allow objects to integrate with Python's built-in syntax.

164
MCQhard

You are using 'concurrent.futures.ThreadPoolExecutor' to fetch data from multiple REST APIs. What happens if an exception is raised inside a thread?

A.The exception is ignored by the ThreadPoolExecutor
B.The entire program crashes immediately
C.The thread dies silently without notification
D.The exception is stored and raised when calling future.result()
AnswerD

The Future object encapsulates the result or the exception.

Why this answer

Exceptions raised in a future are captured and re-raised when calling result() on the Future object returned by submit().

165
Multi-Selectmedium

Which TWO of the following statements correctly describe the behavior of the Tkinter 'pack' geometry manager?

Select 2 answers
A.The manager automatically ignores the order in which pack() is called.
B.The 'side' parameter can be set to 'top', 'bottom', 'left', or 'right'.
C.Widgets are placed in a grid coordinate system.
D.Widgets are positioned at exact X and Y coordinates.
E.The 'fill' parameter can be set to 'x', 'y', 'both', or 'none'.
AnswersB, E

These are the valid values for the 'side' parameter.

Why this answer

Pack stacks widgets based on the 'side' argument and 'fill' determines how they occupy available space.

166
MCQhard

You want to trigger a function when a user releases a key. Which event string should you use with bind()?

A.<Key-Up>
B.<ReleaseKey>
C.<KeyUp>
D.<KeyRelease>
AnswerD

<KeyRelease> is the correct event string.

Why this answer

The '<KeyRelease>' event is used to detect when a key is released.

167
Multi-Selecthard

Which THREE of the following are valid ways to pass arguments to a function called by a Tkinter button command?

Select 3 answers
A.command=lambda arg=arg1: my_func(arg)
B.command=lambda: my_func(arg1)
C.command=functools.partial(my_func, arg1)
D.command=my_func(arg1=value)
E.command=my_func(arg1)
AnswersA, B, C

Using default arguments in a lambda is a robust way to capture values.

Why this answer

Using lambda or functools.partial are the standard ways to handle arguments in button commands.

168
MCQmedium

You are configuring a logging FileHandler. What does the 'mode' parameter control?

A.The log format.
B.The rotation interval.
C.The file opening mode.
D.The character encoding.
AnswerC

The mode parameter specifies how the file is opened (e.g., 'a', 'w').

Why this answer

The 'mode' parameter controls the file opening mode (e.g., 'a' for append, 'w' for write).

169
MCQmedium

You are using the pack() geometry manager and want to place a frame at the bottom of the window, ensuring it stays there even when other widgets are added. Which configuration is correct?

A.frame.pack(side='bottom', fill='x')
B.frame.pack(anchor='s', expand=True)
C.frame.pack(side='bottom', expand=False)
D.difficulty
E.frame.grid(row=99, column=0)
AnswerA

This anchors the frame to the bottom and makes it expand horizontally.

Why this answer

The 'side' parameter set to 'bottom' and 'fill' set to 'x' is the standard way to anchor a widget to the bottom edge.

170
MCQhard

You want to retrieve a list of all section names from a ConfigParser object. How do you do this?

A.list(parser.sections())
B.parser.sections()
C.parser.keys()
D.parser.get_sections()
AnswerB

This returns a list of section names.

Why this answer

The sections() method returns a list containing all section names except the DEFAULT section.

171
Multi-Selecthard

Which TWO of the following statements about the Python 'requests' library are correct?

Select 2 answers
A.It uses 'urllib3' internally for connection pooling
B.It does not support HTTPS
C.It is part of the standard library
D.It is thread-safe by default for all operations
E.It automatically closes connections for every request if not using a Session
AnswersA, E

Requests is built on top of the powerful urllib3 library.

Why this answer

The library handles connection pooling automatically when using Sessions, and it is built on top of 'urllib3'.

172
Multi-Selectmedium

Which TWO of the following are valid ways to create a singleton in Python?

Select 2 answers
A.Using a global variable that is not initialized.
B.Using a function that returns a new instance every call.
C.Using a base class with a custom __new__ method.
D.Using a standard class without any special methods.
E.Using a module as a singleton.
AnswersC, E

Can be used, though metaclasses are cleaner.

Why this answer

Modules are natural singletons, and metaclasses can be used to control instance creation.

173
MCQeasy

Which widget is most suitable for displaying multi-line, editable text?

A.tk.Listbox()
B.tk.Entry()
C.tk.Text()
D.tk.Label()
AnswerC

Text is for multi-line text.

Why this answer

The Text widget provides a flexible, multi-line text area.

174
Multi-Selecteasy

Which TWO of the following are valid conventions for naming in Python according to PEP 8?

Select 2 answers
A.Constants: camelCase
B.Classes: PascalCase
C.Modules: PascalCase
D.Functions: camelCase
E.Variables: snake_case
AnswersB, E

Correct convention for classes.

Why this answer

Functions should use snake_case, and classes should use PascalCase.

175
MCQhard

You are building a REST client that needs to handle 429 Too Many Requests status codes. Which strategy is most effective when implementing an automatic retry mechanism?

A.Implement an exponential backoff strategy with jitter
B.Switch to a different base URL immediately
C.Ignore 429 errors and continue execution
D.Retry immediately in a loop until successful
AnswerA

Exponential backoff with jitter is the industry standard for handling rate limits.

Why this answer

Implementing exponential backoff ensures that you do not overwhelm the server while waiting for the rate limit to reset.

176
Multi-Selectmedium

Which THREE practices improve documentation maintenance?

Select 3 answers
A.Updating documentation as part of the code review process.
B.Writing docs only at the end of the project.
C.Following a consistent docstring format (e.g., Google).
D.Keeping documentation in a separate repository.
E.Using automatic documentation generation tools like Sphinx.
AnswersA, C, E

Keeps info accurate.

Why this answer

Using standard formats, using tools, and regular updates are key.

177
MCQeasy

Which attribute of a Button widget controls the text displayed on it?

A.value
B.text
C.caption
D.label
AnswerB

text is the attribute for the button label.

Why this answer

The 'text' parameter defines the display label of the button.

178
MCQeasy

What happens when you add two objects of a class that implements __add__?

A.It does nothing.
B.It concatenates the objects.
C.It raises a TypeError.
D.The __add__ method is called.
AnswerD

This is how operator overloading works.

Why this answer

The __add__ method is automatically called by the interpreter when the '+' operator is used.

179
Multi-Selectmedium

Which TWO of the following are required to successfully write a row to a CSV file?

Select 2 answers
A.A list of strings to write.
B.An instance of csv.writer.
C.A call to csv.close().
D.A predefined dialect.
E.A file object opened in write mode.
AnswersB, E

The writer object handles the formatting.

Why this answer

You need an open file object and a csv.writer instance.

180
Multi-Selecteasy

Which THREE of the following are valid Tkinter variable classes used for tracking widget states?

Select 3 answers
A.FloatVar
B.IntVar
C.CharVar
D.StringVar
E.BooleanVar
AnswersB, D, E

Used for integer values.

Why this answer

StringVar, IntVar, DoubleVar, and BooleanVar are the standard Tkinter variable classes.

181
MCQmedium

Which practice is recommended when dealing with 'bare' except clauses in Python?

A.Use bare 'except:' for performance optimization.
B.Always specify the exception type you intend to catch.
C.Use 'except Exception:' as the standard catch-all.
D.Use 'except:' but log the error immediately.
AnswerB

This prevents catching unintended system-level exceptions.

Why this answer

Bare 'except:' clauses catch SystemExit and KeyboardInterrupt, which can prevent the user from stopping a program.

182
MCQeasy

When using the 'requests' library to perform a GET request, which parameter should be passed to the 'params' argument to include query string parameters in the URL?

A.A tuple of values
B.A single formatted string
C.A list of strings
D.A dictionary
AnswerD

A dictionary represents the query parameters correctly.

Why this answer

The 'params' argument expects a dictionary of key-value pairs which the library automatically encodes and appends to the URL.

183
MCQhard

You are using configparser.ConfigParser to read a configuration file. You have a file where option names are case-sensitive. How do you ensure the parser respects this casing?

A.parser = ConfigParser(case_sensitive=True)
B.parser.set_case(True)
C.parser.optionxform = lambda x: x
D.parser.read(file, case='preserve')
AnswerC

Setting optionxform to a function that returns the input string prevents lowercase conversion.

Why this answer

By default, ConfigParser converts keys to lowercase. You must override the optionxform method of the parser instance.

184
MCQhard

If you define a class with a metaclass that has a custom __call__ method, when is that __call__ method executed?

A.Every time an instance method is called.
B.When an instance of the class is created.
C.When the metaclass is first imported.
D.When the class itself is defined.
AnswerB

Metaclass __call__ intercepts the instantiation of its class objects.

Why this answer

The metaclass's __call__ method is invoked whenever the class created by that metaclass is instantiated (i.e., when you call the class name like MyClass()).

185
MCQhard

You are configuring logging using a dictConfig. You want to send logs to a RotatingFileHandler. Which key must you define in the 'handlers' section?

A.destination
B.type
C.handler_type
D.class
AnswerD

The 'class' key identifies the handler implementation.

Why this answer

The 'class' key is required to specify the handler type, e.g., 'logging.handlers.RotatingFileHandler'.

186
MCQmedium

You need a color chooser dialog in your application. Which module contains this functionality?

A.tkinter.dialogs
B.tkinter.colorchooser
C.tkinter.colors
D.tkinter.widgets
AnswerB

This module contains the color selection dialog.

Why this answer

The 'tkinter.colorchooser' module provides the askcolor() function.

187
MCQmedium

You need to configure the logging module to capture logs from multiple modules while ensuring that logs from third-party libraries (e.g., 'urllib3') are only captured at the WARNING level. How do you set this?

A.logging.getLogger('urllib3').setLevel(logging.WARNING)
B.logging.config.dictConfig({'urllib3': 'WARNING'})
C.logging.basicConfig(level=logging.WARNING)
D.logging.setLevel('urllib3', logging.WARNING)
AnswerA

This explicitly sets the log level for the specified library logger.

Why this answer

You can configure individual loggers using getLogger() and setting their specific level attribute.

188
Multi-Selecteasy

Which TWO of the following are valid ways to terminate a Tkinter script gracefully?

Select 2 answers
A.os.kill()
B.root.quit()
C.exit()
D.root.close()
E.root.destroy()
AnswersB, E

Correctly exits the event loop.

Why this answer

Calling destroy() on the root window or calling the quit() method are standard ways to end a GUI session.

189
MCQeasy

Which method is used to customize the behavior of the 'in' operator?

A.__contains__
B.__has__
C.__find__
D.__in__
AnswerA

This is the correct magic method.

Why this answer

The __contains__ method is called when using the 'in' or 'not in' operators.

190
Multi-Selecthard

Which TWO of the following are secure coding practices in Python?

Select 2 answers
A.Use 'subprocess' with 'shell=True'.
B.Always use 'eval()' for dynamic execution.
C.Avoid using 'pickle' for untrusted data.
D.Validate and sanitize all user input.
E.Use hardcoded credentials for database connections.
AnswersC, D

Pickle is inherently insecure.

Why this answer

Avoiding dangerous functions and validating all inputs are key security practices.

191
MCQmedium

You are consuming a REST API that returns data in JSON format. After calling response.json(), you notice the data contains nested dictionaries. What is the most Pythonic way to handle a missing key in the response dictionary safely?

A.Wrap the access in a try-except KeyError block
B.Check 'if 'key' in response.json():' before access
C.Use response.json()['key'] and assume the API schema is always correct
D.Use response.json().get('key', default_value)
AnswerD

This is the idiomatic way to handle optional keys in dictionaries.

Why this answer

The dict.get() method provides a way to access a key with a default value if the key does not exist, preventing a KeyError.

192
MCQeasy

What is the primary function of the 'bg' parameter in a widget configuration?

A.Sets the button group.
B.Sets the border group.
C.Sets the background color.
D.Sets the base grid.
AnswerC

bg stands for background.

Why this answer

The 'bg' (or background) parameter sets the background color of the widget.

193
Multi-Selecteasy

Which THREE of the following are valid logging levels?

Select 3 answers
A.DEBUG
B.WARNING
C.NOTICE
D.FATAL
E.INFO
AnswersA, B, E

Valid level.

Why this answer

DEBUG, INFO, and WARNING are valid levels.

194
MCQhard

To prevent a user from editing text in a widget, which configuration option should you set?

A.editable=False
B.enabled=False
C.state=tk.DISABLED
D.readonly=True
AnswerC

state=tk.DISABLED effectively makes the widget uneditable.

Why this answer

Setting 'state' to 'disabled' prevents user interaction with the widget.

195
MCQeasy

Which magic method should you implement to make your objects support the 'with' statement context manager?

A.__context__
B.__enter__ and __exit__
C.__open__ and __close__
D.__init__ and __del__
AnswerB

These are the mandatory methods for the context manager protocol.

Why this answer

The __enter__ and __exit__ methods are required to implement the context manager protocol.

196
MCQeasy

Which function is used to check if an object is an instance of a class?

A.hasattr()
B.issubclass()
C.type()
D.isinstance()
AnswerD

This handles inheritance correctly.

Why this answer

isinstance(obj, Class) is the standard way to check inheritance.

197
MCQmedium

You want to bind a function 'on_click' to a left mouse button click on a Button widget. Which event sequence string is correct?

A.<Button-1>
B.<Mouse-1>
C.<Left-Click>
D.<Click-1>
AnswerA

<Button-1> represents the left mouse click.

Why this answer

The event sequence '<Button-1>' corresponds to the primary (left) mouse button.

198
MCQmedium

In the context of the Factory pattern in Python, what is a typical benefit of using a registry-based approach instead of a large if-else block?

A.It guarantees thread safety without locks.
B.It prevents the instantiation of abstract classes.
C.It enables easy extension by adding new products without changing the factory.
D.It significantly reduces memory usage.
AnswerC

This is the open/closed principle in action.

Why this answer

Registry-based factories allow for decoupled code where new classes can be registered without modifying the factory's core logic.

199
MCQmedium

How do you properly handle a non-200 status code when using 'requests' if you want to avoid manual status code checking?

A.Use response.raise_for_status()
B.Use a decorator on the request function
C.Check response.error
D.The library raises an exception by default
AnswerA

This is the built-in method to handle error status codes.

Why this answer

Calling response.raise_for_status() will raise an HTTPError exception if the status code indicates an error (4xx or 5xx).

200
MCQmedium

You are processing a CSV file using csv.DictReader. If your input file lacks a header row, how do you provide the field names?

A.csv.DictReader(f, headers=['a', 'b'])
B.csv.DictReader(f).map(['a', 'b'])
C.csv.DictReader(f, fieldnames=['a', 'b'])
D.csv.DictReader(f, columns=['a', 'b'])
AnswerC

This correctly maps columns to the provided field names.

Why this answer

You pass the 'fieldnames' argument to the constructor to define the headers explicitly.

201
MCQmedium

You are debugging a legacy application and need to ensure that resources like file handles are always closed. Which construct is preferred?

A.Wrap the file operation in a try-except block.
B.Manually call file.close() in a finally block.
C.Use a context manager with the 'with' statement.
D.Rely on the garbage collector to close the handle.
AnswerC

This is the Pythonic way to handle resource management.

Why this answer

The 'with' statement (context manager) ensures that cleanup code is executed even if an exception occurs.

202
MCQhard

Consider a class that uses a metaclass to automatically register subclasses in a dictionary. If you want to prevent the base class itself from being registered, how should the metaclass be implemented?

A.Check the class name within the metaclass __init__ method before adding it to the registry.
B.Use the __call__ method to raise a TypeError if the base class is instantiated.
C.Set the __new__ method of the metaclass to return None if the name is 'Base'.
D.Define a decorator on the base class that removes it from the metaclass registry.
AnswerA

The __init__ method is invoked after the class creation, allowing you to filter out the base class based on attributes or names.

Why this answer

The metaclass __init__ method receives the class object. By checking the class name or using a specific attribute (e.g., _is_base), you can conditionally skip registration.

203
MCQmedium

How do you set a specific font for a widget?

A.widget.set_font('Arial', 12)
B.widget.style('Arial', 12)
C.widget.font = 'Arial 12'
D.widget.config(font=('Arial', 12))
AnswerD

The font parameter is the standard way to set typography.

Why this answer

The 'font' parameter accepts a tuple or string defining font family, size, and style.

204
MCQmedium

You are using sqlite3 and need to enforce foreign key constraints. How do you enable them?

A.It is enabled by default.
B.connection.execute('PRAGMA foreign_keys = ON')
C.connection.execute('SET FOREIGN_KEYS ON')
D.connection.enable_foreign_keys()
AnswerB

This is the correct SQLite pragma command.

Why this answer

You must execute the command 'PRAGMA foreign_keys = ON;' on the connection.

205
MCQhard

Why might you use the __init_subclass__ hook instead of a metaclass?

A.Metaclasses are deprecated.
B.Metaclasses cannot be used for registration.
C.It is faster at runtime.
D.It is easier to implement and avoids metaclass conflicts.
AnswerD

Metaclass conflicts arise when multiple classes have different metaclasses; __init_subclass__ avoids this.

Why this answer

__init_subclass__ provides a simpler way to perform logic when a subclass is created, without the complexity and inheritance issues associated with custom metaclasses.

206
MCQhard

You are building a custom HTTP client and need to handle persistent connections (keep-alive). What is the primary role of the 'Connection' header?

A.To signal that the server is alive
B.To request the reuse of the TCP connection
C.To encrypt the connection
D.To set the timeout for the connection
AnswerB

This is the purpose of the Connection header.

Why this answer

The 'Connection: keep-alive' header tells the server that the client wants to reuse the same TCP connection for multiple requests.

207
Multi-Selecthard

Which TWO of the following are true about the sqlite3.Cursor object?

Select 2 answers
A.It can be used as an iterator to fetch rows.
B.It is used to execute SQL statements.
C.It automatically creates a transaction for every SELECT.
D.It is limited to one active query.
E.It keeps track of the connection state.
AnswersA, B

Cursors can iterate over result sets.

Why this answer

The cursor is used to execute SQL and retrieve results.

208
Multi-Selecteasy

Which THREE of the following are valid ways to pass data to a REST API using 'requests'?

Select 3 answers
A.json
B.socket
C.url
D.params
E.data
AnswersA, D, E

Used for sending JSON serialized data.

Why this answer

The 'params', 'data', and 'json' arguments allow different ways of sending information in requests.

209
MCQhard

You have a Tkinter Entry widget and want to retrieve the text currently entered by the user. Which method do you call on the Entry instance?

A.entry.get()
B.entry.content()
C.entry.text()
D.entry.value()
AnswerA

get() is the correct method to extract the string content from an Entry widget.

Why this answer

The get() method is used to retrieve the current contents of Entry and Text widgets.

Page 2

Page 3 of 3

All pages