Courseiva

PCPP1 · domain

scenario questions

Practise Python Institute Certified Professional in Python Programming 1 (PCPP1, PCPP-32-101) (PCPP1) scenario questions practice questions — original exam-style scenarios with answer choices, explanations, and analysis of common mistakes.

290 questions72 easy127 medium91 hard

Focused practice

Practice scenario questions questions

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

Start 20-question practice test →

What this domain covers

What to know about scenario questions

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

How the topic appears in realistic exam-style scenarios.

Which detail in the question changes the correct answer.

How to eliminate plausible but wrong options.

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

Watch out for

Common scenario questions exam traps

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

Question index

All scenario questions questions (290)

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

1

Which THREE of the following are true regarding the use of 'threading' and 'requests' in Python?

Hard
2

You are using the logging module in a long-running service. You need to ensure that a specific logger named 'app.db' writes DEBUG and higher messages to a file, but its parent logger 'app' must not propagate these DEBUG messages to the root logger. Which configuration achieves this?

Hard
3

You are consuming a paginated REST API that returns a JSON object with a 'data' list and a 'next' field holding the URL of the following page, or null on the last page. You want a loop that retrieves every record exactly once. Which TWO statements about implementing this loop correctly are true? (Choose two.)

Medium
4

A library defines a base class `Plugin` with `__init_subclass__(cls, **kwargs)` that automatically registers every subclass in a global registry using `cls.__name__`. A developer writes `class MyPlugin(Plugin, priority=5): pass` but the registration fails with a TypeError about unexpected keyword arguments. What is the most likely cause?

Hard
5

Which THREE features are associated with robust logging in production applications?

Hard
6

Which of the following headers is commonly used in REST APIs to indicate the format of the request body?

Easy
7

In a team environment, which PEP 8 guideline should be applied to maintain consistent indentation when mixing spaces and tabs?

Easy
8

A developer is writing a Python script that contains a class named `DataProcessor`. According to PEP 8, which naming convention should be used for the class's methods and attributes?

Easy
9

Which TWO of these are valid PEP 8 recommendations for whitespace?

Easy
10

You are implementing a custom context manager using a class. Which methods must be implemented to support the 'with' statement?

Hard
11

You are writing a Python client to consume a REST API. The API documentation states that the server may respond with a 307 Temporary Redirect when a resource has moved temporarily. You need to ensure that your client, built with the 'requests' library, preserves the original HTTP method and body when following such redirects. Which of the following best describes how 'requests' handles a 307 redirect by default?

Medium
12

You are writing a Python script that uses the `socket` module to create a TCP client. After calling `sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)`, which method should you call next to initiate a connection to a remote server at `('example.com', 80)`?

Medium
13

A developer is documenting a function `fetch_records` that accepts a database connection, a table name, and an optional limit. The team follows Google Style Python Docstrings. Which approach correctly documents the parameters and their types?

Medium
14

You are preparing a Python module for PyPI. Your project layout is: project_root/ ├── setup.py ├── src/ │ └── mypackage/ │ ├── __init__.py │ └── core.py └── tests/ └── test_core.py You want to write a test that imports mypackage.core and verifies the function add(a, b). Which import statement should you use at the top of tests/test_core.py to follow best practices for a src-layout project after installing the package in editable mode?

Medium
15

Which module provides a high-level API for working with URLs, such as parsing and unparsing them?

Medium
16

Which TWO of the following exceptions might be raised during socket operations?

Medium
17

What is the purpose of the logging.StreamHandler?

Easy
18

Which of the following describes the purpose of the __slots__ attribute in a class?

Easy
19

A developer defines a class `Temperature` that stores a Celsius value in `self._celsius` and exposes a `celsius` property with a setter that validates the value is not below absolute zero. After instantiating `t = Temperature(20)`, the developer runs `t.celsius = -300`. What happens?

Medium
20

You are implementing a custom Tkinter widget that must validate user input in an Entry field and prevent non-numeric characters from being entered. Which mechanism should you use to intercept and optionally reject each keystroke before it modifies the Entry contents?

Hard
21

Which TWO of the following represent common data formats used for REST API request/response payloads?

Easy
22

A Tkinter application has a modal dialog implemented as a Toplevel that collects a numeric discount. The dialog's OK button command calls a validator that may raise ValueError, and you want the dialog to stay open with an inline error label rather than crashing the mainloop. The dialog is opened from the main window with dialog.grab_set() followed by main_window.wait_window(dialog). Which approach correctly keeps the error visible and prevents the exception from propagating out of the Tkinter callback?

Hard
23

