Python Institute · Free Practice Questions · Last reviewed May 2026
30real exam-style questions organised by domain, each with the correct answer highlighted and a plain-English explanation of why it's right — and why the others are wrong.
In the context of the Descriptor Protocol, what is the primary difference between a data descriptor and a non-data descriptor?
Non-data descriptors can override instance dictionary lookup.
Data descriptors define __set__ or __delete__, whereas non-data descriptors do not.
This is the strict definition of the descriptor protocol's precedence.
Data descriptors only function with class attributes.
Non-data descriptors are always read-only.
How do you correctly call a method from a sibling class in a diamond inheritance structure using super()?
Call the grandparent class directly.
Use super() in each class to delegate to the next class in the MRO.
super() ensures that each class in the MRO is initialized exactly once.
Use the __bases__ attribute to iterate through parents.
Explicitly call the sibling class method by name.
Which magic method is responsible for providing the informal string representation of an object, typically used for user-facing output?
__str__
__str__ is the standard method for informal string conversion.
__format__
__unicode__
__repr__
What is the result of applying the @staticmethod decorator to a method inside a class that also defines a metaclass?
The metaclass must manually convert it back to a static method.
It raises a TypeError at class definition time.
The method is correctly bound as a static function regardless of the metaclass.
The descriptor logic for @staticmethod operates independently of the class-level metaclass definition.
The metaclass will treat the method as an instance method.
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?
It prevents the creation of multiple instances during the unpickling process.
Using a metaclass or a decorator ensures that the instance returned during deserialization is the same one already created, maintaining the Singleton property.
The __new__ method cannot accept variable arguments in Python 3.
The __new__ method is reserved for static methods only.
It is required for thread-safe access to the instance variable.
You are implementing the Observer pattern. Why should you avoid using a strong reference to the observers in the subject's list?
It causes circular dependency issues.
It makes the notify method thread-unsafe.
It violates the principle of encapsulation.
It prevents the observer from being garbage collected when it is no longer needed.
Weak references allow the garbage collector to reclaim the observer even if it's in the subject's list.
Want more Advanced Object Oriented Programming practice?
Practice this domainAccording to PEP 257, what is the standard format for a single-line docstring?
Use a single quote for the entire block.
The docstring should span three lines including the summary.
The summary should start on the next line.
Use triple quotes and keep the summary on the same line, ending with a period.
This is the recommended convention for short docstrings.
When naming a constant in Python, which convention does PEP 8 recommend?
UPPER_CASE_WITH_UNDERSCORES.
The standard convention for constants.
PascalCase.
snake_case.
CamelCase.
Which practice is recommended when dealing with 'bare' except clauses in Python?
Use bare 'except:' for performance optimization.
Always specify the exception type you intend to catch.
This prevents catching unintended system-level exceptions.
Use 'except Exception:' as the standard catch-all.
Use 'except:' but log the error immediately.
You are debugging a legacy application and need to ensure that resources like file handles are always closed. Which construct is preferred?
Wrap the file operation in a try-except block.
Manually call file.close() in a finally block.
Use a context manager with the 'with' statement.
This is the Pythonic way to handle resource management.
Rely on the garbage collector to close the handle.
You are writing a library that expects a custom exception. Which practice aligns best with Python's exception handling hierarchy?
Use a mixin class without inheritance.
Inherit from StandardError.
Inherit from BaseException.
Inherit from Exception.
Exception is the correct base class for user-defined exceptions.
When implementing secure coding practices in a web-facing Python application, how should you handle raw user input to prevent command injection?
Pass the entire input string to os.system().
Concatenate the input string into a shell command for execution.
Pass input arguments as a list to subprocess.run(args, shell=False).
This approach treats the input as data rather than an executable command string.
Sanitize input using a custom regex to remove special characters.
Want more Best Practices And Coding Conventions practice?
Practice this domainYou have a Checkbutton and you need to track its state. What is the recommended way to associate a variable with the Checkbutton?
Use the 'onvalue' parameter.
Pass a BooleanVar object to the 'variable' parameter.
Variable objects allow for dynamic tracking of widget values.
Use the state attribute directly.
Use the 'command' parameter to set a global flag.
You want to create a button that closes the GUI application when clicked. Which method should you call inside the command callback?
root.destroy()
destroy() is the standard way to close a window.
root.close()
root.exit()
root.quit()
You want to bind a function 'on_click' to a left mouse button click on a Button widget. Which event sequence string is correct?
<Button-1>
<Button-1> represents the left mouse click.
<Mouse-1>
<Left-Click>
<Click-1>
You need to add a label that displays static text in your GUI. Which widget is most appropriate for this purpose?
tk.Message()
tk.Entry()
tk.Display()
tk.Label()
Label is the standard widget for displaying text.
tk.Text()
In a Tkinter grid layout, you want a button to span across two columns. Which parameter should you use?
columnspan=2
columnspan is the correct parameter for merging grid columns.
span_cols=2
merge=2
cols=2
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?
entry.get()
get() is the correct method to extract the string content from an Entry widget.
entry.content()
entry.text()
entry.value()
Want more Graphical User Interface Programming practice?
Practice this domainWhen using sqlite3.Row, what is the primary benefit over using a standard tuple?
It automatically commits transactions.
It provides dictionary-like access to columns by name.
This feature makes code more readable and robust against schema changes.
It is faster to execute.
It supports multi-threading natively.
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?
parser = ConfigParser(case_sensitive=True)
parser.set_case(True)
parser.optionxform = lambda x: x
Setting optionxform to a function that returns the input string prevents lowercase conversion.
parser.read(file, case='preserve')
You are processing a CSV file using csv.DictReader. If your input file lacks a header row, how do you provide the field names?
csv.DictReader(f, headers=['a', 'b'])
csv.DictReader(f).map(['a', 'b'])
csv.DictReader(f, fieldnames=['a', 'b'])
This correctly maps columns to the provided field names.
csv.DictReader(f, columns=['a', 'b'])
When parsing an XML document using xml.etree.ElementTree, you want to find all 'item' tags that are immediate children of the root element. Which method is most efficient for this?
root.findall('item')
findall('item') retrieves direct children matching the tag name.
root.iter('item')
root.find('item')
root.get('item')
Which method in the xml.dom.minidom module is used to retrieve the value of a specific attribute of an element?
element.attr('attr_name')
element.getAttribute('attr_name')
This is the correct method for accessing attributes in DOM nodes.
element.getAttributeNode('attr_name').value
element.value('attr_name')
element['attr_name']
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?
logging.getLogger('urllib3').setLevel(logging.WARNING)
This explicitly sets the log level for the specified library logger.
logging.config.dictConfig({'urllib3': 'WARNING'})
logging.basicConfig(level=logging.WARNING)
logging.setLevel('urllib3', logging.WARNING)
Want more Library Modules practice?
Practice this domainWhen working with raw sockets, what does the 'socket.SOCK_STREAM' constant represent?
UDP datagram sockets
Raw network sockets
TCP connection-oriented sockets
SOCK_STREAM provides sequenced, reliable, two-way byte streams.
Unix domain sockets only
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?
sock.bind(('192.168.1.50', 8080))
sock.accept()
sock.connect(('192.168.1.50', 8080))
The connect method accepts a tuple containing the host IP and port.
sock.listen(1)
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?
Wrap the access in a try-except KeyError block
Check 'if 'key' in response.json():' before access
Use response.json()['key'] and assume the API schema is always correct
Use response.json().get('key', default_value)
This is the idiomatic way to handle optional keys in dictionaries.
When using the 'socket' module, what is the effect of calling 'socket.settimeout(5.0)' on a socket object?
It sets the send buffer size to 5.0 bytes
It causes the operation to raise a socket.timeout after 5 seconds
This is the correct behavior for blocking operations.
It blocks the thread for exactly 5 seconds
It forces the socket to close after 5 seconds of inactivity
In the 'requests' library, which HTTP method is typically used to update an existing resource on a server?
PUT
PUT is the semantic method for resource replacement/updates.
POST
GET
DELETE
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?
Implement an exponential backoff strategy with jitter
Exponential backoff with jitter is the industry standard for handling rate limits.
Switch to a different base URL immediately
Ignore 429 errors and continue execution
Retry immediately in a loop until successful
Want more Networking And Restful Apis practice?
Practice this domainThe PCPP1 exam has 200 questions and must be completed in 120 minutes. The passing score is 700/1000.
Scenario-based questions covering exam objectives with detailed answer explanations.
The exam covers 5 domains: Advanced Object Oriented Programming, Best Practices And Coding Conventions, Graphical User Interface Programming, Library Modules, Networking And Restful Apis. Questions are weighted by domain — higher-weight domains appear more on your actual exam.
No. These are original exam-style practice questions written against the official Python Institute PCPP1 exam objectives. They are not copied from the real exam. Courseiva focuses on genuine understanding, not memorisation of braindumps.
Courseiva tracks your accuracy per domain and routes you toward weak areas automatically. Free, no account required.