Courseiva

CCNA Best Practices And Coding Conventions Questions

53 questions · Best Practices And Coding Conventions topic · All types, answers revealed

1
Multi-Selecthard

Which THREE features are associated with robust logging in production applications?

Select 3 answers
A.Log rotation to prevent disk space exhaustion.
B.Logging to 'stdout' exclusively.
C.Configuring log formatters for structured output.
D.Using different logging levels for different environments.
E.Including personal user data in logs.
AnswersA, C, D

Log rotation caps file growth by archiving or deleting older entries once a size or time threshold is reached, directly preventing the disk space exhaustion named in the stem. Without it, unbounded log files eventually fill the volume, halting the application — a failure mode robust production logging must actively guard against.

Why this answer

Option A is correct because log rotation (e.g., via logrotate or size/time-based rolling appenders) caps log file growth and prevents disk space exhaustion, which is a core production reliability concern. Option C is correct because structured output (e.g., JSON formatters) makes logs machine-parseable, enabling reliable aggregation, searching, and alerting in tools like the ELK stack or Splunk. Option D is correct because using different logging levels per environment (e.g., DEBUG in development, WARN or ERROR in production) controls verbosity, reduces noise and cost, and keeps production logs actionable.

Option B is not inherently a robust-logging feature: writing only to stdout can be valid in containerized setups, but 'exclusively' excludes durable file or remote sinks and is not a defining best practice. Option E is incorrect because including personal user data in logs risks privacy violations (e.g., GDPR) and security exposure, so it should be avoided or masked.

2
MCQeasy

In a team environment, which PEP 8 guideline should be applied to maintain consistent indentation when mixing spaces and tabs?

A.Use spaces exclusively for indentation.
B.Use tabs exclusively, as they are more efficient for file size.
C.Always use a combination of tabs and spaces to allow personal editor configuration.
D.Default to the indentation used by the first author of the module.
AnswerA

PEP 8 mandates spaces exclusively, never mixing tabs and spaces, because tab width varies between editors and tools. Using spaces alone guarantees identical rendering across the team's environments, satisfying the consistency constraint in the stem.

Why this answer

PEP 8 explicitly recommends using spaces exclusively for indentation, with four spaces per indentation level. This avoids the ambiguity and inconsistency that arises when tabs and spaces are mixed, which can lead to Python interpreting indentation differently across editors and causing IndentationError or TabError. Using spaces ensures that code looks the same regardless of editor tab width settings.

Exam trap

PCPP1 often tests the specific PEP 8 rule that spaces are preferred over tabs, and candidates may incorrectly think tabs are acceptable if used consistently, but PEP 8 is clear that spaces are the standard.

How to eliminate wrong answers

Option B is wrong because while tabs are more space-efficient in file size, PEP 8 prioritizes readability and consistency over file size, and tabs can be rendered differently across environments. Option C is wrong because mixing tabs and spaces is explicitly discouraged by PEP 8 and can cause Python 3 to raise a TabError. Option D is wrong because defaulting to the first author's indentation style does not guarantee consistency across the team and violates PEP 8's recommendation for spaces.

3
MCQeasy

A developer is writing a Python script that contains a class named `DataProcessor`. According to PEP 8, which naming convention should be used for the class's methods and attributes?

A.Methods and attributes should use `lowercase_with_underscores`.
B.Methods and attributes should use `CapWords` to be consistent with the class name.
C.Methods and attributes should use `camelCase` to match the class name style.
D.Methods should use `lowercase_with_underscores`, but attributes should use `UPPERCASE`.
AnswerA

PEP 8 specifies that method names and instance variables should be lowercase, with words separated by underscores to improve readability. This convention, known as snake_case, is widely used in Python code and is consistent with the naming of functions and variables. For a class like `DataProcessor`, methods such as `process_data` and attributes like `raw_data` would follow this guideline, ensuring clarity and adherence to community standards.

Why this answer

PEP 8 recommends that method names and instance variables use lowercase with underscores (snake_case). This convention distinguishes them from class names, which use CapWords. Following this guideline ensures consistency and readability across Python codebases.

The other options suggest styles that are either not recommended (camelCase, CapWords) or misapply the constant convention to attributes.

Exam trap

The trap here is assuming that methods and attributes should mirror the class name's CapWords style, when PEP 8 explicitly reserves that for classes and uses snake_case for members.

4
Multi-Selecteasy

Which TWO of these are valid PEP 8 recommendations for whitespace?

Select 2 answers
A.Use two spaces for every level of indentation.
B.Use large blocks of whitespace between functions.
C.Avoid trailing whitespace.
D.Use tabs for all indentation.
E.Use a single space after commas.
AnswersC, E

Trailing whitespace is invisible but flagged by linters and version-control diffs, so PEP 8 explicitly advises removing it. This satisfies the stem's requirement for a valid whitespace recommendation, as the guideline applies to every line of code regardless of context, making it one of the two correct choices.

Why this answer

Option C is correct because PEP 8 explicitly states that trailing whitespace should be avoided anywhere in code, since it is invisible, can cause spurious diffs, and may trigger errors in some tools. Option E is correct because PEP 8 recommends a single space after a comma in expressions and argument lists (e.g., function calls and tuples), which improves readability. Option A is wrong because PEP 8 mandates four spaces per indentation level, not two.

Option B is wrong because PEP 8 advises using blank lines sparingly—typically two blank lines around top-level functions and classes—not large blocks of whitespace. Option D is wrong because PEP 8 recommends spaces over tabs for indentation, and mixing tabs and spaces is explicitly discouraged.

5
MCQhard

You are implementing a custom context manager using a class. Which methods must be implemented to support the 'with' statement?

A.__setup__ and __teardown__.
B.__open__ and __close__.
C.__init__ and __del__.
D.__enter__ and __exit__.
AnswerD

The with statement calls __enter__ on entry, binding its return value to the target, and __exit__ on exit, passing exception details so cleanup and suppression can occur. Both methods are required for a class-based context manager to work.

Why this answer

A context manager requires `__enter__` to set up the resource and `__exit__` to handle cleanup.

6
MCQmedium

A developer is documenting a function `fetch_records` that accepts a database connection, a table name, and an optional limit. The team follows Google Style Python Docstrings. Which approach correctly documents the parameters and their types?

A.List each parameter under an `Args:` section with the parameter name, a colon, and a description that includes the expected type.
B.Use a `Parameters:` section modeled on reStructuredText field lists with `:param name:` and `:type name:` entries.
C.Describe parameters only in inline `#` comments next to each function call in the calling code.
D.Embed the parameter details directly in the first summary line so readers see them immediately.
AnswerA

Google Style Python Docstrings use an `Args:` section where each parameter is written as `name (type): description`. This format is machine-readable by tools such as Sphinx's napoleon extension and is the documented convention. Including the type in parentheses alongside the name keeps the documentation consistent and parseable for `fetch_records`.

Why this answer

Google Style Python Docstrings document parameters in an `Args:` section using the pattern `name (type): description`. This structured format is parsed by documentation tools and keeps type information alongside the parameter name. Other styles, such as Sphinx field lists or unstructured summaries, do not match the convention the team has adopted, so consistency requires the `Args:` form.

Exam trap

The trap here is conflating Sphinx field-list syntax with Google Style, even though both are valid documentation approaches in different ecosystems.