You are designing a plugin system where each plugin class must automatically register itself with a central registry when defined, without requiring an explicit decorator or registration call. You decide to use the __init_subclass__ hook in the base Plugin class. Which statement correctly describes how to implement this so that every subclass is registered with its own class object?

Medium
24

Which TWO of the following events are commonly bound in Tkinter for mouse interaction?

Medium
25

Which magic method is responsible for providing the informal string representation of an object, typically used for user-facing output?

Easy
26

You are developing a Python application that must parse a large XML file and extract specific data. The file is too large to fit into memory, so you need to process it incrementally. Which approach using the xml.etree.ElementTree module is most appropriate?

Medium
27

Which magic method allows an object to behave like a function?

Medium
28

You are writing a client that must upload a binary file to a REST endpoint using requests.put(). The file is several hundred megabytes, and you want to avoid loading it entirely into memory while still letting the server know the total size. Which approach meets both goals?

Medium
29

When using the place() geometry manager, what is the purpose of 'relx' and 'rely'?

Hard
30

Which THREE of the following are attributes of the 'requests.Response' object?

Medium
31

A developer writes a class `Money` that implements `__eq__` to compare amounts and currencies, but does not implement `__hash__`. Instances of `Money` are then used as keys in a `set`. What is the result?

Medium
32

A Python script consumes a REST endpoint that returns a JSON document. You call response = requests.get(url) and want to convert the body into native Python objects. The response is guaranteed to be valid JSON. Which expression gives you the deserialized data?

Easy
33

In the Factory pattern, what should you do if the requested type is unknown?

Medium
34

When using configparser, how do you retrieve a value as a boolean?

Easy
35

A developer is reviewing a pull request where a function uses a global variable to track a counter. The reviewer suggests refactoring to avoid global state. Which refactoring best follows best practices for maintainability and testability?

Hard
36

You are developing a Tkinter application that includes a Button widget. When the user clicks the button, you need to execute a function named handle_click that accepts no arguments. Which approach correctly associates this function with the button's click event?

Medium
37

In the 'requests' library, which HTTP method is typically used to update an existing resource on a server?

Easy
38

You are implementing a `Vector` class whose instances should support `v1 + v2` and also `v1 + 5`, where the second form broadcasts the scalar across every component. A colleague suggests relying on `__radd__` to handle the scalar case. Why is that insufficient?

Hard
39

You are designing a Python class that manages a database connection. The class has a method `_execute_query` that should only be used internally. According to Python best practices and PEP 8, how should you indicate that this method is for internal use only?

Hard
40

A teammate writes a `Money` value object that defines `__eq__` to compare amounts and currencies, and `__hash__` to hash the same two fields. During a code review you notice that a subclass `Discount` adds a `percentage` field, overrides only `__eq__` to include that field, and leaves `__hash__` inherited. Objects of `Discount` are then used as dictionary keys. What is the actual runtime consequence?

Hard
41

What is the difference between a class-level variable and an instance-level variable?

Medium
42

Which TWO of the following are valid ways to add padding to a widget in the grid layout?

Hard
43

When creating a new project, how should you structure your imports?

Medium
44

What is the purpose of the 'socket.shutdown()' method in Python?

Medium
45

You are using the `json` module to serialize a custom object that contains a `datetime.date` attribute. When you call `json.dumps(obj)`, you get a `TypeError: Object of type date is not JSON serializable`. Which approach correctly allows serialization while preserving the date as an ISO 8601 string?

Hard
46

You are designing a class `Matrix` that supports element-wise addition and scalar multiplication. You want `m1 + m2` to return a new `Matrix` without modifying `m1` or `m2`. You have implemented `__add__` correctly. A colleague writes `m1 += m2` and expects `m1` to be rebound to a new `Matrix` object. However, after the statement, `m1` still refers to the same object and its internal data has been modified in place. Which change to your class is the most likely cause of this behavior?

Medium
47

When overriding the __getattr__ method, what must you be careful to avoid?

Medium
48

You are writing a script that reads a large CSV file using csv.reader. The file uses a semicolon as the delimiter and contains quoted fields with embedded newlines. Which instantiation correctly handles this format?

Easy
49

When receiving data from a TCP socket using 'recv(buffer_size)', what does the returned value represent?

Easy
50

Which THREE of the following steps are required to initialize a TCP server socket?

Hard
51

Which TWO practices help maintain clean code when using Python's 'try-except' blocks?

Medium
52

You are writing a Python application that must parse a configuration file where a value spans multiple lines, such as a long list of email addresses separated by newlines. You decide to use the configparser module. Which of the following correctly describes how to include a multi-line value in the configuration file?

Medium
53

