Python Online Certification (POC) — Questions and Answers
Question 1: What is parameterized testing in pytest?
- Running the same test function with multiple different input values (Correct answer)
- Testing with environment variable overrides
- Testing with multiple fixtures simultaneously
- Executing tests in parallel processes
Correct answer: Running the same test function with multiple different input values
Parameterized testing uses `@pytest.mark.parametrize` to run a single test function with multiple sets of arguments automatically.
Question 2: How do you check for syntax errors in Python?
- Using a linter or running the code (Correct answer)
- Cannot be detected
- Only during runtime
- Through print statements
Correct answer: Using a linter or running the code
Syntax errors are fundamental errors in the structure of the code that prevent Python from understanding and executing it. They are typically detected either by a linter (a static code analysis tool) before runtime, or by the Python interpreter itself when you attempt to run the code. The interpreter will raise a `SyntaxError` immediately upon parsing.
Question 3: What does `collections.defaultdict(list)` do when a missing key is accessed?
- Automatically creates an empty list for that key (Correct answer)
- Returns None
- Raises KeyError
- Returns an empty string
Correct answer: Automatically creates an empty list for that key
`defaultdict` calls the factory function (`list`) to generate a default value for any missing key, avoiding KeyError.
Question 4: What is the result of `set([1, 2, 2, 3, 3, 3])`?
- {1, 2, 3} (Correct answer)
- [1, 2, 3]
- {1, 2, 2, 3, 3, 3}
- Error
Correct answer: {1, 2, 3}
Converting a list to a set removes all duplicate values, leaving only unique elements.
Question 5: What is the role of a Python `__slots__` declaration in memory-efficient system design?
- It controls the order in which attributes are serialized to JSON
- It prevents dynamic attribute creation and reduces per-instance memory overhead (Correct answer)
- It limits the number of instances a class can create
- It defines the public interface of a class for documentation
Correct answer: It prevents dynamic attribute creation and reduces per-instance memory overhead
__slots__ replaces the per-instance __dict__ with a fixed-size array, significantly reducing memory usage when millions of instances are created.
Question 6: Which Python library is commonly used to implement asynchronous task queues in a distributed system?
- Flask
- Pydantic
- SQLAlchemy
- Celery (Correct answer)
Correct answer: Celery
Celery is a distributed task queue library for Python that enables offloading work to background workers using brokers like Redis or RabbitMQ.
Question 7: Which statement about Python decorators is true?
- A decorator is a function that takes a function and returns a modified function (Correct answer)
- Only one decorator can be applied per function
- Decorators can only be applied to classes
- Decorators permanently alter the original function's source code
Correct answer: A decorator is a function that takes a function and returns a modified function
A decorator is a higher-order function that wraps another function, extending or altering its behavior without modifying its source.
Question 8: Given `d = {'a': 1, 'b': 2}`, what does `d.get('c', 0)` return?
- False
- 0 (Correct answer)
- None
- KeyError
Correct answer: 0
`dict.get(key, default)` returns the default value (0 here) when the key is not found, instead of raising KeyError.
Question 9: Which mode opens a file and raises `FileExistsError` if the file already exists?
- 'r+'
- 'a'
- 'x' (Correct answer)
- 'w'
Correct answer: 'x'
Mode `'x'` (exclusive creation) opens a file for writing only if it does not already exist, raising `FileExistsError` otherwise.
Question 10: Which pandas method converts a DataFrame column containing string dates into datetime objects?
- df['col'].to_date()
- df['col'].astype('datetime')
- df['col'].parse_date()
- pd.to_datetime(df['col']) (Correct answer)
Correct answer: pd.to_datetime(df['col'])
pd.to_datetime() parses string or numeric representations of dates into pandas Timestamp objects.
Question 11: What is the main advantage of using Python's `asyncio` event loop in a high-concurrency system design?
- It provides automatic garbage collection for large objects
- It handles thousands of concurrent I/O-bound operations without blocking threads (Correct answer)
- It replaces the need for a database connection pool
- It automatically distributes work across CPU cores
Correct answer: It handles thousands of concurrent I/O-bound operations without blocking threads
asyncio uses cooperative multitasking to handle many I/O-bound operations concurrently on a single thread without thread overhead.
Question 12: Which file mode string opens a binary file for both reading and writing without truncating it?
- xb
- ab+
- wb
- rb+ (Correct answer)
Correct answer: rb+
`rb+` opens a binary file for both reading and writing, preserving existing content, while `wb` truncates the file.
Question 13: Your script produces `IndentationError: unexpected indent`. What is the most likely cause?
- Dividing by zero inside a loop
- Calling a function that doesn't exist
- Using a variable before assigning it
- Mixing tabs and spaces in the same block (Correct answer)
Correct answer: Mixing tabs and spaces in the same block
Python treats tabs and spaces as different characters, so mixing them causes inconsistent indentation levels.
Question 14: What does setting thread.daemon = True do before starting a thread?
- Makes the thread run in the background and automatically exit when the main program ends (Correct answer)
- Allocates additional memory to the thread for large workloads
- Raises the thread's execution priority to the highest level
- Prevents the thread from being interrupted by signals
Correct answer: Makes the thread run in the background and automatically exit when the main program ends
Daemon threads are background threads that do not prevent the program from exiting; they are killed automatically when all non-daemon threads finish.
Question 15: What is the primary benefit of applying Dependency Injection (DI) in a Python application?
- It makes dependencies explicit and swappable, improving testability and flexibility (Correct answer)
- It reduces the number of modules needed in a project
- It automatically optimizes import order at startup
- It enforces type checking at runtime for all function arguments
Correct answer: It makes dependencies explicit and swappable, improving testability and flexibility
DI decouples class creation from class use by passing dependencies from the outside, making it easy to substitute mocks in tests or swap implementations.
Question 16: What is the purpose of `MagicMock` in Python's `unittest.mock` module?
- To mock only database connection objects
- To generate random test data automatically
- To create async-compatible test doubles
- To create mock objects that also support magic (dunder) methods (Correct answer)
Correct answer: To create mock objects that also support magic (dunder) methods
`MagicMock` is a subclass of `Mock` that pre-configures support for Python magic methods like `__len__`, `__str__`, and `__iter__`.
Question 17: What role does documentation play in system architecture?
- It slows down development
- It is only needed for compliance audits
- It enables team understanding, maintenance, and future development decisions (Correct answer)
- It is optional for small systems
Correct answer: It enables team understanding, maintenance, and future development decisions
Architecture documentation is essential for team understanding, system maintenance, and informed decision-making about future development and changes.
Question 18: What does the 'break' keyword do in a loop?
- Repeats the loop.
- Skips current iteration.
- Restarts the loop.
- Exits the loop (Correct answer)
Correct answer: Exits the loop
The `break` keyword in Python is used to terminate the current loop prematurely. When `break` is encountered inside a `for` or `while` loop, the loop immediately stops, and program execution continues with the statement immediately following the loop. It's often used to exit a loop based on a specific condition.
Question 19: What does the `collections.deque` class offer that a regular list does not?
- Built-in JSON serialization
- Automatic sorting of elements
- Thread-safe iteration
- O(1) append and pop from both ends (Correct answer)
Correct answer: O(1) append and pop from both ends
`deque` provides O(1) time complexity for appending and popping from both the left and right ends, while list pop(0) is O(n).
Question 20: What is the output of `list(map(str, [1, 2, 3]))`?
- [1, 2, 3]
- Error
- ['str', 'str', 'str']
- ['1', '2', '3'] (Correct answer)
Correct answer: ['1', '2', '3']
`map(str, [1,2,3])` applies `str()` to each element, converting integers to strings, resulting in ['1','2','3'].
Question 21: What does Python's `cProfile` module report that helps identify performance bottlenecks?
- Disk I/O per module
- Thread contention statistics
- Memory leaks per function
- Number of calls and cumulative time per function (Correct answer)
Correct answer: Number of calls and cumulative time per function
cProfile records the call count, total time, and cumulative time for every function, making it straightforward to identify hot spots.
Question 22: What is the purpose of a staging environment?
- To run performance tests only
- To test configurations and changes before deploying to production (Correct answer)
- To store backup data
- To host development tools
Correct answer: To test configurations and changes before deploying to production
Staging environments replicate production conditions for testing configurations and changes, reducing the risk of deployment failures affecting live systems.
Question 23: What does the 'with' statement do when opening a file?
- It locks the file
- It closes the file automatically (Correct answer)
- It encrypts the file
- It writes to the file automatically
Correct answer: It closes the file automatically
The 'with' statement in Python creates a context manager, which ensures that resources are properly managed. When used with file operations, it guarantees that the file's `close()` method is automatically called once the block of code is exited, even if errors occur. This prevents resource leaks and simplifies file handling.
Question 24: Which operator is used for exponentiation in Python?
- ^
- //
- ** (Correct answer)
- exp
Correct answer: **
In Python, the double asterisk `**` operator is used for exponentiation, meaning "to the power of." For example, `2 ** 3` would calculate 2 raised to the power of 3, resulting in 8. This operator provides a concise way to perform power calculations.
Question 25: In Python packaging, what does a `MANIFEST.in` file specify?
- Test discovery configuration
- Additional files to include in source distributions (Correct answer)
- The list of Python files to compile
- Installed console scripts and entry points
Correct answer: Additional files to include in source distributions
`MANIFEST.in` uses directives like `include` and `recursive-include` to add non-Python files (docs, data) to a source distribution.
Question 26: When should performance testing be conducted?
- Throughout the development lifecycle and before major releases (Correct answer)
- Only after receiving user complaints
- Only for applications with more than 1000 users
- Once during initial deployment only
Correct answer: Throughout the development lifecycle and before major releases
Performance testing throughout the lifecycle catches issues early when they are cheaper to fix and prevents performance regressions in new releases.
Question 27: Which Python pattern separates the construction of a complex object from its representation?
- Builder (Correct answer)
- Strategy
- Flyweight
- Proxy
Correct answer: Builder
The Builder pattern uses a director and builder classes to construct complex objects step-by-step, separating construction logic from the final representation.
Question 28: Which keyword is used to inherit from a parent class in Python?
- Parentheses with the parent class name in the class definition (Correct answer)
- implements
- extends
- inherits
Correct answer: Parentheses with the parent class name in the class definition
Python uses parentheses in the class definition (e.g., `class Child(Parent):`) to indicate inheritance.
Question 29: Which file extension is used for Python modules?
- .pym
- .pt
- .py (Correct answer)
- .exe
Correct answer: .py
Python source code files, including those intended to be imported as modules, are conventionally saved with the `.py` file extension. This extension helps the operating system and Python interpreter identify the file as a Python script or module. Other extensions like `.pym` or `.pt` are not standard for Python modules.
Question 30: When should an issue be escalated to a higher support level?
- Only after exhausting every possible solution
- Never, all issues should be resolved at the first level
- When the issue exceeds your technical expertise or authorization level (Correct answer)
- Immediately, before attempting any resolution
Correct answer: When the issue exceeds your technical expertise or authorization level
Issues should be escalated when they exceed the current level technical expertise or authorization, ensuring timely resolution while maintaining appropriate support boundaries.
Question 31: What happens when a Python `assert` statement's condition evaluates to False?
- It returns False
- It prints a warning message
- It terminates the program silently
- It raises AssertionError (Correct answer)
Correct answer: It raises AssertionError
When an `assert` condition is False, Python raises an `AssertionError`, optionally with a custom message.
Question 32: Which pip command installs a package in 'editable' (development) mode from a local directory?
- pip install --source .
- pip install --editable=local .
- pip install --dev .
- pip install -e . (Correct answer)
Correct answer: pip install -e .
The `-e` flag (short for `--editable`) installs a package so changes in the source directory are immediately reflected without reinstalling.
Question 33: What does enabling `SECURE_HSTS_SECONDS` in a Python Django application accomplish?
- Limits the number of secure connections per second
- Sets the session cookie expiry time in seconds
- Instructs browsers to only connect via HTTPS for the specified duration via a response header (Correct answer)
- Enforces password minimum length on the login form
Correct answer: Instructs browsers to only connect via HTTPS for the specified duration via a response header
Setting `SECURE_HSTS_SECONDS` causes Django to emit the `Strict-Transport-Security` response header, telling browsers to refuse HTTP connections for the configured period.
Question 34: What is the output of `tuple([1, 2, 3]) == (1, 2, 3)`?
- False
- None
- TypeError
- True (Correct answer)
Correct answer: True
`tuple([1, 2, 3])` constructs the tuple `(1, 2, 3)`, which compares equal to the literal `(1, 2, 3)`.
Question 35: Which data structure should you use to count the frequency of each word in a text efficiently?
- tuple
- list
- set
- collections.Counter (Correct answer)
Correct answer: collections.Counter
`collections.Counter` is a dict subclass designed to count hashable objects, making it ideal for frequency analysis.
Question 36: What does the `seek(0)` method do on a file object?
- Truncates the file
- Moves the file pointer to the beginning (Correct answer)
- Reads the first byte
- Closes and reopens the file
Correct answer: Moves the file pointer to the beginning
`seek(0)` repositions the file pointer to byte offset 0, i.e., the start of the file, allowing re-reading from the beginning.
Question 37: Which statement about Python's `with` statement is correct?
- It creates a new variable scope
- It replaces try/except blocks entirely
- It automatically calls __enter__ and __exit__ on a context manager (Correct answer)
- It is only used for file I/O
Correct answer: It automatically calls __enter__ and __exit__ on a context manager
The `with` statement invokes `__enter__` at the start and guarantees `__exit__` is called when the block ends, even if an exception occurs.
Question 38: Which Python tool is the standard for measuring code coverage during testing?
- codecheck.py
- testcov
- coverage.py (Correct answer)
- measure.py
Correct answer: coverage.py
`coverage.py` is the standard Python tool for measuring code coverage and can produce detailed HTML reports.
Question 39: What is the primary consideration when designing system architecture?
- Minimizing the number of components
- Matching competitor architectures
- Using the newest technology available
- Scalability, reliability, and alignment with business requirements (Correct answer)
Correct answer: Scalability, reliability, and alignment with business requirements
System architecture must prioritize scalability, reliability, and alignment with business requirements to ensure long-term viability and value delivery.
Question 40: Which built-in function returns a list of names defined in the current namespace or a given object?
- globals()
- vars()
- inspect()
- dir() (Correct answer)
Correct answer: dir()
`dir()` returns a sorted list of names in the current scope or the attributes of the passed object.
Question 41: In the `logging` module, which level is HIGHER in severity than WARNING?
- INFO
- ERROR (Correct answer)
- NOTICE
- DEBUG
Correct answer: ERROR
The logging severity order is DEBUG < INFO < WARNING < ERROR < CRITICAL.
Question 42: Given `class B(A):`, what happens if `B` does not override method `foo` defined in `A`?
- Calling `b.foo()` executes `A`'s version of `foo` (Correct answer)
- Calling `b.foo()` raises an AttributeError
- Python automatically creates an empty `foo` in `B`
- The method is deleted from `B`
Correct answer: Calling `b.foo()` executes `A`'s version of `foo`
Python's MRO (Method Resolution Order) looks up the inheritance chain, so `B` inherits and can use `A`'s `foo` unchanged.
Question 43: Which loop is used to iterate over a sequence in Python?
- while-do
- loop
- for (Correct answer)
- repeat
Correct answer: for
The `for` loop in Python is specifically designed to iterate over the elements of a sequence (like a list, tuple, string, or range) or other iterable objects. It executes a block of code for each item in the sequence, making it ideal for processing collections of data.
Question 44: Which Python library provides JIT compilation to speed up numerical Python code?
- PyPy
- Cython
- cffi
- Numba (Correct answer)
Correct answer: Numba
Numba uses LLVM to JIT-compile Python functions decorated with @jit, achieving near-C speed for numeric loops.
Question 45: Which method is called when an object is about to be garbage collected?
- __exit__
- __delete__
- __init__
- __del__ (Correct answer)
Correct answer: __del__
`__del__` is the destructor method, called when the object's reference count drops to zero.
Question 46: When using `with open('file.txt') as f:`, what happens to the file when the block exits?
- It is flushed but remains open
- It is deleted
- Nothing happens
- It is automatically closed (Correct answer)
Correct answer: It is automatically closed
The context manager protocol calls `f.__exit__()`, which closes the file automatically even if an exception occurs.
Question 47: Which `traceback` module function prints the current exception's traceback to stderr?
- traceback.dump()
- traceback.print_exc() (Correct answer)
- traceback.format_tb()
- traceback.show()
Correct answer: traceback.print_exc()
`traceback.print_exc()` prints the traceback of the currently handled exception, mimicking Python's default error output.
Question 48: Which of the following is a mutable data type in Python?
- frozenset
- list (Correct answer)
- str
- tuple
Correct answer: list
Lists are mutable; their elements can be added, removed, or changed after creation, unlike tuples, frozensets, and strings.
Question 49: What does the `@pytest.fixture` decorator do?
- Configures a test timeout value
- Sets the test execution order
- Marks a test as expected to fail
- Defines a reusable setup function injected into test parameters (Correct answer)
Correct answer: Defines a reusable setup function injected into test parameters
The `@pytest.fixture` decorator defines a function that provides a fixed baseline or shared resource, injected by name into test function parameters.
Question 50: What is the result of `[x**2 for x in range(4) if x % 2 == 0]`?
- [0, 4] (Correct answer)
- [4, 16]
- [0, 1, 4, 9]
- [1, 9]
Correct answer: [0, 4]
range(4) gives 0,1,2,3; filtering even values gives 0 and 2; squaring gives [0, 4].
Question 51: In Python system design, what is the primary purpose of using a message broker like RabbitMQ or Redis Pub/Sub?
- To provide distributed locking across microservices
- To decouple producers and consumers by asynchronously passing messages (Correct answer)
- To replicate code deployments across multiple servers
- To cache database query results near the application layer
Correct answer: To decouple producers and consumers by asynchronously passing messages
Message brokers enable asynchronous communication between services, so producers don't block waiting for consumers and services remain loosely coupled.
Question 52: Which profiling tool provides line-by-line memory usage statistics for Python code?
- memory_profiler (Correct answer)
- cProfile
- tracemalloc
- pyflakes
Correct answer: memory_profiler
memory_profiler's @profile decorator reports memory consumption on a per-line basis, helping pinpoint memory-hungry code.
Question 53: Which of the following correctly defines a class method in Python?
- Using the @classmethod decorator with cls as first parameter (Correct answer)
- Defining a method without self
- Using the @method decorator
- Using the @staticmethod decorator
Correct answer: Using the @classmethod decorator with cls as first parameter
A class method is defined with `@classmethod` and receives the class itself (conventionally named `cls`) as its first argument.
Question 54: What is the MRO (Method Resolution Order) used for?
- Organizing methods by execution speed
- Sorting class attributes alphabetically
- Defining the order of `__init__` calls
- Determining the order in which base classes are searched when looking up a method (Correct answer)
Correct answer: Determining the order in which base classes are searched when looking up a method
MRO defines the lookup order for methods and attributes in class hierarchies, especially important in multiple inheritance.
Question 55: What is the key difference between a unit test and an integration test?
- Unit tests are always faster; integration tests are always more accurate
- Unit tests are automated; integration tests are always manual
- Unit tests must use mocks; integration tests must use real databases
- Unit tests verify isolated components; integration tests verify multiple components interacting (Correct answer)
Correct answer: Unit tests verify isolated components; integration tests verify multiple components interacting
Unit tests verify individual components in isolation, while integration tests verify that multiple components work together correctly.
Question 56: What is the role of 'transactions' in database management when using Python's sqlite3 module?
- They automatically back up the database
- They group SQL operations so all succeed or all fail atomically (Correct answer)
- They encrypt data before writing
- They cache queries in memory for performance
Correct answer: They group SQL operations so all succeed or all fail atomically
A transaction groups multiple SQL statements into an atomic unit; if any statement fails, a rollback reverts all changes.
Question 57: In a Python distributed system, what does 'eventual consistency' mean?
- All nodes see the same data simultaneously after every write
- Consistency is enforced by retrying failed writes indefinitely
- Data is only consistent within a single transaction boundary
- Given enough time without new updates, all replicas converge to the same value (Correct answer)
Correct answer: Given enough time without new updates, all replicas converge to the same value
Eventual consistency is a model where replicas may temporarily diverge but will converge to the same state once updates propagate through the system.
Question 58: How should security be incorporated into system architecture?
- Only addressed when vulnerabilities are discovered
- Added after all functional features are complete
- Integrated from the initial design phase as a foundational requirement (Correct answer)
- Handled entirely by the network team
Correct answer: Integrated from the initial design phase as a foundational requirement
Security must be integrated from the initial design phase (security by design) to be effective, as retrofitting security is more costly and less thorough.
Question 59: In Python's asyncio framework, which keyword suspends a coroutine until an awaitable completes?
- yield
- await (Correct answer)
- suspend
- pause
Correct answer: await
The `await` keyword suspends the current coroutine and yields control back to the event loop, which resumes it when the awaitable is done.
Question 60: When designing a Python system that must handle millions of events per second, which architecture pattern is most appropriate?
- Batch processing with cron jobs
- Synchronous REST with connection pooling
- Monolithic with multi-threading
- Event-driven architecture with message streaming (Correct answer)
Correct answer: Event-driven architecture with message streaming
Event-driven architecture with message streaming (e.g., Kafka) decouples producers and consumers, enabling high-throughput real-time processing.
Question 61: What is the purpose of using `memoryview` in Python?
- To access buffer protocol objects without copying data (Correct answer)
- To profile memory allocations
- To display memory usage statistics
- To create shared memory between processes
Correct answer: To access buffer protocol objects without copying data
memoryview exposes the buffer protocol, letting you slice and pass large byte sequences to functions without copying the underlying data.
Question 62: What does the `global` keyword do inside a function?
- Prevents the variable from being modified
- Creates a new global variable only
- Declares that a variable refers to the global scope (Correct answer)
- Imports a variable from another module
Correct answer: Declares that a variable refers to the global scope
The `global` keyword tells Python to use the variable from the global (module-level) scope rather than creating a local one.
Question 63: What is the advantage of using `asyncio` for I/O-bound tasks in Python?
- Handles many concurrent I/O operations with a single thread via event loop (Correct answer)
- Bypasses the GIL for all operations
- Executes tasks on multiple CPU cores simultaneously
- Automatically parallelizes loops
Correct answer: Handles many concurrent I/O operations with a single thread via event loop
asyncio's event loop suspends coroutines waiting on I/O and runs others, achieving high concurrency without the overhead of multiple threads or processes.
Question 64: In a virtual environment created with `venv`, where are installed packages stored?
- In `/usr/local/lib/python`
- In the user's home directory
- In the system site-packages
- In the `Lib/site-packages` subdirectory of the venv folder (Correct answer)
Correct answer: In the `Lib/site-packages` subdirectory of the venv folder
A venv maintains its own isolated `Lib/site-packages` directory separate from the global Python installation.
Question 65: What does TDD stand for in software development?
- Technical Design Document
- Top-Down Design
- Test Data Definition
- Test-Driven Development (Correct answer)
Correct answer: Test-Driven Development
TDD (Test-Driven Development) is a methodology where tests are written before the actual implementation code.
Question 66: What decorator is used in unittest to mark a test that should be skipped?
- @ignore
- @pytest.skip
- @skip
- @unittest.skip (Correct answer)
Correct answer: @unittest.skip
The `@unittest.skip` decorator marks a test to be skipped with an optional reason string.
Question 67: How should configuration changes be tracked?
- Through version control systems with documented change rationale (Correct answer)
- Only in emergency situations
- In personal notes
- Verbally between team members
Correct answer: Through version control systems with documented change rationale
Version control with documented rationale provides an audit trail, enables rollbacks, and ensures team visibility into all configuration changes.
Question 68: How do you determine if an optimization was successful?
- Assume success if no errors occur
- Check if the system is still running
- Compare post-optimization metrics against the established baseline (Correct answer)
- Rely on subjective user feedback
Correct answer: Compare post-optimization metrics against the established baseline
Comparing post-optimization metrics against established baselines provides objective evidence of improvement and quantifies the impact of changes.
Question 69: What happens when you raise an exception without an argument inside an `except` block?
- Python ignores the raise statement
- A new RuntimeError is created
- A SyntaxError is thrown
- The caught exception is re-raised (Correct answer)
Correct answer: The caught exception is re-raised
A bare `raise` inside an `except` block re-raises the currently handled exception with its original traceback.
Question 70: What is the purpose of the 'import' statement in Python?
- To comment out code
- To execute code line-by-line
- To define a new function
- To include external modules or libraries (Correct answer)
Correct answer: To include external modules or libraries
The `import` statement in Python is used to bring external modules or libraries into the current program's namespace. This allows you to access functions, classes, and variables defined in those modules, promoting code reusability and modularity. It does not define new functions or execute code line-by-line in the way described.
Question 71: When configuring logging via a dictionary using `logging.config.dictConfig()`, which top-level key specifies the minimum version of the schema?
- schema_version
- config_version
- version (Correct answer)
- logging_version
Correct answer: version
The `version` key is required in dictConfig schemas; currently the only valid value is `1`.
Question 72: Which statement correctly inserts value `99` at index 2 of list `L`?
- L.add(2, 99)
- L.append(2, 99)
- L.insert(2, 99) (Correct answer)
- L[2] = 99
Correct answer: L.insert(2, 99)
`list.insert(i, x)` inserts element `x` before the item at index `i`, shifting subsequent elements right.
Question 73: What is the correct way to open a file for reading?
- open('file.txt', 'x')
- open('file.txt', 'w')
- open('file.txt', 'a')
- open('file.txt') (Correct answer)
Correct answer: open('file.txt')
When using the `open()` function in Python, if no mode is specified, it defaults to `'r'`, which stands for read mode. Therefore, `open('file.txt')` is the correct and most common way to open a file for reading its contents. Other modes like `'w'` (write), `'x'` (exclusive creation), and `'a'` (append) serve different purposes.
Question 74: What method in unittest is used to verify that two values are equal?
- assertEquals()
- verify()
- assertSame()
- assertEqual() (Correct answer)
Correct answer: assertEqual()
`assertEqual(a, b)` checks that `a` and `b` are equal and raises AssertionError if not.
Question 75: How do you create a generator function in Python?
- Use `async def` syntax
- Decorate the function with @generator
- Use the `return` keyword with a list
- Use the `yield` keyword inside a function (Correct answer)
Correct answer: Use the `yield` keyword inside a function
A function containing at least one `yield` statement becomes a generator function that returns a generator iterator.
Question 76: Which data structure should you use in Python when you need the smallest element accessible in O(1) time?
- OrderedDict
- deque
- sorted list
- heapq-managed list (Correct answer)
Correct answer: heapq-managed list
heapq maintains a min-heap invariant so the smallest element is always at index 0, accessible in O(1) with O(log n) push/pop.
Question 77: Which data type is used to store True or False values?
- bool (Correct answer)
- int
- char
- str
Correct answer: bool
The `bool` (Boolean) data type in Python is used to represent logical values, which can only be `True` or `False`. These values are fundamental for conditional statements and logical operations, controlling program flow based on truthiness. They are essential for decision-making in programs.
Question 78: What is the primary purpose of security auditing?
- To create busy work for the security team
- To identify vulnerabilities and verify compliance with security policies (Correct answer)
- To find reasons to terminate employees
- To justify security spending
Correct answer: To identify vulnerabilities and verify compliance with security policies
Security auditing identifies vulnerabilities, verifies policy compliance, and provides evidence of due diligence in protecting organizational assets.
Question 79: What does Python's Global Interpreter Lock (GIL) primarily affect?
- Memory allocation speed
- Multiprocessing performance
- I/O-bound threads
- CPU-bound threads running Python bytecode simultaneously (Correct answer)
Correct answer: CPU-bound threads running Python bytecode simultaneously
The GIL prevents multiple native threads from executing Python bytecode at the same time, limiting CPU-bound parallelism within one process.
Question 80: Which file, placed at the root of a package, is read by PyPI and displayed as the package description on the package page?
- CHANGELOG.md
- MANIFEST.in
- DESCRIPTION.txt
- README.md (or README.rst) referenced in setup.py/pyproject.toml (Correct answer)
Correct answer: README.md (or README.rst) referenced in setup.py/pyproject.toml
The README file (Markdown or reStructuredText) is referenced via `long_description` in packaging config and rendered on the PyPI project page.
Question 81: When reading a CSV file with Python's `csv.reader`, what type does each row come back as?
- A tuple of strings
- A string
- A list of strings (Correct answer)
- A dict
Correct answer: A list of strings
`csv.reader` yields each row as a list of strings, where each element corresponds to a field in that row.
Question 82: In a Python application using the Repository pattern, what is the primary responsibility of the repository class?
- To orchestrate multiple service calls in a transaction
- To serialize objects to JSON for API responses
- To abstract data access and provide collection-like interfaces for domain objects (Correct answer)
- To define business rules for domain entities
Correct answer: To abstract data access and provide collection-like interfaces for domain objects
The Repository pattern abstracts the data layer, providing a clean interface for accessing domain objects without exposing database implementation details.
Question 83: Which NumPy operation is generally faster than an equivalent Python for-loop?
- Nested Python loops on NumPy arrays
- Vectorized array arithmetic (Correct answer)
- String operations on NumPy arrays
- List comprehension inside NumPy
Correct answer: Vectorized array arithmetic
NumPy vectorized operations are implemented in C and operate on entire arrays at once, bypassing Python's interpreter overhead per element.
Question 84: Which Python standard library module provides the `uuid4()` function for generating cryptographically random identifiers?
- random
- uuid (Correct answer)
- os
- secrets
Correct answer: uuid
The `uuid` module's `uuid4()` generates a random UUID using `os.urandom()`, making it suitable for generating unpredictable unique identifiers like session IDs.
Question 85: In Python web applications, what is the purpose of setting the `HttpOnly` flag on session cookies?
- Prevents JavaScript from accessing the cookie, mitigating XSS cookie theft (Correct answer)
- Prevents the cookie from being sent over HTTP (requires HTTPS)
- Limits the cookie to HTTP/1.1 connections only
- Forces the server to regenerate the cookie on every request
Correct answer: Prevents JavaScript from accessing the cookie, mitigating XSS cookie theft
The `HttpOnly` flag instructs the browser to block JavaScript access to the cookie, preventing XSS attacks from stealing session identifiers.
Question 86: Which Python micro-framework is most commonly used to build lightweight web applications and REST APIs?
- Django
- Flask (Correct answer)
- Tornado
- Pyramid
Correct answer: Flask
Flask is a lightweight WSGI micro-framework that provides minimal built-in features, making it easy to start building web apps and APIs.
Question 87: A script occasionally raises `ZeroDivisionError` depending on input data. What is the best defensive approach?
- Cast the divisor to float before dividing
- Validate the divisor before dividing and handle the zero case explicitly (Correct answer)
- Replace division with multiplication by a reciprocal
- Wrap every arithmetic operation in a try/except
Correct answer: Validate the divisor before dividing and handle the zero case explicitly
Checking preconditions (guard clauses) prevents the error from occurring rather than catching it after the fact.
Question 88: Which method of threading.Thread should you override in a subclass to define the thread's work?
- start()
- execute()
- begin()
- run() (Correct answer)
Correct answer: run()
Overriding run() defines the code executed in the new thread; start() internally calls run() in a new thread context.
Question 89: What problem does the Circuit Breaker pattern solve in a Python microservices system?
- Preventing SQL injection in service-to-service calls
- Encrypting inter-service communication automatically
- Balancing load evenly across service replicas
- Stopping cascading failures when a downstream service is unavailable (Correct answer)
Correct answer: Stopping cascading failures when a downstream service is unavailable
The Circuit Breaker pattern trips open when a service fails repeatedly, preventing the calling service from wasting resources on doomed requests and allowing time for recovery.
Question 90: In pytest, what built-in fixture provides a temporary directory for test files?
- tmp_path (Correct answer)
- test_dir
- tmpdir
- temp_dir
Correct answer: tmp_path
The `tmp_path` fixture in pytest provides a `pathlib.Path` temporary directory unique to each test invocation.
Question 91: Which keyword is used to define a function in Python?
- define
- func
- def (Correct answer)
- function
Correct answer: def
In Python, the `def` keyword is used to define a function. It stands for "define" and is followed by the function name, parentheses for parameters, and a colon, signaling the start of the function's code block. This keyword is fundamental for creating reusable blocks of code.
Question 92: Which Python module provides built-in unit testing capabilities?
- pytest
- nose
- unittest (Correct answer)
- doctest
Correct answer: unittest
The `unittest` module is Python's built-in testing framework inspired by JUnit.
Question 93: What happens when you open a file with mode `'a'` and write to it?
- Data is appended to the end of the file (Correct answer)
- A new file is always created
- The file is truncated before writing
- A FileExistsError is raised if the file exists
Correct answer: Data is appended to the end of the file
Append mode (`'a'`) positions the write pointer at the end of the file, so new data is added after existing content.
Question 94: What is capacity planning?
- Waiting until resources are exhausted to add more
- Predicting future resource needs based on growth trends and requirements (Correct answer)
- Only planning for current usage levels
- Buying maximum resources upfront
Correct answer: Predicting future resource needs based on growth trends and requirements
Capacity planning uses growth trends and requirements to predict future needs, ensuring adequate resources are available without over-provisioning.
Question 95: When should architectural decisions be reviewed and potentially revised?
- Only when migrating to new hardware
- When requirements change significantly or performance targets are not met (Correct answer)
- Never, once architecture is set it should not change
- Only during annual reviews
Correct answer: When requirements change significantly or performance targets are not met
Architectural decisions should be reviewed when requirements change significantly or performance issues arise, ensuring the system continues to meet evolving needs.
Question 96: Which data structure allows only unique elements?
- List
- Set (Correct answer)
- Tuple
- Dictionary
Correct answer: Set
A Set is a built-in Python data structure that stores an unordered collection of unique elements. It automatically handles the removal of duplicate values. Unlike Lists, Dictionaries, or Tuples, which can contain multiple identical items, a Set ensures that each element is distinct.
Question 97: Which of the following creates a shallow copy of a list `L`?
- list(L.items())
- L.clone()
- copy.deepcopy(L)
- L.copy() (Correct answer)
Correct answer: L.copy()
`L.copy()` (or `L[:]`) creates a shallow copy, duplicating the list but not the objects it references.
Question 98: What is the output of `bool([])` in Python?
- False (Correct answer)
- True
- Error
- None
Correct answer: False
An empty list is falsy in Python, so `bool([])` evaluates to False.
Question 99: When designing a Python system with multiple payment providers, which pattern best allows switching providers without modifying client code?
- Decorator
- Strategy (Correct answer)
- Builder
- Chain of Responsibility
Correct answer: Strategy
The Strategy pattern defines a family of algorithms (payment providers) behind a common interface, allowing the active strategy to be swapped at runtime.
Question 100: What is the correct way to create a variable in Python?
- x := 10
- x = 10 (Correct answer)
- int x = 10
- define x 10
Correct answer: x = 10
In Python, variables are created simply by assigning a value to a name using the assignment operator `=`. Python is dynamically typed, meaning you don't need to declare the variable's type explicitly. The interpreter infers the type based on the assigned value.
Python Online Certification (POC)
The Python Online Certification (POC) validates professional-level Python programming skills across core language concepts, object-oriented design, data structures, system architecture, performance optimization, and software testing practices. It is designed for developers seeking to demonstrate comprehensive, real-world Python proficiency.
Exam Rules
- You can skip questions and return to them later
- Flag questions for review before submitting
- No feedback shown until you submit the entire exam
- Unanswered questions count as wrong — answer everything
- 10 pretest questions are mixed in and don't affect your score
- Timer auto-submits when time runs out
- Your progress is auto-saved every 30 seconds