7
MCQmedium

You are preparing a Python module for PyPI. Your project layout is: project_root/ ├── setup.py ├── src/ │ └── mypackage/ │ ├── __init__.py │ └── core.py └── tests/ └── test_core.py You want to write a test that imports mypackage.core and verifies the function add(a, b). Which import statement should you use at the top of tests/test_core.py to follow best practices for a src-layout project after installing the package in editable mode?

A.from mypackage import core
B.from src.mypackage import core
C.import core
D.import src.mypackage.core as core
AnswerA

With a src layout, the package is installed (e.g., pip install -e .) before running tests, so the package is importable by its top-level name. Importing 'mypackage.core' directly reflects the installed package structure, avoids path manipulation, and ensures tests run against the installed code rather than relative files. This is the recommended practice to prevent accidental imports from the source tree.

Why this answer

In a src-layout project, the package is installed into the environment (e.g., editable install) before tests are run, so tests should import the package by its top-level name, not via the src directory. Using 'from mypackage import core' ensures the test exercises the installed code, matches how users will import it, and avoids fragile sys.path assumptions. This aligns with packaging best practices for test isolation.

Exam trap

The trap here is assuming that because the source files live under src/, the import path must include src, confusing filesystem layout with the importable package name after installation.

8
MCQhard

A developer is reviewing a pull request where a function uses a global variable to track a counter. The reviewer suggests refactoring to avoid global state. Which refactoring best follows best practices for maintainability and testability?

A.Pass the counter as an argument and return the updated value.
B.Use a default mutable argument to store the counter.
C.Use a module-level variable and declare it global inside the function.
D.Encapsulate the counter in a class and use an instance variable.
AnswerD

Encapsulating the counter in a class with an instance variable removes global state, making the code more modular and testable. Each instance maintains its own counter, and the state is explicit. This aligns with object-oriented best practices and reduces side effects, improving maintainability.

Why this answer

Encapsulating state in a class instance eliminates global mutable state, making the code more modular and testable. Each instance has its own counter, and interactions are explicit. Passing the counter as an argument is also valid but can be less convenient for complex state.

Using module-level globals or mutable defaults perpetuates the issues of shared state.

Exam trap

The trap here is thinking that using a module-level variable with global is equivalent to encapsulation, but it still introduces global mutable state and its associated problems.

9
MCQhard

You are designing a Python class that manages a database connection. The class has a method `_execute_query` that should only be used internally. According to Python best practices and PEP 8, how should you indicate that this method is for internal use only?

A.Prefix the method name with a single underscore: `_execute_query`.
B.Prefix the method name with two underscores: `__execute_query`.
C.Use the `@internal` decorator from the `typing` module.
D.Add a comment above the method: `# Internal use only`.
AnswerA

PEP 8 recommends using a single leading underscore to indicate that a method or attribute is intended for internal use. This is a convention that tells other developers that the method is not part of the public API, though it can still be accessed. It is the standard way to signal internal use in Python.

Why this answer

PEP 8 specifies that a single leading underscore should be used to indicate that an attribute or method is intended for internal use. This is a widely recognized convention in Python. Double underscores are for name mangling, comments are not a convention, and there is no standard `@internal` decorator.

Exam trap

The trap here is confusing the single underscore (internal use) with the double underscore (name mangling) or assuming that a decorator or comment is the standard way.

10
MCQmedium

When creating a new project, how should you structure your imports?

A.In the order they are used in the file.
B.Standard library imports, then third-party, then local, with blank lines between groups.
C.Alphabetically regardless of source.
D.All in a single line separated by semicolons.
AnswerB

PEP 8's import grouping convention satisfies the readability constraint by separating standard library, third-party and local imports with blank lines, so each dependency's origin is immediately clear and merge conflicts or circular-import confusion are easier to spot.

Why this answer

PEP 8 specifies that imports should be grouped in the order: standard library, related third-party, then local application/library imports, with a blank line between each group. Within each group, imports should be sorted alphabetically. This convention makes dependencies explicit and helps detect circular imports early.

Exam trap

PCPP1 often tests whether candidates know PEP 8's specific grouping order (standard, third-party, local) rather than just 'alphabetical' or 'usage order' — the grouping is the key detail.

How to eliminate wrong answers

Option A is wrong because ordering imports by usage order is not a recognized convention and makes it harder to see at a glance which dependencies are external vs. internal. Option C is wrong because alphabetical ordering across all sources ignores the semantic distinction between standard library, third-party, and local imports — PEP 8 requires grouping first, then alphabetical within groups. Option D is wrong because semicolon-separated imports on a single line violate PEP 8 (which discourages multiple statements per line) and reduce readability; each import should be on its own line.

11
Multi-Selectmedium

Which TWO practices help maintain clean code when using Python's 'try-except' blocks?

Select 2 answers
A.Keep the 'try' block as small as possible.
B.Use a single 'except:' clause for the whole project.
C.Always ignore errors in the 'except' block.
D.Catch the most specific exceptions first.
E.Put as much code as possible in the 'try' block.
AnswersA, D

Keeping the `try` block minimal confines exception handling to the exact statement that may fail, so unrelated errors are not accidentally caught and masked. This satisfies the stem's clean-code constraint by making the guarded operation explicit, narrowing the exception's scope, and preventing broad handlers from hiding genuine bugs elsewhere in the logic.

Why this answer

Option A is correct because keeping the 'try' block as small as possible limits it to only the statements that can actually raise the expected exception, which makes the source of an error obvious and prevents unrelated bugs from being accidentally caught and masked. Option D is correct because Python evaluates 'except' clauses in order, so catching the most specific exception classes first (for example 'except ValueError:' before 'except Exception:') ensures precise handling and prevents a broad handler from shadowing a more specific one. Option B is wrong because a single bare 'except:' for the whole project swallows every exception, including 'KeyboardInterrupt' and 'SystemExit', and hides real defects.

Option C is wrong because silently ignoring errors in the 'except' block discards diagnostic information and lets the program continue in an invalid state. Option E is wrong because putting as much code as possible in the 'try' block widens the scope of what can be caught, making it unclear which statement raised the exception and increasing the chance of masking unrelated errors.

12
MCQmedium

What is the recommended way to handle a function that requires a large number of arguments?

A.Just define the function with many arguments; it is perfectly fine.
B.Use a single argument dictionary.
C.Use *args and **kwargs for everything.
D.Group related parameters into a dataclass or object.
AnswerD

Grouping related parameters into a dataclass or object reduces the positional argument count, satisfying the stem's constraint of a function requiring a large number of arguments. It also improves readability and keeps the call signature stable as related values evolve together.

Why this answer

If a function has too many arguments, it is often a sign it should be broken down or that a configuration object should be used.

13
MCQeasy

According to PEP 257, what is the standard format for a single-line docstring?

A.Use a single quote for the entire block.
B.The docstring should span three lines including the summary.
C.The summary should start on the next line.
D.Use triple quotes and keep the summary on the same line, ending with a period.
AnswerD

PEP 257 specifies triple double quotes with the summary on the same line as the opening quotes, terminated by a period. This satisfies the stem's single-line format requirement, keeping the docstring concise and consistent with the convention.

Why this answer

A single-line docstring should be on the same line as the opening triple quotes, ending with a period.

14
MCQhard