A developer creates a class named `Registry` in a module. The class inherits from `ABCMeta` and defines a `__new__` method that performs validation on the class namespace before the class is created. Inside `__new__`, the developer needs to inspect the attributes defined in the class body of the class being created. Which parameter of `__new__` provides direct access to those attributes?

Medium
54

You are building a Tkinter GUI that includes a Canvas widget. You want to draw a rectangle and then later change its fill color without redrawing the entire canvas. Which method should you use to update the rectangle's fill color?

Hard
55

When sending a JSON payload with 'requests.post()', which argument should you use to automatically set the 'Content-Type' to 'application/json'?

Medium
56

When using 'requests.get()', how can you include a custom HTTP header in your request?

Easy
57

When using a metaclass, how can you access the class attributes during the class definition?

Medium
58

You are building a canvas-based drawing tool and need to detect when the user clicks on a specific rectangle item to select it, while other clicks should be ignored. Which canvas feature should you use?

Hard
59

A Tkinter data-entry form uses an Entry widget for a numeric amount. Users report that pressing Enter in the Entry does nothing, and the value is only saved when they click a separate Save button. You want Enter to trigger the same save routine as the button, without duplicating logic. Which binding achieves this?

Medium
60

You are logging events with custom levels. How do you add a custom level 'TRACE' (value 5) to the logging module?

Hard
61

What is the recommended way to handle a function that requires a large number of arguments?

Medium
62

You need to send binary data over a socket. Which method should you use on the socket object to ensure all data is sent?

Medium
63

You are developing a multithreaded HTTP scraper. When using the 'requests' library inside 'threading.Thread' objects, what is the recommended practice for handling session persistence?

Hard
64

You are creating a class where you want to prevent instances from having a __dict__ to save memory. You add __slots__ = ('x', 'y') to the class. Which statement is true about this class?

Easy
65

According to PEP 257, what is the standard format for a single-line docstring?

Easy
66

Which TWO of the following are true regarding multiple inheritance in Python?

Medium
67

You are implementing a class `Vector` that supports addition and scalar multiplication. You want `v1 + v2` to return a new `Vector`, and `v1 * 3` to return a new scaled `Vector`. You also want `3 * v1` to work identically. Which pair of methods must you implement to support both `v1 * 3` and `3 * v1` correctly, assuming `v1` is a `Vector` and `3` is an `int`?

Hard
68

A Tkinter application has a main window containing a Text widget used as a log console. The application performs a long-running data import and must remain responsive, so the import runs in a background thread. The worker thread needs to append status lines to the Text widget. Which approach is correct?

Medium
69

You are designing a class hierarchy for a document processing system. The base class `Document` defines a method `render()` that returns a string. You want subclasses to be forced to provide their own implementation, and you want to prevent `Document` from being instantiated directly. Which code correctly enforces this requirement?

Medium
70

In the context of the CSV module, what is a 'dialect'?

Easy
71

You are writing a Python script that needs to parse a URL and extract the query parameters. The URL is 'https://api.example.com/v1/items?limit=10&offset=20'. Which module should you use to reliably parse this URL and retrieve the value of 'limit'?

Easy
72

How do you access the value of a StringVar associated with an Entry widget?

Hard
73

Which status code indicates that a requested resource has been successfully created?

Easy
74

What is the primary risk of using 'getattr' without a default value?

Hard
75

You are developing a Tkinter application that uses multiple threads to perform background tasks. One thread updates a Label widget's text using its config method. Occasionally, the application crashes with a Tcl error about calling from a different thread. What is the correct approach to safely update the GUI from a background thread?

Hard
76

A developer is writing a Python function that accepts a mutable default argument, such as `def add_item(item, items=[])`. A code reviewer flags this as a potential bug. Which statement best explains the issue and the recommended fix according to best practices?

Hard
77

You are building a Tkinter application with a Button widget that should run a long-running calculation when clicked, but the GUI freezes until the calculation finishes. Which approach best keeps the interface responsive while performing the calculation?

Medium
78

You need to add a label that displays static text in your GUI. Which widget is most appropriate for this purpose?

Easy
79

When using the __call__ method to implement a decorator, what does the decorator receive as an argument?

Medium
80

You need to perform a HEAD request to check if a file exists on a server without downloading the body. How is this done with 'requests'?

Medium
81

You are working with a large XML file and need to extract specific elements efficiently without loading the entire document into memory. You decide to use the xml.etree.ElementTree module. Which of the following methods should you use to iterate over all 'book' elements in the document?

Hard
82

Why does the __init__ method not return anything?

Hard
83

What is the primary difference between the 'socket.AF_INET' and 'socket.AF_INET6' address families?

Easy
84

