Practical Python Basics Practice Questions & Quiz

40 questions / 10 random questions

data structures functions exceptions files and JSON virtual environments typing tests logging security and concurrency
Try a 10-question Practical Python Basics quiz

Random questions, instant feedback, and review for missed questions.

Start quiz →

View recommended Practical Python Basics resources →

Included topics (40 questions)

Q1

Which type stores an ordered, mutable collection whose items can be added or removed?

Answer: list

A list is an ordered, mutable collection.

Q2

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.

Q3

Which type is appropriate for a collection of unique tags?

Answer: set

A set represents a collection of unique elements.

Q4

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.

Q5

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.

Q6

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.

Q7

Which syntax collects variable positional arguments in a function?

Answer: *args

*args receives extra positional arguments as a tuple.

Q8

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.

Q9

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.

Q10

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.

Q11

What is a readable way to interpolate variables into a string?

Answer: An f-string

An f-string embeds expressions clearly and readably.

Q12

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.

Q13

Which operator normally compares whether two variables have equal values?

Answer: ==

== compares value equality, while is checks object identity.

Q14

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.

Q15

How should you loop over a sequence with both index and value?

Answer: enumerate(sequence)

enumerate returns an index and item together.

Q16

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.

Q17

How do you serialize a Python object to a JSON string?

Answer: json.dumps(value)

json.dumps encodes supported objects as JSON text.

Q18

How should you reliably open a UTF-8 text file for reading?

Answer: open(path, encoding="utf-8")

Specifying encoding avoids platform-default differences.

Q19

Which API supports portable filesystem path operations?

Answer: pathlib.Path

pathlib handles path joining, inspection, and I/O portably.

Q20

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.

Q21

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.

Q22

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.

Q23

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.

Q24

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.

Q25

Which standard module provides levels, timestamps, and configurable destinations for application logs?

Answer: logging

logging supports levels, formatters, and handlers for operational logs.

Q26

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.

Q27

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.

Q28

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.

Q29

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.

Q30

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.

Q31

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.

Q32

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.

Q33

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.

Q34

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.

Q35

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.

Q36

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.

Q37

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.

Q38

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.

Q39

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.

Q40

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.

certdrill.dev is an independent, unofficial learning site and is not affiliated with LPI Japan, IPA, AWS, Microsoft Azure, or any exam provider. Questions and explanations are original content.