A developer is writing a Python function that accepts a mutable default argument, such as `def add_item(item, items=[])`. A code reviewer flags this as a potential bug. Which statement best explains the issue and the recommended fix according to best practices?

A.The default list is copied for each call, so the only issue is performance; use a tuple for efficiency.
B.The default list is shared across all calls, so use `None` as the default and create a new list inside the function.
C.The default list is immutable, so it cannot be modified; use a tuple instead.
D.The default argument is re-evaluated on each call, so the code is safe; no change is needed.
AnswerB

In Python, default arguments are evaluated only once at function definition time. Using a mutable default like `[]` means the same list object is reused across all calls, leading to unintended persistence of data. The recommended fix is to use `None` as the default and then check `if items is None: items = []` inside the function. This ensures a fresh list is created for each call, avoiding shared state bugs.

Why this answer

Mutable default arguments are evaluated once at definition time, causing shared state across calls. The correct practice is to use `None` as a default and create a new mutable object inside the function. This avoids bugs where data unexpectedly persists.

Other options either misdiagnose the problem or propose ineffective solutions.

Exam trap

The trap here is thinking that default arguments are re-evaluated on each call, when they are actually evaluated once at function definition.

15
MCQeasy

A developer is writing a Python script and wants to ensure that lines do not exceed the recommended maximum length according to PEP 8. What is the maximum line length that PEP 8 recommends for code?

A.100 characters
B.80 characters
C.79 characters
D.120 characters
AnswerC

PEP 8 recommends limiting all lines to a maximum of 79 characters. This limit is intended to improve readability, especially when viewing code side-by-side or on smaller displays. It also allows for multiple files to be open simultaneously. While many modern projects relax this to 99 or 119 characters, the official PEP 8 guideline remains 79 for code and 72 for docstrings and comments.

Why this answer

PEP 8 recommends a maximum line length of 79 characters for code. This limit is intended to improve readability and allow for side-by-side viewing. It also accommodates smaller screens and terminals.

While some projects adopt longer limits like 99 or 119 characters, the official PEP 8 guideline is 79. Following this convention helps maintain consistency across Python codebases.

Exam trap

The trap here is rounding up to 80 characters, which is a common misconception but not what PEP 8 specifies.

16
MCQeasy

A developer is writing a Python script and wants to ensure that the code adheres to PEP 8's recommendations for blank lines. According to PEP 8, how many blank lines should surround a top-level function definition?

A.Two blank lines before and after the function definition.
B.No blank lines are required; the function can be adjacent to other code.
C.One blank line before and after the function definition.
D.Three blank lines before and after the function definition.
AnswerA

PEP 8 specifies that top-level function and class definitions should be surrounded by two blank lines. This convention improves readability by clearly separating distinct sections of code. It helps developers quickly identify where one function ends and another begins, especially in larger modules. Adhering to this rule is a common practice in well-formatted Python codebases.

Why this answer

PEP 8 recommends two blank lines before and after top-level function and class definitions. This provides clear visual separation and improves readability. One blank line is used for methods inside classes, and no blank lines would make the code cramped.

Three blank lines are excessive. The correct choice is two blank lines.

Exam trap

The trap here is confusing the rule for top-level functions with the rule for methods, which require only one blank line.

17
Multi-Selectmedium

Which TWO practices ensure secure handling of sensitive environment configurations?

Select 2 answers
A.Commit .env files to the code repository.
B.Store secrets in code comments.
C.Share the '.env' file via email.
D.Add '.env' to your '.gitignore' file.
E.Use a library like 'python-dotenv' to load configuration.
AnswersD, E

Adding `.env` to `.gitignore` prevents credentials and API keys from being committed to version control, satisfying the constraint that secrets must never enter the repository history. Since Git tracks content permanently, excluding the file at source stops accidental exposure through pushed commits, forks or public mirrors.

Why this answer

Option D is correct because adding '.env' to '.gitignore' prevents the file containing sensitive configuration values from being tracked and pushed to the Git repository, keeping secrets out of version control history. Option E is correct because using a library like 'python-dotenv' loads configuration from a local '.env' file into environment variables at runtime, so secrets stay out of source code and can be managed per-environment. Options A and C are insecure because committing '.env' files to the repository or emailing them exposes secrets to unintended parties and version history.

Option B is also wrong since storing secrets in code comments still embeds them in source code that may be shared or committed.

18
MCQhard

A script processes data from untrusted sources. Which technique best mitigates 'pickle' deserialization vulnerabilities?

A.Only unpickle from files with a specific extension.
B.Use an alternative format like JSON or XML for serialization.
C.Wrap the unpickling in a try-except block.
D.Use 'pickle.load()' with a restricted whitelist of modules.
AnswerB

JSON and XML parsers construct only primitive data types, so they cannot execute arbitrary code during deserialisation. This directly satisfies the untrusted-source constraint, where pickle's `__reduce__` method allows attackers to run commands. Switching format removes the code-execution vector entirely rather than merely restricting which classes may load.

Why this answer

The pickle module is inherently unsafe for untrusted data because unpickling executes arbitrary code via the __reduce__ method during object reconstruction. The only reliable mitigation is to avoid pickle entirely for untrusted input and use a data-only format like JSON or XML, which cannot execute code during parsing. JSON/XML parsers only construct primitive data types (dicts, lists, strings, numbers), eliminating the remote code execution vector.

Exam trap

PCPP1 often tests the misconception that defensive coding patterns like try-except or file validation can secure pickle, when the only real fix is to not use pickle on untrusted data at all.

How to eliminate wrong answers

Option A is wrong because file extensions are trivially spoofed and provide zero protection — a malicious pickle can be named anything. Option C is wrong because try-except only catches exceptions after the malicious __reduce__ payload has already executed; the damage is done before any exception is raised. Option D is wrong because pickle.load() has no built-in whitelist mechanism — there is no restricted unpickler in the standard library, and third-party solutions like restricted unpicklers are fragile and easily bypassed.

19
MCQeasy

When naming a constant in Python, which convention does PEP 8 recommend?

A.UPPER_CASE_WITH_UNDERSCORES.
B.PascalCase.
C.snake_case.
D.CamelCase.
AnswerA

PEP 8 specifies that constants be written in all-uppercase letters with words separated by underscores, satisfying the stem's request for the recommended naming convention. This distinct style visually flags module-level values that should not change, separating them from lowercase variables and functions.

Why this answer

Constants should be named using all capital letters with underscores to separate words.

20
Multi-Selecteasy

Which THREE of the following are recommended in PEP 8 for class definitions?

Select 3 answers
A.Put two blank lines between top-level classes.
B.Place imports inside the class definition.
C.Omit docstrings for private classes.
D.Use CamelCase for class names.
E.Include a docstring for the class.
AnswersA, D, E

PEP 8 mandates two blank lines before and after every top-level class definition, visually separating it from surrounding module-level code. This satisfies the stem's request for recommended class-definition formatting, distinguishing top-level classes from nested ones and methods, which use a single blank line.

Why this answer

Option A is correct because PEP 8's blank-lines rule requires two blank lines around top-level function and class definitions, so separating top-level classes with two blank lines is the recommended style. Option D is correct because PEP 8 prescribes the CapWords (CamelCase) convention for class names, e.g., class MyClass. Option E is correct because PEP 8 states that docstrings should be written for all public modules, functions, classes, and methods, so a class should include a docstring.