A developer implements a class `Vector` with `__add__` returning a new `Vector`, and also defines `__iadd__` that mutates `self` in place and returns `self`. A colleague writes `a = Vector(1,2); b = Vector(3,4); c = a; a += b`. What is the state of `c`?

Hard
85

In a multithreaded network application, you observe 'ConnectionResetError'. What is the most likely cause when using Python sockets?

Hard
86

What is the purpose of the 'weakref' module in relation to the Observer pattern?

Hard
87

When using configparser, what happens if you attempt to read a configuration file that does not exist using the read() method?

Medium
88

You are using the socket module to create a TCP client. After creating the socket object, which method call is required to establish a connection to a remote server listening on 192.168.1.50 at port 8080?

Medium
89

You are writing a Python tool that must connect to a REST API over HTTPS. The API's server certificate is signed by an internal corporate CA whose root certificate is stored in a file named corp-ca.pem. You use the requests library and need the connection to be verified against that specific CA while still performing normal hostname checking. Which call accomplishes this?

Medium
90

You are prototyping a Tkinter application and want a single-line input field where users can type a search term. The field should also show a placeholder-like behavior by pre-filling the text 'Search...' when the window opens. Which widget and option combination achieves this most directly?

Easy
91

A developer is writing a Python script and wants to ensure that lines do not exceed the recommended maximum length according to PEP 8. What is the maximum line length that PEP 8 recommends for code?

Easy
92

You are writing a Python script that must process a large text file line by line. The file is UTF-8 encoded, but some lines contain characters that are not representable in the default system encoding. You want to ensure that the script reads the file correctly on any platform. Which code correctly opens the file?

Medium
93

Which TWO of the following are valid ways to define a configuration option in configparser?

Medium
94

How do you define a property in a class to make it read-only?

Hard
95

A developer is writing a Python script and wants to ensure that the code adheres to PEP 8's recommendations for blank lines. According to PEP 8, how many blank lines should surround a top-level function definition?

Easy
96

Which TWO of the following are true regarding the HTTP 'User-Agent' header?

Hard
97

Which THREE of the following are correct regarding socket buffer sizes?

Medium
98

Which TWO practices ensure secure handling of sensitive environment configurations?

Medium
99

You are building a Python script that consumes a REST API which returns paginated JSON responses. The API includes a 'next' link in the response body for the next page. You need to follow these links until all pages are retrieved. Which approach is most appropriate using the requests library?

Medium
100

A script processes data from untrusted sources. Which technique best mitigates 'pickle' deserialization vulnerabilities?

Hard
101

When naming a constant in Python, which convention does PEP 8 recommend?

Easy
102

Which THREE of the following are recommended in PEP 8 for class definitions?

Easy
103

You wish to group several widgets together within a frame. Which widget acts as a container for this purpose?

Medium
104

Which magic method is used to control how an instance is displayed when using the print() function?

Easy
105

You are developing a Python application that needs to retrieve data from a public REST API. The API returns JSON data and requires you to send a GET request with a custom User-Agent header. Which of the following code snippets correctly sends the request using the requests library?

Easy
106

A developer is implementing the Observer pattern and wants to store a list of observers without preventing them from being garbage collected when no other references exist. They decide to use `weakref.WeakSet` to hold the observers. Which statement accurately describes the behavior they should expect?

Medium
107

You are creating a Tkinter application with a Canvas widget. You draw a circle using create_oval and assign it the tag 'ball'. Later, you want to move the circle 10 pixels to the right and 5 pixels down. Which Canvas method should you use?

Easy
108

A developer is writing a Python script that processes sensitive data. They want to ensure that any errors are logged without exposing the sensitive data itself. Which logging practice should they follow to avoid leaking sensitive information in logs?

Hard
109

You are designing a Tkinter application that uses a ttk.Treeview to display a table of records. You need to configure the widget so that users can select multiple non-contiguous rows and so that the first column shows a tree-style expander control. Which two actions must you perform? (Choose two.)

Medium
110

You are creating a simple Tkinter application and notice that your window does not appear on the screen after calling the Tk() constructor. Which method must be called to start the event loop?

Easy
111

You have a Checkbutton and you need to track its state. What is the recommended way to associate a variable with the Checkbutton?

Medium
112

A colleague built a Tkinter form where every Entry widget uses `pack()` in the same frame. They now need the labels to sit in a single column with the entries aligned in the next column and the whole form centered. They ask you to recommend the smallest structural change that makes this alignment reliable. What should you suggest?

Hard
113

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

Medium
114

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?

Medium
115

You are implementing a Python client that communicates with a REST API over HTTPS. The API uses a self-signed certificate. You need to verify the server's certificate against a custom CA bundle while also ensuring that the hostname is verified. Which approach correctly configures the 'requests' library?

