40 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.