Option B is not recommended: imports must be placed at the top of the file, after module docstrings and before module-level code, never inside a class body. Option C is not recommended: PEP 8 calls for docstrings on all public classes, and omitting them for private classes is not a PEP 8 rule.

21
MCQhard

A developer is writing a Python script that processes sensitive data. They want to ensure that any errors are logged without exposing the sensitive data itself. Which logging practice should they follow to avoid leaking sensitive information in logs?

A.Log only the exception type and not the message or traceback.
B.Use a custom logging filter to redact sensitive fields before logging.
C.Disable logging entirely for the module that processes sensitive data.
D.Log the full exception traceback including the exception message.
AnswerB

A custom logging filter can inspect log records and redact or remove sensitive information before they are emitted. This allows developers to log useful debugging information while ensuring that sensitive data such as passwords, tokens, or personal identifiers are not written to logs, maintaining security and compliance.

Why this answer

Using a custom logging filter to redact sensitive fields is a balanced approach. It allows logging of useful information while preventing sensitive data from being written. This practice is recommended for applications handling sensitive data, as it maintains security without sacrificing debuggability.

Exam trap

The trap here is thinking that logging the full traceback is always safe; in reality, exception messages can contain sensitive data that would be exposed in logs.

22
Multi-Selectmedium

Which THREE practices are recommended when handling external libraries?

Select 3 answers
A.Install libraries globally.
B.Import all libraries at the very end of the file.
C.Use a virtual environment for every project.
D.Document dependencies in a manifest file.
E.Pin your dependencies in a requirements.txt file.
AnswersC, D, E

A virtual environment isolates each project's installed packages from the system interpreter and from other projects, preventing version conflicts between libraries that demand incompatible dependencies. Creating one per project is the recommended baseline for reproducible, dependency-safe development.

Why this answer

Option C is correct because creating a virtual environment (e.g., python -m venv .venv) for every project isolates its third-party packages from the system Python and other projects, preventing version conflicts and keeping the global interpreter clean. Option D is correct because documenting dependencies in a manifest file (such as requirements.txt, pyproject.toml, or package.json) records exactly which external libraries the project needs, enabling reproducible installs and easier auditing. Option E is correct because pinning dependencies in requirements.txt (e.g., requests==2.31.0) locks exact versions so builds are deterministic and a later upstream release cannot silently break the application.

Option A is wrong because installing libraries globally pollutes the system interpreter, risks version clashes between projects, and often requires elevated privileges. Option B is wrong because imports should be grouped at the top of the file per PEP 8, and deferring them to the end harms readability and can cause NameError at runtime.

Exam trap

The trap is treating 'install globally' or 'import at the end' as harmless style choices — the exam expects you to recognize that global installs and misplaced imports violate both PEP 8 and reproducibility principles.

23
MCQeasy

When is it acceptable to ignore PEP 8 guidelines?

A.Only when you disagree with the stylistic choice.
B.Never.
C.When you are writing a script that will only be used once.
D.When necessary to maintain consistency with existing code or for legacy reasons.
AnswerD

PEP 8 explicitly permits local consistency to override its rules when working within an existing codebase, so matching surrounding legacy conventions takes precedence over strict compliance. This satisfies the stem's constraint by acknowledging that readability and uniformity within a project outweigh blanket adherence to the style guide.

Why this answer

PEP 8 itself states that project consistency and backward compatibility may warrant exceptions to the rules.

24
MCQmedium

When designing a public API, how should you signal that a method is for internal use only?

A.By prepending a single underscore.
B.By raising a warning if called externally.
C.By adding a comment like '# INTERNAL'.
D.By using all caps.
E.By suffixing with an underscore.
AnswerA

A single leading underscore marks the method as non-public by convention, satisfying the need to signal internal-only use without enforcing access control. Python's documentation treats such names as internal, and `from module import *` excludes them, so external callers receive a clear warning while the API remains unbroken.

Why this answer

Prefixing a name with a single underscore is the conventional way to indicate internal use.

25
MCQmedium

When writing a library, what is the best practice for documenting the usage of a function?

A.Include the documentation as comments above the function definition.
B.Use docstrings to provide a clear summary and usage details.
C.Provide usage examples in the 'README.md' file only.
D.Wait for users to ask for documentation.
AnswerB

Docstrings are the conventional, introspectable place for usage documentation in Python. Because they attach to the function object itself, tools like help() and IDEs surface the summary and usage details directly, satisfying the library's need for discoverable, self-contained documentation.

Why this answer

Docstrings provide the most standard and accessible form of documentation that can be integrated with tools like Sphinx.

26
MCQhard

A developer is writing a Python function that accepts a callback. They want to ensure the function's docstring follows PEP 257 conventions for multi-line docstrings. Which of the following is the correct format for a multi-line docstring?

A.The summary line is indented, followed by a blank line, then the detailed description, and the closing quotes are indented to match the summary line's indentation.
B.The opening triple quotes are followed by a blank line, then the summary line, then the detailed description, with closing quotes on the same line as the last sentence.
C.The entire docstring is on a single line, regardless of length, to avoid multi-line formatting issues.
D.The summary line starts on the same line as the opening triple quotes, followed by a blank line, then a more detailed description, and the closing triple quotes are on a line by themselves.
AnswerD

PEP 257 specifies that multi-line docstrings should begin with a summary line on the same line as the opening quotes, followed by a blank line, then a more detailed description. The closing quotes should be on a separate line. This structure allows tools like help() to display the summary first and ensures consistent formatting across the codebase.

Why this answer

PEP 257 defines the canonical format for multi-line docstrings: a summary line on the same line as the opening triple quotes, a blank line, a detailed description, and closing quotes on their own line. This structure is widely supported by documentation generators and helps maintain consistency. The summary line should be a concise one-line description, while the body provides additional details.

Exam trap

The trap here is misplacing the summary line or the closing quotes, which can break automated docstring parsers.

27
MCQhard

In the context of writing robust error handling, what is the 'EAFP' principle?

A.Ensure All Functions Pass.
B.Exit All Files Properly.
C.Easier to Ask for Forgiveness than Permission.
D.Evaluate All Faults Promptly.
AnswerC

EAFP means attempting the operation and catching exceptions rather than pre-checking conditions. Python's try/except embodies this, avoiding race conditions between a check and the action, and suiting duck-typed code where pre-validation is unreliable or verbose.

Why this answer

EAFP stands for 'Easier to Ask for Forgiveness than Permission,' a Python coding philosophy that encourages attempting an operation and catching exceptions if it fails, rather than checking preconditions beforehand. In practice, this means using try/except blocks around code that might raise errors (e.g., accessing a dictionary key or opening a file) instead of using if statements to verify conditions first. This approach aligns with Python's dynamic nature and often results in cleaner, faster code because it avoids redundant checks and race conditions.

Exam trap

PCPP1 often tests... the confusion between EAFP and LBYL, where candidates might pick a distractor that sounds like a proactive error-checking strategy (like Option D) instead of recognizing the specific Python idiom of using try/except over if-checks.

How to eliminate wrong answers

Option A is wrong because 'Ensure All Functions Pass' is a meaningless phrase that does not correspond to any known programming principle; it confuses the acronym with a generic quality goal. Option B is wrong because 'Exit All Files Properly' describes a resource management practice (like using context managers), not the EAFP principle, and misinterprets the acronym. Option D is wrong because 'Evaluate All Faults Promptly' suggests a proactive error-checking strategy, which is closer to the opposite philosophy (LBYL – Look Before You Leap) and does not match the EAFP acronym or its meaning.