Hard
116

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

Hard
117

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

Easy
118

What is the purpose of the __set_name__ method in descriptors?

Hard
119

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

Medium
120

You are using the csv module to read a file that contains fields with embedded newlines and commas. Which TWO of the following statements about the csv.reader are correct? (Choose two.)

Medium
121

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

Easy
122

Which THREE practices are recommended when handling external libraries?

Medium
123

You are reviewing a Tkinter application that uses ttk widgets and a Canvas to draw a seating chart. The chart must redraw when the window is resized, and a toolbar above it must stay a fixed height. Which two techniques correctly contribute to a layout where the Canvas expands and the toolbar does not? (Choose two.)

Hard
124

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

Easy
125

You are building a Python application that uses the shelve module to store persistent data. You want to ensure that the database file is updated correctly and that you can access keys as attributes. Which TWO of the following statements about the shelve module are true? (Choose two.)

Medium
126

When is it acceptable to ignore PEP 8 guidelines?

Easy
127

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

Medium
128

You are developing a Python application that uses the `requests` library to consume a REST API. You need to implement a retry mechanism for transient HTTP errors (e.g., 500, 502, 503, 504) and connection timeouts. Which TWO of the following approaches are valid and recommended for achieving this with `requests`? (Choose two.)

Hard
129

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

Medium
130

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

Medium
131

You are building a client for a REST API that requires an OAuth 2.0 bearer token. The token is long-lived and stored in an environment variable. You want every request in a session to carry the Authorization header without repeating the header setup at each call site. Which approach is correct and idiomatic with the requests library?

Hard
132

A developer is writing a Python function that accepts a callback. They want to ensure the function's docstring follows PEP 257 conventions for multi-line docstrings. Which of the following is the correct format for a multi-line docstring?

Hard
133

You are designing a Tkinter application with a Listbox widget that displays multiple items. You want to allow the user to select multiple non-contiguous items (e.g., by holding Ctrl and clicking). Which configuration option of the Listbox should you set, and to what value?

Hard
134

You are writing a Tkinter dialog that must react to a user pressing the Escape key at any time, even when focus is inside an Entry widget. You have a function named on_cancel. Which binding correctly achieves this?

Hard
135

A colleague's script parses a CSV export that uses a semicolon as the field separator and contains quoted text fields with embedded semicolons. They call csv.reader(f) without arguments and complain that rows are split incorrectly into too many fields. What is the correct fix?

Medium
136

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

Hard
137

You are creating a Tkinter application with a menu bar. You want to add a keyboard shortcut (accelerator) to a menu item so that pressing Ctrl+S triggers the save action. Which option of the add_command method should you use to display the shortcut text, and what additional step is required to make the shortcut functional?

Medium
138

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

Medium
139

A developer is adding a new public function `calculate_discount` to an existing Python module. The module currently uses four spaces per indentation level, and the function spans several nested `if` blocks. Which PEP 8 indentation practice should the developer follow?

Easy
140

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

Medium
141

You are writing a Python script that must read a configuration file in TOML format. Which module from the Python Standard Library should you use?

Easy
142

You wrote a small REST client that calls `requests.get('https://api.example.com/v1/items', timeout=5)`. Under normal network load the call succeeds, but the server occasionally takes longer than 5 seconds to start sending the response body while the TCP connection is already established. You want to allow up to 5 seconds for the connection to be established and up to 30 seconds for the server to send data after the connection is made. Which call achieves this?

Medium
143

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?

Medium
144

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

Hard
145

You are implementing a Python client that uses the `socket` module to communicate with a server. The server sends data in chunks, and you need to ensure you receive all data until the connection is closed by the server. Which approach correctly reads all data from the socket?

Hard
146

You are writing a REST client that must handle HTTP error responses robustly. For each response, you want to detect server errors and extract the error message returned in a JSON body. Which TWO of the following approaches are correct and safe? (Choose two.)

Medium
147

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

Medium
148

You are working with the sqlite3 module to build a small inventory application. You need to execute a parameterized INSERT statement and then retrieve the auto-generated primary key for the newly inserted row. Which two approaches are valid and safe? (Choose two.)

Medium
149

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

Medium
150

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

Hard
151

A code reviewer notices that a Python module defines a class named `dataProcessor` and a function named `processData`. The team follows PEP 8. Which naming convention should be applied to the class name?

Medium
152

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

Medium
153

You are designing a Python microservice that exposes a REST API. A client sends a PUT request to update a resource with a JSON body. Your service must ensure idempotency: if the same request is received multiple times, the resource should end up in the same state. Which HTTP method and semantics should you implement to guarantee idempotency for updates?

