60 questions / 10 random questions
Random questions, instant feedback, and review for missed questions.
View recommended Practical Python Basics resources →
Which type stores an ordered, mutable collection whose items can be added or removed?
Answer: list
A list is an ordered, mutable collection.
Which data structure is appropriate for looking up a name by user ID?
Answer: dict
A dict maps keys to values and supports key-based lookup.
Which type is appropriate for a collection of unique tags?
Answer: set
A set represents a collection of unique elements.
How can you get a default value when a dictionary key is missing without raising an exception?
Answer: mapping.get(key, default)
dict.get returns the supplied default when the key is absent.
How should you process many values lazily without keeping them all in memory?
Answer: A generator using yield
A generator produces values on demand and can reduce memory usage.
What problem can occur when an empty list is used directly as a function default argument?
Answer: The same list is reused across calls
Default arguments are evaluated at definition time; use None and create the list inside.
Which syntax collects variable positional arguments in a function?
Answer: *args
*args receives extra positional arguments as a tuple.
Which construct ensures a resource is released whether or not an exception occurs?
Answer: Use a context manager with a with statement
with reliably invokes a context manager's cleanup.
How should you handle only an expected exception without hiding other failures?
Answer: Catch a specific exception such as ValueError
Catching specific exceptions lets unexpected failures propagate.
How can you add domain context to an exception while preserving the original cause?
Answer: raise NewError(...) from exc
raise ... from ... explicitly chains exceptions and preserves causality.
What is a readable way to interpolate variables into a string?
Answer: An f-string
An f-string embeds expressions clearly and readably.
What happens when a non-string value is concatenated directly to a string with +?
Answer: It commonly raises TypeError
Convert explicitly with str or use an f-string.
Which operator normally compares whether two variables have equal values?
Answer: ==
== compares value equality, while is checks object identity.
What is the recommended way to test whether a value is None?
Answer: value is None
None is a singleton, so use identity comparison with is.
How should you loop over a sequence with both index and value?
Answer: enumerate(sequence)
enumerate returns an index and item together.
How do you parse a JSON string into Python objects?
Answer: json.loads(text)
json.loads decodes JSON text into dicts, lists, and other values.
How do you serialize a Python object to a JSON string?
Answer: json.dumps(value)
json.dumps encodes supported objects as JSON text.
How should you reliably open a UTF-8 text file for reading?
Answer: open(path, encoding="utf-8")
Specifying encoding avoids platform-default differences.
Which API supports portable filesystem path operations?
Answer: pathlib.Path
pathlib handles path joining, inspection, and I/O portably.
What is a safe basic approach for running an external command with arguments?
Answer: Pass an argument list to subprocess.run and keep shell=False
An argument list with shell=False reduces shell-injection risk.
What is the basic way to isolate dependencies per project?
Answer: Create a virtual environment with venv or a similar tool
A virtual environment isolates a project's interpreter environment and packages.
How should you make application dependency versions reproducible?
Answer: Version-control locked dependencies and install the same set in CI
Locked dependencies reduce unexpected version differences between environments.
Which guard runs CLI code only when a module is executed directly?
Answer: if __name__ == "__main__":
When run directly, __name__ is __main__, avoiding import-time side effects.
What is a basic way to read configuration from the environment instead of hard-coding it?
Answer: Read environment variables via os.environ or a configuration library
Environment variables separate configuration from code; combine them with validation and secret storage.
Which standard module provides levels, timestamps, and configurable destinations for application logs?
Answer: logging
logging supports levels, formatters, and handlers for operational logs.
When processing many records, one bad record should not always abort the whole batch. What is appropriate?
Answer: Catch failures per record, log them, and continue, retry, or quarantine by policy
Clear failure boundaries and retry policy support partial-failure handling.
What is a sound basic policy for network failures in an HTTP API call?
Answer: Set timeouts and retry only retryable failures with backoff
Timeouts and selective retries prevent hangs and overload.
What should you use to document function input and return types for static checking?
Answer: Type hints
Type hints are not runtime enforcement, but IDEs and type checkers can detect mismatches.
What is appropriate for a simple data container that needs generated init and repr methods?
Answer: @dataclass
A dataclass can generate init, repr, and comparisons from fields.
What is the safe way to pass user input into a database query?
Answer: Use the database driver's parameterized query
Parameter binding separates values from SQL syntax and prevents SQL injection.
What is appropriate for automatically verifying expected output from a small function?
Answer: Write a unit test asserting inputs and expected outputs
A unit test checks small behavior quickly and repeatedly.
How should you keep a unit test stable for code that calls an external API?
Answer: Inject the dependency and replace the boundary with a mock or fake
Replacing external boundaries keeps tests fast and deterministic while integration tests cover real connections.
How should a test avoid leaking temporary files?
Answer: Use a temporary-directory fixture or context manager
Let the test framework or context manager own temporary-resource cleanup.
What is the problem with using assert as the only production input validation?
Answer: Assertions can be disabled by optimization options
assert is for development invariants; use explicit exceptions for input errors.
Why should pickle be avoided for untrusted data?
Answer: Deserialization can lead to arbitrary code execution
pickle is for trusted Python objects; external input needs safer formats and schema validation.
What is the problem with passing untrusted text to eval?
Answer: It can execute arbitrary Python code
eval executes text as code; use a parser or explicit conversion instead.
What is a common choice for parallelizing CPU-bound pure Python work across cores?
Answer: multiprocessing or a process pool
Processes use separate interpreters and can distribute CPU-bound work across cores.
Which option can efficiently handle many I/O-waiting tasks?
Answer: asyncio with async-compatible libraries
asyncio can run other tasks while I/O waits, but blocking work must be avoided.
Which information is useful in logs for production incident analysis?
Answer: Record time, level, request or job ID, and key context without secrets
Correlation IDs and context improve traceability while secrets and personal data must be minimized.
Why is calling sys.exit inside a reusable library function often problematic?
Answer: The caller loses control over error handling and cleanup
Libraries should raise meaningful exceptions and let a CLI or boundary decide whether to exit.
How should you sort users by ascending age and then by ascending name for equal ages?
Answer: sorted(users, key=lambda u: (u.age, u.name))
Key tuples are compared from left to right, so they clearly express multi-field ordering. sorted does not mutate the original list.
After copying a nested dict with copy.copy(), changing an inner list also changes the original. What explains this and how can it be addressed?
Answer: A shallow copy shares nested objects; use copy.deepcopy or an explicit independent copy when required
A shallow copy creates a new outer container but shares references to nested values. Consider deepcopy cost and objects that should remain shared.
How should a dataclass field be defined so each instance receives its own empty list?
Answer: field(default_factory=list)
default_factory creates a new list for each instance and avoids sharing a mutable default.
Which choice is appropriate for monetary totals that should avoid binary floating-point artifacts such as 0.1 + 0.2?
Answer: Create decimal.Decimal values from strings and specify the required rounding rule
Decimal controls decimal precision and rounding. Construct it from strings or integer minor units rather than importing an existing binary float artifact.
What is a safe policy for storing and comparing timestamps in an API serving users in multiple time zones?
Answer: Store and compare timezone-aware UTC datetimes, converting to the user's time zone for display
UTC-aware datetimes represent instants unambiguously. Define input and output zones and ISO 8601 formats, then convert at display boundaries.
How should a UTF-8 CSV file be opened with the standard csv module to avoid extra blank lines, including on Windows?
Answer: open(path, mode, encoding='utf-8', newline='')
Use newline='' so the csv module controls newline handling and specify the encoding explicitly. Choose utf-8-sig only when an external format requires a BOM.
How should a configuration file be updated so readers do not see a partially written file if the process stops?
Answer: Write the complete content to a temporary file on the same filesystem, flush as required, then replace with os.replace
Completing a temporary file and replacing within the same filesystem helps readers observe either the old or new version. Consider fsync and backups for stronger durability requirements.
Which standard-library choice consistently handles required CLI options, type conversion, help messages, and exit codes?
Answer: argparse
argparse handles definitions, parsing, type conversion, usage and help, and invalid-input exits. Separating CLI boundaries from business logic also improves testability.
Which file is central to the standard format for build-system settings, project metadata, and core dependencies in a modern Python project?
Answer: pyproject.toml
pyproject.toml is the standard location for build backends, project metadata, dependencies, and tool configuration. Lock-file handling depends on the package manager.
Which standard-library approach is appropriate for generating a hard-to-guess password-reset token?
Answer: secrets.token_urlsafe()
The secrets module generates cryptographically strong randomness for authentication tokens. Also design sufficient entropy, expiration, and single use.
What is the appropriate basic policy for storing application passwords?
Answer: Use a trusted library implementing a salted, slow password hash such as Argon2
Password storage needs a dedicated KDF that slows brute force and a per-password salt. Plan parameter upgrades and rehashing as well.
How should several database updates be handled so they commit only if all succeed and roll back when an exception occurs?
Answer: Use the driver or ORM transaction context to commit on success and roll back on exception
Define the transaction boundary and reliably manage commit, rollback, and connection return through a context manager. Avoid holding locks across slow external calls.
What is required to retrieve all records from an HTTP API that uses page tokens?
Answer: Follow each response's next token until termination, accounting for rate limits and possible duplicates
Follow the pagination contract until no next token remains. Design timeouts, errors, rate limits, deduplication, and checkpoints as required.
How should a multi-gigabyte HTTP response be saved to a file while keeping memory use bounded?
Answer: Receive the response in streaming mode and write bounded chunks to the file
Streaming chunked writes keep memory bounded. Combine them with timeouts, status checks, size limits, temporary files, checksums, and failure cleanup.
Which conditions make functools.lru_cache appropriate for an expensive function?
Answer: The same hashable arguments produce the same acceptable result, staleness is understood, and maxsize is considered
lru_cache reuses results keyed by arguments. Consider purity, hashability, freshness, memory bounds, and when cache_clear is needed.
How can pytest test the same function with many input and expected-value pairs while reducing duplicated test code?
Answer: List the cases with @pytest.mark.parametrize
Parametrize supplies multiple cases to one test body and reports each case separately, making boundary and error cases easy to add.
How should a pytest fixture create a test database connection and guarantee rollback and close even when the test fails?
Answer: Create the resource in a fixture, yield it, and perform cleanup after yield with finally-style guarantees
A yield fixture expresses setup before yield and teardown afterward, allowing cleanup on test success or failure. Choose scope while preserving test isolation.
How can an external service client be replaceable and type-checked by required methods without requiring inheritance from a specific class?
Answer: Define the required interface with typing.Protocol
Protocol structurally accepts types that provide the required attributes and methods, keeping implementations decoupled and fakes or adapters statically checkable.
Multiple threads perform read-modify-write operations on a shared dict and updates are lost. What is a basic remedy?
Answer: Reduce shared state and protect required critical sections with threading.Lock or an appropriate synchronization primitive
Read-modify-write consists of multiple operations and can race. Choose locks, queues, thread-local state, or immutable data as appropriate, and consider lock scope and deadlocks.
How should a containerized Python worker handle SIGTERM so it can finish in-flight work and exit safely?
Answer: Have the signal handler set a shutdown flag, stop accepting new work, and let the main loop clean up and exit within the deadline
Keep the signal handler small and communicate shutdown to normal control flow. Design queue intake, in-flight work, checkpoints, connection closing, and the platform grace period.