28
MCQeasy

A developer is adding a new public function `calculate_discount` to an existing Python module. The module currently uses four spaces per indentation level, and the function spans several nested `if` blocks. Which PEP 8 indentation practice should the developer follow?

A.Use one tab per indentation level because tabs render consistently in every IDE.
B.Use four spaces per indentation level throughout the function and avoid mixing tabs with spaces.
C.Use two spaces per indentation level to keep deeply nested blocks from drifting too far right.
D.Use a mix of tabs for the outer blocks and spaces for the inner blocks to visually separate nesting levels.
AnswerB

PEP 8 explicitly recommends four spaces per indentation level and states that spaces are the preferred indentation method. Using four spaces consistently in the new function keeps the module uniform and avoids the ambiguity that arises when tabs and spaces are mixed, which can cause `TabError` or silent misalignment across different editors.

Why this answer

PEP 8 recommends four spaces per indentation level and spaces over tabs. Because the existing module already uses four spaces, the new function should match that convention to keep the file internally consistent and avoid tab/space mixing, which Python 3 can reject with `TabError`. Consistency within a module matters more than personal preference.

Exam trap

The trap here is assuming that tab indentation is acceptable simply because it renders consistently in a particular editor.

29
MCQhard

You are refactoring code that performs sensitive operations. Which of the following is the most secure practice for handling secret keys?

A.Use environment variables to store sensitive configuration.
B.Encrypt the secrets and store them as constants in a module.
C.Store secrets in a private class attribute.
D.Hardcode them as strings inside a 'config.py' file and ignore it in Git.
AnswerA

Environment variables keep secrets out of source code and version control, so credentials are injected at runtime rather than committed. This satisfies the constraint of handling sensitive keys without embedding them in files that could be leaked.

Why this answer

Hardcoding secrets is a major security vulnerability; using environment variables is the industry standard.

30
MCQhard

When implementing secure coding practices in a web-facing Python application, how should you handle raw user input to prevent command injection?

A.Pass the entire input string to os.system().
B.Concatenate the input string into a shell command for execution.
C.Pass input arguments as a list to subprocess.run(args, shell=False).
D.Sanitize input using a custom regex to remove special characters.
AnswerC

Passing arguments as a list with shell=False bypasses the shell entirely, so metacharacters like `;`, `|` and `&&` are treated as literal argument data rather than shell syntax. This satisfies the stem's command injection constraint by removing shell interpretation, the mechanism through which injected commands would otherwise execute.

Why this answer

Using the 'subprocess' module with 'shell=False' (the default) prevents the shell from interpreting user-provided strings as commands.

31
MCQmedium

A code reviewer notices that a Python module defines a class named `dataProcessor` and a function named `processData`. The team follows PEP 8. Which naming convention should be applied to the class name?

A.Rename the class to `data_processor` using snake_case.
B.Keep the class name as `dataProcessor` (camelCase).
C.Rename the class to `DATA_PROCESSOR` using all uppercase with underscores.
D.Rename the class to `DataProcessor` using CapWords (PascalCase).
AnswerD

PEP 8 states that class names should normally use the CapWords convention (also known as PascalCase), where each word starts with an uppercase letter and there are no underscores. Renaming `dataProcessor` to `DataProcessor` aligns with this widely accepted standard, improving readability and consistency across Python codebases. This is the correct convention for classes.

Why this answer

PEP 8 recommends CapWords (PascalCase) for class names, so `DataProcessor` is the correct choice. Snake_case, camelCase, and all-uppercase with underscores are used for other purposes: functions/variables, non-standard style, and constants respectively. Adhering to this convention ensures consistency and readability in Python projects.

Exam trap

The trap here is assuming that any consistent naming style is acceptable, but PEP 8 specifically mandates CapWords for classes.

32
MCQmedium

You are writing a library that expects a custom exception. Which practice aligns best with Python's exception handling hierarchy?

A.Use a mixin class without inheritance.
B.Inherit from StandardError.
C.Inherit from BaseException.
D.Inherit from Exception.
AnswerD

Inheriting from Exception satisfies the requirement that a custom exception integrates with Python's standard hierarchy, so `except Exception` handlers still catch it. Unlike BaseException subclasses, which bypass ordinary handlers, this keeps the library's errors catchable by callers while avoiding the overly broad BaseException branch.

Why this answer

Custom application exceptions should inherit from Exception, which is the base class for all non-system-exiting exceptions and is intended for user-defined errors. Inheriting from Exception ensures the exception is caught by normal 'except Exception' handlers and does not interfere with interpreter-level control flow. This is the standard practice recommended by PEP 8 and the Python documentation.

Exam trap

PCPP1 often tests the Python 2 vs Python 3 exception hierarchy — candidates who remember 'StandardError' from Python 2 pick it, not realizing it was removed in Python 3.

How to eliminate wrong answers

Option A is wrong because a mixin without inheritance does not create an exception class at all — it would not be raisable or catchable as an exception. Option B is wrong because StandardError was a Python 2 class that was removed in Python 3; referencing it causes a NameError. Option C is wrong because BaseException is reserved for system-exiting exceptions like SystemExit, KeyboardInterrupt, and GeneratorExit — inheriting from it means normal 'except Exception' blocks will not catch your custom exception, which is almost never desired.

33
Multi-Selecthard

Which TWO of these identify a potential 'code smell' in Python exception handling?

Select 2 answers
A.Using 'finally' for cleanup.
B.Swallowing exceptions with an empty 'except' block.
C.Catching specific exceptions.
D.Catching 'BaseException' instead of 'Exception'.
E.Raising custom exceptions.
AnswersB, D

An empty `except:` block catches every exception, including `KeyboardInterrupt` and `SystemExit`, then discards it silently. This hides failures, so bugs surface later far from their origin. It satisfies the stem's code-smell criterion: the handler neither logs, re-raises, nor narrows the exception type, leaving no diagnostic trace.

Why this answer

Option B is a code smell because an empty 'except:' block silently swallows every exception, hiding failures and making debugging nearly impossible; at minimum the handler should log or re-raise. Option D is a code smell because 'BaseException' includes 'SystemExit', 'KeyboardInterrupt', and 'GeneratorExit', so catching it can prevent normal interpreter shutdown and interrupt handling; application code should normally catch 'Exception' or more specific subclasses. Option A is not a smell: 'finally' is the correct construct for guaranteed cleanup such as closing files or releasing locks.

Option C is not a smell: catching specific exception types is the recommended practice for precise, safe error handling. Option E is not a smell: defining and raising custom exceptions improves clarity and lets callers handle domain-specific errors.

34
MCQhard

You are writing a Python module that includes a function to compute the factorial of a number. You want to document the function using a docstring that is compatible with the Google Python Style Guide. Which of the following docstrings correctly follows the Google style for documenting parameters and return values, including types?