Hard
154

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

Medium
155

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

Easy
156

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

Hard
157

You are developing a Tkinter application with a top-level window that contains a Frame widget. Inside the Frame, you place three Button widgets using grid(). Later, you need to add a fourth Button that should span the full width of the Frame, below the existing three. Which grid() configuration should you apply to the new Button?

Medium
158

You are writing a reusable module that must expose only a small public API while keeping several helper functions and constants internal. Users of the module should not import the helpers with 'from mymodule import *', but direct access such as mymodule._helper() may still be needed for tests. Which approach fits best?

Hard
159

You are writing a Python script that needs to create a temporary directory, write several files into it, and ensure that the directory and its contents are automatically deleted when the script exits, even if an exception occurs. Which approach using the tempfile module is most appropriate?

Easy
160

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

Medium
161

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

Hard
162

You are writing a class `Temperature` that should support addition and comparison. You want `t1 + t2` to return a new `Temperature` object, and `t1 == t2` to compare their values. Which magic methods must you implement to achieve this?

Medium
163

A desktop tool built with Tkinter needs a list of departments shown as mutually exclusive radio buttons. When the user selects a department, the underlying model object's department attribute must update immediately, and the code must read the selection later without iterating over every radio button. Which Tkinter mechanism best satisfies these requirements?

Easy
164

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?

Medium
165

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

Medium
166

You are writing a Python module that includes a function to compute the factorial of a number. You want to document the function using a docstring that is compatible with the Google Python Style Guide. Which of the following docstrings correctly follows the Google style for documenting parameters and return values, including types?

Hard
167

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

Easy
168

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

Hard
169

You are using the datetime module to calculate the difference between two dates. You have two datetime objects, start and end, and you need to find the number of full days between them, ignoring any fractional part. Which expression correctly computes this?

Hard
170

A Tkinter application uses a Canvas to draw a seating chart. Each seat is a rectangle created with create_rectangle, and seats are grouped by section. When a section is selected, every seat in it must change fill color, and some seats must later be moved to a new position. Which strategy best supports efficient grouped updates while keeping individual seats addressable?

Hard
171

You are using the sqlite3 module to insert a large number of rows into a table. You want to maximize performance by reducing the number of disk writes. Which approach is most effective?

Hard
172

You are maintaining a Tkinter inventory application where users type quantities into an Entry widget. A colleague reports that the application accepts "12.5" for an item that must be a whole number, and invalid keystrokes are only caught after the user clicks Save. You must reject non-numeric input as it is typed, while still allowing a normal editing experience. Which mechanism should you register on the Entry widget?

Medium
173

You are building a Tkinter desktop application with a menu bar. Users report two problems: keyboard shortcuts such as Ctrl+S do not trigger the Save command when focus is inside a Text widget, and mnemonic underlines on the File menu are missing. You must correct the menu configuration. Which two changes should you make? (Choose two.)

Hard
174

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

Hard
175

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

Medium
176

You are creating a dialog window in a Tkinter application that must block interaction with the main window until the user closes it, and must return a value to the caller. Which approach correctly implements this behavior?

Medium
177

A `Temperature` class stores a numeric `celsius` attribute. Callers keep assigning `temp.celsius = -500`, which is physically impossible. You want any assignment below absolute zero to raise `ValueError` while keeping normal attribute access unchanged. Which construct should you implement?

Easy
178

You are implementing a class `Matrix` that supports the `+` operator for matrix addition. You want `m1 + m2` to return a new `Matrix`, and you also want `sum([m1, m2, m3])` to work correctly. You define `__add__` to return a new `Matrix`. However, `sum([m1, m2, m3])` raises a `TypeError`. What is the most likely reason?

Hard
179

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

Easy
180

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

Hard
181

A development team is refactoring a legacy Python module. They want to enforce a consistent import ordering convention across the codebase. According to PEP 8, which grouping and ordering of imports is considered best practice?

Medium
182

A developer is designing a `Shape` base class and wants subclasses to be forced to implement an `area()` method. Which two approaches are valid in Python for enforcing that subclasses provide `area()`? (Choose two.)

Medium
183

A team is reviewing code and notices that a function uses a mutable default argument: def append_to(element, target=[]):. Which change best adheres to Python best practices and avoids unexpected behavior?

Easy
184

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

Hard
185

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

Medium
186

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

Easy
187

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

Medium
188

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?

Easy
189

A developer wants to ensure that a method `area` in a base class `Shape` must be overridden by any concrete subclass. The developer writes `class Shape(ABC):` and `@abstractmethod def area(self): ...`. A colleague then creates `class Circle(Shape):` without implementing `area` and tries to instantiate `Circle()`. What happens?

Easy
190

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

Hard
191

You are placing several widgets in a window using the grid() geometry manager and want a widget to span multiple columns in the same row. Which grid() option accomplishes this?

Easy
192

You are writing a script that downloads a large file from a REST endpoint using `requests.get(url, stream=True)`. You want to write the content to disk in chunks rather than loading it all into memory. Which approach correctly implements chunked reading?

Easy
193

You are designing a class `Connection` that must ensure only one instance exists and that the same instance is returned whenever `Connection()` is called. You implement this using `__new__` to control instance creation, and you also define `__init__`. During testing, you notice that `__init__` runs every time `Connection()` is called, even though `__new__` returns the existing singleton instance. What is the most appropriate way to prevent `__init__` from reinitializing the singleton on subsequent calls?

Medium
194

A developer defines `class Config:` with `__slots__ = ('host', 'port')`. Later, they want to add a new attribute `timeout` to an existing instance without modifying the class. They write `cfg.timeout = 30` and receive an `AttributeError`. Which change would allow per-instance `timeout` assignment while keeping `__slots__` for `host` and `port`?

Hard
195

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

Medium
196

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

Hard
197

You are designing a Python REST API client that must handle HTTP errors gracefully. The client uses the requests library. Which TWO of the following statements about error handling with requests are correct? (Choose two.)

Hard
198

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

Medium
199

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?

Medium
200

You are developing a Python application that uses a third-party library. You need to ensure that your code handles exceptions raised by that library in a way that is both robust and follows best practices. The library raises a custom exception named LibraryError, which is a subclass of Exception. Your function calls a method that may raise LibraryError. Which of the following is the best approach to handle this exception?

Medium
201

You are building a Tkinter application with a menu bar. You want to add a 'File' menu with an 'Exit' item that terminates the application when selected. Which command should you associate with the 'Exit' menu item to properly close the application?

Medium
202

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

Easy
203

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

Easy
204

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

Hard
205

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

Medium
206

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?

Hard
207

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

Medium
208

You are writing a Python script that needs to send a GET request to a REST API and parse the JSON response. The API requires an API key passed as a query parameter. Which code snippet correctly performs this request using the requests library?

Easy
209

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

Medium
210

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

Medium
211

You are creating a Tkinter GUI with a Canvas widget to draw a simple chart. You need to draw a filled blue rectangle from (50, 50) to (150, 100). Which Canvas method call achieves this?

Easy
212

What is the purpose of the __repr__ method?

Easy
213

A developer is writing a Python module and wants to follow best practices for documenting functions. Which TWO of the following are recommended by PEP 257 for docstrings? (Choose two.)

Medium
214

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

Medium
215

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

Hard
216

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

Medium
217

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

Medium
218

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

Medium
219

You maintain a Tkinter inventory dashboard whose main window contains a large frame with a Treeview listing warehouse items. Operators complain that when they maximize the window, the Treeview stays at its original size and leaves a large empty gray area. The frame is already managed with grid() and the Treeview is placed inside that frame with pack(). Which single change most directly makes the Treeview grow with the frame when the window is resized?

Medium
220

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

Hard
221

You are building a Tkinter application that uses a ttk.Treeview to display a list of employees. Each employee has an ID, name, and department. You want to display the data in columns with headings, and you need the ID column to be hidden. Which approach correctly configures the Treeview to achieve this?

Hard
222

You are implementing a class that represents a monetary amount. You want the expression amount1 + amount2 to return a new Money instance, and you also want amount1 + 5 to work by treating 5 as a Money with zero cents. However, 5 + amount1 should raise a TypeError. Which implementation achieves this behavior?

Hard
223

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

Easy
224

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

Hard
225

You are writing a Python utility that copies a directory tree to a network share using shutil. You must preserve file metadata and fail loudly if the destination already contains a conflicting file, rather than silently overwriting it. Which TWO shutil features satisfy these requirements? (Choose two.)

Hard
226

You are designing a REST client that must call an endpoint protected by OAuth 2.0 using the client credentials grant. The authorization server expects the client identifier and client secret to be sent in the request body as `application/x-www-form-urlencoded`, along with `grant_type=client_credentials`. Which `requests` call correctly obtains the token?

Hard
227

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

Medium
228

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

Medium
229

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

Easy
230

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

Easy
231

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

Medium
232

You are building a desktop tool with tkinter. A user clicks a button, and while a long file-compression routine runs you want a small window with a progress bar to stay visible and animated; the main application window must remain responsive to the user's clicks throughout. Which approach should you use?

Medium
233