A."""Compute the factorial of a number. Arguments: n: int, the number to compute the factorial for. Returns: int, the factorial of n. Raises: ValueError, if n is negative. """
B."""Compute the factorial of a number. :param n: The number to compute the factorial for. :type n: int :return: The factorial of n. :rtype: int :raises ValueError: If n is negative. """
C."""Compute the factorial of a number. @param n: The number to compute the factorial for. @return: The factorial of n. @raises ValueError: If n is negative. """
D."""Compute the factorial of a number. Args: n (int): The number to compute the factorial for. Returns: int: The factorial of n. Raises: ValueError: If n is negative. """
AnswerD

This docstring follows the Google style: a one-line summary, then sections for Args, Returns, and Raises. Each parameter is documented with its type in parentheses, and the return type is specified. The Raises section documents the exception. This format is easily parsed by tools like Sphinx with napoleon and is very readable, making it the most compliant with the Google Python Style Guide.

Why this answer

The Google Python Style Guide specifies that docstrings should have sections like Args, Returns, and Raises, with parameter types in parentheses after the parameter name. The correct docstring follows this exactly, making it both human-readable and machine-parsable by tools like Sphinx with the napoleon extension. This consistency is key for maintainable documentation.

Exam trap

The trap here is confusing the Google style with other popular docstring formats like reST or Epydoc, or slightly altering the section headers and type placement, which breaks compatibility with tools expecting the exact Google format.

35
MCQmedium

A development team is refactoring a legacy Python module. They want to enforce a consistent import ordering convention across the codebase. According to PEP 8, which grouping and ordering of imports is considered best practice?

A.Standard library imports first, then third-party imports, then local application imports, with each group separated by a blank line.
B.Third-party imports first, followed by standard library imports, to highlight external dependencies.
C.Local application imports first, then standard library and third-party imports mixed together alphabetically.
D.All imports in a single block, sorted alphabetically by module name, regardless of origin.
AnswerA

PEP 8 specifies that imports should be grouped in the order: standard library, related third-party, and local application imports. Each group should be separated by a blank line. This ordering improves readability by clearly distinguishing built-in modules from external dependencies and project-specific modules, making it easier to manage and review dependencies.

Why this answer

PEP 8 recommends grouping imports into three distinct categories: standard library, third-party, and local application. Each group should be separated by a blank line. This ordering is not just stylistic; it helps developers quickly understand a module's dependencies and ensures that imports are logically organized.

Alphabetical sorting within each group is also encouraged but not mandatory.

Exam trap

The trap here is assuming that alphabetical order across all imports is sufficient, overlooking the required grouping by origin.

36
MCQeasy

A team is reviewing code and notices that a function uses a mutable default argument: def append_to(element, target=[]):. Which change best adheres to Python best practices and avoids unexpected behavior?

A.def append_to(element, target=[]): target.append(element); return target
B.def append_to(element, target=None): if target is None: target = []
C.def append_to(element, target=list()): target.append(element); return target
D.def append_to(element, target=()): target.append(element); return target
AnswerB

Using None as the default and creating a new list inside the function prevents the mutable default from being shared across calls. This is the recommended pattern in Python to avoid the well-known pitfall of mutable default arguments, ensuring each call gets a fresh list when no target is provided.

Why this answer

Mutable default arguments are evaluated once at function definition, so using a list as a default causes state to persist across calls. The best practice is to use None as the default and create a new list inside the function. This ensures each call without an explicit target gets a fresh list, preventing unintended side effects.

Exam trap

The trap here is thinking that replacing [] with list() or () avoids the mutable default problem, but only using None as a sentinel and creating the list inside the function truly fixes it.

37
MCQhard

How should one handle the 'KeyboardInterrupt' exception if it must be caught for cleanup purposes?

A.Catch it, clean up resources, and then use 'raise'.
B.Prevent it by setting a signal handler for SIGINT.
C.Use a bare 'except:' clause.
D.Catch it and ignore it to keep the app running.
AnswerA

KeyboardInterrupt signals user-requested termination, so swallowing it would leave the interpreter in an inconsistent state. Catching it solely to release resources, then re-raising with bare raise, preserves the original traceback and lets the interrupt propagate as intended.

Why this answer

You should catch it, perform the cleanup, and then re-raise it so the application still shuts down gracefully.

38
MCQmedium

You are developing a Python application that uses a third-party library. You need to ensure that your code handles exceptions raised by that library in a way that is both robust and follows best practices. The library raises a custom exception named LibraryError, which is a subclass of Exception. Your function calls a method that may raise LibraryError. Which of the following is the best approach to handle this exception?

A.try: result = library.method() except LibraryError: print("An error occurred")
B.try: result = library.method() except Exception: pass
C.try: result = library.method() except LibraryError as e: logger.error("Library method failed: %s", e) raise
D.try: result = library.method() except BaseException as e: logger.error("Error: %s", e)
AnswerC

This approach catches the specific exception, logs it with a meaningful message, and re-raises it to allow the caller to handle it appropriately. It follows best practices by not swallowing the exception, preserving the traceback, and providing context. It also avoids catching unrelated exceptions, making the error handling precise and maintainable.

Why this answer

The best practice is to catch the specific exception, log it with context, and re-raise it to allow higher-level handlers to decide how to proceed. This preserves the traceback and ensures that the error is not silently ignored. Catching only LibraryError avoids masking unrelated issues, and using a logger instead of print provides proper production-grade logging.

Exam trap

The trap here is thinking that catching a broad exception like Exception or BaseException is safer, when in fact it can hide critical errors and make debugging harder.

39
MCQhard

When documenting a complex function, which approach is most compliant with Google Style Python Docstrings regarding parameter types?

A.Use the 'Args:' section followed by the parameter name, type, and description.
B.Embed the types directly in the function name.
C.Include type hints in the docstring but omit them from the function signature.
D.Avoid documenting types to prevent redundancy with type hints.
AnswerA

Google Style mandates an `Args:` section where each parameter appears as `name (type): description`, satisfying the stem's requirement to document parameter types explicitly. This structured format lets tools such as Sphinx napoleon parse types reliably, unlike free-form prose or reStructuredText `:param:` fields, which Google Style does not use.

Why this answer

Google Style Python Docstrings require an 'Args:' section where each parameter is listed with its name, type, and description in the format 'name (type): description'. This makes the function's interface self-documenting and consistent with tools like Sphinx Napoleon that parse Google-style docstrings.

Exam trap

The trap is assuming type hints make docstring types redundant — candidates may pick option D, not realizing Google Style explicitly requires types in the Args section for documentation completeness and tooling compatibility.

How to eliminate wrong answers

Option B is wrong because embedding types in the function name is not a documentation practice at all — it would produce unreadable, non-PEP 8 compliant identifiers. Option C is wrong because Google Style encourages documenting types in the docstring while still using type hints in the signature — omitting them from the signature defeats the purpose of static analysis. Option D is wrong because Google Style explicitly includes types in the Args section; type hints and docstring types serve different audiences (static analyzers vs. human readers and documentation generators).

40
Multi-Selectmedium

A developer is writing a Python module and wants to follow best practices for documenting functions. Which TWO of the following are recommended by PEP 257 for docstrings? (Choose two.)