You are building a Python script that needs to create a ZIP archive containing files from a directory. You want to preserve the directory structure inside the archive. Which approach using the zipfile module correctly adds the file '/data/reports/summary.txt' as 'reports/summary.txt' inside the archive?

Hard
234

A developer is writing a function that computes the average of a list of numbers. The function should not modify the input list. Which annotation best communicates this intent and aligns with PEP 484 best practices?

Medium
235

When using configparser, how do you handle multiline values?

Hard
236

A developer is writing a module-level variable that holds the maximum number of retries for a network client and will never change during runtime. Which naming convention does PEP 8 recommend for this constant?

Easy
237

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

Easy
238

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

Easy
239

Which comment style is preferred for block comments in Python?

Easy
240

Which TWO of the following are true about magic methods?

Medium
241

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

Hard
242

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

Medium
243

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

Hard
244

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

Medium
245

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

Hard
246

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

Medium
247

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

Easy
248

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

Easy
249

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?

Hard
250

Which THREE practices improve documentation maintenance?

Medium
251

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

Easy
252

You are designing a plugin registry that must automatically register every concrete subclass of a base class `Plugin` at the moment the subclass is defined, without requiring any explicit registration call in the subclass body. You want to avoid a metaclass because the project already uses `ABCMeta` for the base class and you do not want to introduce metaclass conflicts. Which approach best satisfies this requirement?

Medium
253

A developer is writing a Python module and wants to follow PEP 8's recommendations for imports. The module currently has the following imports: `import os`, `import sys`, `import requests`, `from collections import defaultdict`. According to PEP 8, how should these imports be grouped and ordered?

Medium
254

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

Easy
255

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

Medium
256

You are developing a Python script that needs to determine the absolute path of a file located in a directory relative to the script's location. You decide to use the os.path module. Which of the following functions should you use to obtain the absolute path without resolving symbolic links?

Hard
257

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?

Easy
258

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?

Hard
259

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

Hard
260

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

Hard
261

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

Medium
262

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?

Medium
263

You are designing a Python application that consumes a REST API which returns JSON data. The API responses can be large, and you need to process the JSON incrementally to avoid loading the entire response into memory. The server supports chunked transfer encoding. Which of the following techniques should you use with the 'requests' library to stream the response and parse it incrementally?

Hard
264

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

Easy
265

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

Easy
266

You are implementing a REST API client in Python using the 'requests' library. The API requires authentication using OAuth 2.0. You need to obtain an access token and then use it to authenticate subsequent requests. Which TWO of the following statements about handling OAuth 2.0 with 'requests' are correct? (Choose two.)

Hard
267

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

Hard
268

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?

Medium
269

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

Easy
270

You are building a configuration manager that reads an INI file. A section contains the key-value pair `timeout = 30`. You need to retrieve the value as an integer, but if the key is missing, you want to get 60 without raising an exception. Which code snippet achieves this using the `configparser` module?

Medium
271

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

Easy
272

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

Easy
273

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

Medium
274

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?

Medium
275

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

Medium
276

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

Medium
277

A Python developer is writing a function that reads a configuration file and returns a dictionary. They want to follow PEP 8 and best practices for function design and documentation. Which two of the following should they do? (Choose two.)

Medium
278

A team is reviewing a module where a helper function `_normalize_path` is prefixed with a single underscore. A new developer asks which statement best describes the intent of that naming choice according to common Python conventions.

Medium
279

You are writing a Python script that must download a large file from a REST API endpoint. The file is several gigabytes, and you want to avoid loading it entirely into memory. Which approach using the requests library is most memory-efficient?

Medium
280

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

Medium
281

How do you set a specific font for a widget?

Medium
282

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

Medium
283

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

Hard
284

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

Hard
285

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

Hard
286

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

Easy
287

Your team uses a REST API that requires a Bearer token in the Authorization header for every request. You want to configure a `requests.Session` so that all requests made through it automatically include this header, and you also want to reuse the underlying TCP connection across calls. Which approach is correct?

Medium
288

You are developing a Tkinter application that includes a Canvas widget for drawing a dynamic bar chart. The chart data updates every second, and you must redraw the bars. To avoid visual flicker and improve performance, you decide to reuse existing canvas items instead of deleting and recreating them. Which Canvas method should you use to change the height of an existing rectangle item identified by its item ID?

Medium
289

A Python developer is reviewing code and notices that a function has a default argument value set to an empty list: `def append_to(element, target=[]):`. According to best practices, what is the recommended way to handle mutable default arguments?

Easy
290

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?

Hard

Frequently asked questions

What does the scenario questions domain cover on the PCPP1 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 290 scenario questions questions in the PCPP1 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.