Select 2 answers
A.The docstring should be enclosed in triple double quotes (""").
B.The docstring should be a single line that ends with a period.
C.The docstring should be separated from the function definition by a blank line.
D.The docstring should describe the function's purpose and its parameters.
E.The docstring should be written in all uppercase letters.
AnswersA, D

PEP 257 recommends using triple double quotes for docstrings. This is the standard convention, and it allows multi-line docstrings. Using triple single quotes is also valid, but triple double quotes are preferred for consistency and to avoid conflicts with apostrophes in the text.

Why this answer

PEP 257 recommends using triple double quotes for docstrings and that they should describe the function's purpose and parameters. It also advises that a one-line docstring should end with a period, but does not require all docstrings to be single-line. No blank line should precede the docstring, and there is no rule about uppercase.

Exam trap

The trap here is assuming that all docstrings must be single-line or that a blank line before the docstring is acceptable, when PEP 257 specifies no blank line before and allows multi-line docstrings.

41
MCQmedium

What is the primary benefit of using 'logging' over 'print' statements for application diagnostics?

A.It is faster for small scripts.
B.It prevents the application from crashing on errors.
C.It allows setting severity levels and routing logs to different handlers.
D.It automatically cleans up log files.
AnswerC

The logging module assigns severity levels and dispatches records to configurable handlers such as files, streams or syslog, unlike print's single hardcoded output. This routing and filtering capability is the diagnostic advantage the stem asks for.

Why this answer

The 'logging' module provides granular control over levels, destinations, and output formatting without changing the source code.

42
MCQeasy

According to PEP 8, what is the maximum recommended length for a line of code?

A.79 characters.
B.80 characters.
C.No limit.
D.120 characters.
AnswerA

PEP 8 sets the maximum line length at 79 characters for code, a limit historically tied to side-by-side diff viewing and terminal widths. This is the specific figure the style guide recommends, satisfying the question's constraint.

Why this answer

PEP 8 suggests limiting lines to 79 characters to allow multiple files to be opened side-by-side.

43
MCQmedium

A developer is writing a function that computes the average of a list of numbers. The function should not modify the input list. Which annotation best communicates this intent and aligns with PEP 484 best practices?

A.def average(numbers: List[float]) -> float:
B.def average(numbers: Tuple[float, ...]) -> float:
C.def average(numbers: list) -> float:
D.def average(numbers: Sequence[float]) -> float:
AnswerD

Sequence[float] from typing indicates an ordered, read-only collection of floats. It communicates that the function will not mutate the input, and it accepts any sequence (list, tuple, etc.), aligning with PEP 484 and best practices for flexible, safe APIs.

Why this answer

Using Sequence[float] from the typing module communicates that the function accepts any read-only sequence of floats, preserving flexibility while indicating no mutation. This follows PEP 484 guidance to prefer abstract types for parameters. List and Tuple are more specific and imply mutability or a concrete type, which is unnecessarily limiting.

Exam trap

The trap here is assuming that a more specific type like List[float] is always better, when in fact abstract types like Sequence better express intent and improve API flexibility.

44
MCQeasy

A developer is writing a module-level variable that holds the maximum number of retries for a network client and will never change during runtime. Which naming convention does PEP 8 recommend for this constant?

A.Use CapWords, such as `MaxRetries`, to indicate that the value is a named entity.
B.Use all uppercase letters with underscores between words, such as `MAX_RETRIES`.
C.Prefix the name with a single underscore, such as `_MAX_RETRIES`, to mark it as a constant.
D.Use lowercase letters with underscores, such as `max_retries`, because Python does not enforce constantness.
AnswerB

PEP 8 recommends all uppercase letters with underscores for constants, so `MAX_RETRIES` is the correct form. This convention makes it immediately clear to readers that the value is intended to remain constant. It also distinguishes constants from regular variables, which use lowercase with underscores, improving readability across the module.

Why this answer

PEP 8 names constants using all uppercase letters with underscores separating words, so `MAX_RETRIES` is the recommended form. Python does not enforce immutability, but the naming convention communicates intent to readers and distinguishes constants from ordinary variables and classes. Other capitalizations belong to different categories of names.

Exam trap

The trap here is thinking that because Python does not enforce constantness, the all-caps convention is optional rather than a strong readability signal.

45
MCQeasy

Which comment style is preferred for block comments in Python?

A.Using a string literal (triple quotes) at the top level.
B.Using block comments inside a single line.
C.Each line starting with a single '#' and a space.
D.Using a single '#' at the end of every line.
AnswerC

Each line beginning with a single '#' and a space keeps every line independently commented, so no delimiter can be broken by nesting or formatting. This satisfies Python's style guidance (PEP 8) for block comments, unlike triple-quoted strings, which are string literals rather than true comments and can interfere with docstring conventions.

Why this answer

Block comments should consist of paragraphs of text, each starting with a # and a single space.

46
Multi-Selecteasy

Which TWO of the following are valid conventions for naming in Python according to PEP 8?

Select 2 answers
A.Constants: camelCase
B.Classes: PascalCase
C.Modules: PascalCase
D.Functions: camelCase
E.Variables: snake_case
AnswersB, E

PEP 8 prescribes PascalCase (CapWords) for class names, satisfying the stem's requirement for a valid naming convention. Each word is capitalised without underscores, as in `class HttpClient:`. This distinguishes classes from functions and variables, which use snake_case, and constants, which use UPPER_CASE.

Why this answer

Option B is correct because PEP 8 specifies that class names should use the CapWords (PascalCase) convention, e.g., class MyClass. Option E is correct because PEP 8 states that variable names should be lowercase with words separated by underscores (snake_case), e.g., my_variable. The unmarked options are incorrect: constants should be UPPER_CASE_WITH_UNDERSCORES, not camelCase (A); modules should be short, all-lowercase names, preferably with underscores, not PascalCase (C); and functions should be lowercase with underscores (snake_case), not camelCase (D).

Exam trap

PCPP1 often tests PEP 8 naming conventions, and candidates confuse camelCase (common in Java/JavaScript) with Python's snake_case for functions and variables, or mistakenly use PascalCase for modules.

47
Multi-Selectmedium

Which THREE practices improve documentation maintenance?

Select 3 answers
A.Updating documentation as part of the code review process.
B.Writing docs only at the end of the project.
C.Following a consistent docstring format (e.g., Google).
D.Keeping documentation in a separate repository.
E.Using automatic documentation generation tools like Sphinx.
AnswersA, C, E

Reviewing documentation alongside code changes keeps it synchronised with behaviour, since reviewers already inspect the diff. This satisfies the maintenance constraint by making documentation updates a gate in the existing workflow rather than a separate, easily deferred task.

Why this answer

Option A is correct because integrating documentation updates into the code review process makes doc changes a required, verifiable part of every pull request, so docs stay synchronized with code changes instead of drifting out of date. Option C is correct because following a consistent docstring format such as Google style enforces a uniform structure for parameters, returns, and raises sections, which makes documentation easier to read, review, and parse by tooling. Option E is correct because automatic documentation generation tools like Sphinx build docs directly from source docstrings, so regenerating after each change keeps published documentation current with minimal manual effort.

Option B is not correct because writing docs only at the end of a project causes them to lag behind implementation and often results in incomplete or stale content. Option D is not correct because keeping documentation in a separate repository decouples it from the code, making it harder to update in the same commit or review cycle and increasing the risk of version mismatch.

48
MCQmedium

A developer is writing a Python module and wants to follow PEP 8's recommendations for imports. The module currently has the following imports: `import os`, `import sys`, `import requests`, `from collections import defaultdict`. According to PEP 8, how should these imports be grouped and ordered?

A.Standard library imports first, then third-party imports, each group separated by a blank line.
B.All imports should be sorted alphabetically regardless of origin.
C.Imports should be placed on separate lines, and no blank lines are needed between groups.
D.Third-party imports first, then standard library imports, to highlight external dependencies.
AnswerA

PEP 8 recommends grouping imports in the following order: standard library imports, related third-party imports, and local application/library specific imports. Each group should be separated by a blank line. In this case, `os`, `sys`, and `collections` are standard library, while `requests` is third-party. So the correct grouping is standard library imports first, then third-party, with a blank line between groups.

Why this answer

PEP 8 specifies that imports should be grouped in the order: standard library, third-party, and local application/library specific. Each group should be separated by a blank line. In the given scenario, `os`, `sys`, and `collections` are standard library, while `requests` is third-party.

Therefore, standard library imports should come first, followed by a blank line, then third-party imports.

Exam trap

The trap here is thinking that imports should be sorted purely alphabetically, ignoring the grouping by origin that PEP 8 recommends.

49
Multi-Selecthard

Which TWO of the following are secure coding practices in Python?

Select 2 answers
A.Use 'subprocess' with 'shell=True'.
B.Always use 'eval()' for dynamic execution.
C.Avoid using 'pickle' for untrusted data.
D.Validate and sanitize all user input.
E.Use hardcoded credentials for database connections.
AnswersC, D

Unpickling executes arbitrary code via the __reduce__ mechanism, so a crafted payload from an untrusted source achieves remote code execution. Avoiding pickle for untrusted data removes that deserialisation attack surface, matching the secure coding requirement.

Why this answer

Option C is correct because Python's 'pickle' module is inherently unsafe for untrusted data: unpickling executes arbitrary code via the __reduce__ method, so deserializing attacker-controlled bytes can lead to remote code execution; safe alternatives include 'json' or other non-executable formats. Option D is correct because validating and sanitizing all user input (e.g., using allowlists, type checks, and parameterized queries) prevents injection flaws such as SQL injection, command injection, and XSS, forming a core secure coding practice. Option A is wrong because 'subprocess' with 'shell=True' passes the command through the shell, enabling shell metacharacter injection; the safe practice is 'shell=False' with an argument list.

Option B is wrong because 'eval()' executes arbitrary Python expressions and is a classic code-injection vector; dynamic execution should use safer mechanisms like 'ast.literal_eval' for literals. Option E is wrong because hardcoded credentials in source code expose secrets and violate secure secret-management practices such as using environment variables or a secrets manager.

50
Multi-Selectmedium

A Python developer is writing a function that reads a configuration file and returns a dictionary. They want to follow PEP 8 and best practices for function design and documentation. Which two of the following should they do? (Choose two.)

Select 2 answers
A.Place the function at the top of the file, before any imports, to make it easily accessible.
B.Include a docstring that describes the function's purpose, parameters, and return value.
C.Raise a generic `Exception` if the file cannot be read, to keep error handling simple.
D.Use a descriptive function name in lowercase with underscores, such as `read_config_file`.
E.Use a single-letter parameter name like `f` for the file path to keep the signature short.
AnswersB, D

PEP 257 recommends that all public functions include a docstring. A good docstring explains what the function does, its parameters, and its return value. This practice is essential for documentation generation tools and for other developers to understand the function's behavior without reading the implementation. It aligns with best practices for writing clear, maintainable code and is expected in professional Python projects.

Why this answer

Following PEP 8 and best practices, function names should be descriptive and use lowercase with underscores, and public functions should have docstrings that explain their purpose, parameters, and return values. These practices enhance code readability and maintainability. The other options either use unclear parameter names, raise overly broad exceptions, or misplace the function relative to imports, all of which violate established conventions.

Exam trap

The trap here is focusing on brevity (short parameter names, simple error handling) at the expense of clarity and specificity, which PEP 8 explicitly discourages.

51
MCQmedium

A team is reviewing a module where a helper function `_normalize_path` is prefixed with a single underscore. A new developer asks which statement best describes the intent of that naming choice according to common Python conventions.

A.The single underscore marks the function as deprecated and scheduled for removal in a future release.
B.The single underscore signals that the function is intended for internal use and is not part of the module's public API.
C.The single underscore makes the function inaccessible from outside the module at runtime.
D.The single underscore indicates that the function is a special method recognized by the Python interpreter.
AnswerB

A leading single underscore is a widely recognized convention indicating that a name is meant for internal use. It does not enforce privacy at runtime, but it tells other developers that the function is an implementation detail and may change without notice. This matches the intent of `_normalize_path` as a helper rather than a public entry point.

Why this answer

A leading single underscore is a convention that marks a name as internal, signaling that it is not part of the public API and may change without notice. It provides no runtime enforcement, so callers can still use it, but doing so is discouraged. This convention helps communicate intent in `_normalize_path` without altering behavior.

Exam trap

The trap here is believing that a single leading underscore enforces privacy at runtime rather than serving purely as a naming convention.

52
MCQmedium

You are debugging a legacy application and need to ensure that resources like file handles are always closed. Which construct is preferred?

A.Wrap the file operation in a try-except block.
B.Manually call file.close() in a finally block.
C.Use a context manager with the 'with' statement.
D.Rely on the garbage collector to close the handle.
AnswerC

A context manager using 'with' guarantees __exit__ runs on block exit, including on exceptions, so file handles close deterministically. This satisfies the legacy-code constraint of always releasing resources, unlike relying on garbage collection or manual close calls that can be skipped.

Why this answer

The 'with' statement invokes a context manager, which guarantees that the __exit__ method runs and closes the file handle even if an exception occurs inside the block. This is the idiomatic, preferred Python construct for deterministic resource cleanup. It is cleaner and safer than manual try/finally code.

Exam trap

PCPP1 often tests the misconception that try/finally or garbage collection is equivalent to 'with'; only the context manager guarantees deterministic, exception-safe cleanup.

How to eliminate wrong answers

Option A is wrong because a try-except block alone does not guarantee the file is closed — it only handles exceptions, and the handle may leak if no close is called. Option B is wrong because while a finally block does close the file, it is more verbose and error-prone than the 'with' statement, and it is not the preferred construct. Option D is wrong because relying on the garbage collector is non-deterministic and may delay or never close the handle, especially in CPython where reference counting usually closes it but other implementations may not.

53
MCQeasy

A Python developer is reviewing code and notices that a function has a default argument value set to an empty list: `def append_to(element, target=[]):`. According to best practices, what is the recommended way to handle mutable default arguments?

A.Keep the empty list as the default; Python handles it safely.
B.Use a tuple instead of a list as the default value.
C.Use `None` as the default and create a new list inside the function if needed.
D.Define the default argument inside the function body instead.
AnswerC

Using None as the default avoids the mutable default argument pitfall. Inside the function, you can check if the argument is None and assign a new list, ensuring each call gets a fresh list. This prevents unexpected shared state across calls.

Why this answer

Mutable default arguments are evaluated once at function definition, leading to shared state. The recommended practice is to use None as the default and create a new mutable object inside the function when needed. This ensures each call gets a fresh object unless one is explicitly passed.

Exam trap

The trap here is thinking that Python creates a new default list for each call; in reality, the default is evaluated once and shared across all calls that omit the argument.

Ready to test yourself?

Try a timed practice session using only Best Practices And Coding Conventions questions.