Courseiva

CCNA Best Practices And Coding Conventions Questions

35 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

Prevents logs from growing indefinitely.

Why this answer

Logging levels, rotation, and external log aggregation are standard.

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

Spaces are the preferred indentation method according to PEP 8.

Why this answer

PEP 8 states that spaces are the preferred indentation method over tabs to ensure cross-platform consistency.

3
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 unnecessary clutter.

Why this answer

Avoid trailing whitespace and use spaces around assignments only if necessary.

4
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

These are the mandatory methods for the Context Manager protocol.

Why this answer

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

5
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

This is the order specified in PEP 8.

Why this answer

PEP 8 states that imports should be grouped into standard library imports, third-party imports, and local application imports.

6
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

Reduces accidental catching of unrelated errors.

Why this answer

Keep the try block small and catch specific exceptions.

7
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

This improves readability and maintainability.

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.

8
MCQeasy

When should you use absolute imports over relative imports in a large project?

A.When the file is in the same directory.
B.Always, as they are PEP 8 recommended for clarity and robustness.
C.Only if using Python 2.
D.When performance is the main priority.
AnswerB

Absolute imports are less prone to issues with package refactoring.

Why this answer

Absolute imports are recommended by PEP 8 because they are clearer and avoid ambiguity in complex package structures.

9
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

This is the recommended convention for short docstrings.

Why this answer

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

10
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

Prevents accidental commits.

Why this answer

Using .env files and ignoring them in version control is the standard.

11
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

These formats do not support object reconstruction via arbitrary code execution.

Why this answer

The 'pickle' module is fundamentally insecure; using secure formats like JSON is the only way to avoid code injection during deserialization.

12
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

The standard convention for constants.

Why this answer

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

13
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

Standard spacing.

Why this answer

Use CamelCase, omit blank lines before classes, and use docstrings.

14
MCQmedium

You need to ensure your code is readable by other Python developers. Which naming style should be used for variable names?

A.UPPER_SNAKE_CASE.
B.camelCase.
C.snake_case.
D.PascalCase.
AnswerC

The standard Python convention for variables.

Why this answer

PEP 8 prescribes snake_case (lowercase with underscores) for variable and function names.

15
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

This keeps dependencies isolated.

Why this answer

You should use virtual environments, pin your dependencies, and document your requirements.

16
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

Consistency is a key tenet of the style guide.

Why this answer

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

17
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

This is the established convention in Python.

Why this answer

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

18
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 built-in standard for Python documentation.

Why this answer

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

19
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

This is the fundamental philosophy behind Python's exception handling.

Why this answer

EAFP stands for 'Easier to Ask for Forgiveness than Permission', which encourages using try-except blocks instead of pre-checking states.

20
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 the source code repository.

Why this answer

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

21
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

This approach treats the input as data rather than an executable command string.

Why this answer

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

22
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

Exception is the correct base class for user-defined exceptions.

Why this answer

Custom exceptions should inherit from the built-in Exception class to ensure they are catchable by standard error handlers.

23
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

Silently failing makes debugging nearly impossible.

Why this answer

Swallowing exceptions and catching BaseException are both poor practices.

24
MCQeasy

Which of the following is the correct way to handle whitespace around an operator according to PEP 8?

A.x= y +z
B.x = y + z
C.x = y + z
D.x=y+z
AnswerB

This follows the PEP 8 spacing rule.

Why this answer

PEP 8 dictates surrounding operators with a single space on both sides.

25
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

This pattern allows for cleanup while respecting the user's intent to exit.

Why this answer

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

26
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

This is the standard format for Google-style docstrings.

Why this answer

Google Style requires explicit listing of types in the Args section to improve readability for static analysis tools.

27
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

This is the core advantage of a structured logging system.

Why this answer

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

28
Multi-Selecteasy

Which THREE elements are essential for a good Python docstring?

Select 3 answers
A.A detailed description of the logic.
B.A list of all possible variable types in the code.
C.A brief summary of the object's purpose.
D.A blank line following the summary line.
E.The full source code of the function.
AnswersA, C, D

Helps clarify complex behavior.

Why this answer

A summary line, a blank line, and a detailed description are standard.

29
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

This is the exact PEP 8 recommendation.

Why this answer

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

30
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

This is the PEP 8 standard for block comments.

Why this answer

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

31
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

Correct convention for classes.

Why this answer

Functions should use snake_case, and classes should use PascalCase.

32
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

Keeps info accurate.

Why this answer

Using standard formats, using tools, and regular updates are key.

33
MCQmedium

Which practice is recommended when dealing with 'bare' except clauses in Python?

A.Use bare 'except:' for performance optimization.
B.Always specify the exception type you intend to catch.
C.Use 'except Exception:' as the standard catch-all.
D.Use 'except:' but log the error immediately.
AnswerB

This prevents catching unintended system-level exceptions.

Why this answer

Bare 'except:' clauses catch SystemExit and KeyboardInterrupt, which can prevent the user from stopping a program.

34
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

Pickle is inherently insecure.

Why this answer

Avoiding dangerous functions and validating all inputs are key security practices.

35
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

This is the Pythonic way to handle resource management.

Why this answer

The 'with' statement (context manager) ensures that cleanup code is executed even if an exception occurs.

Ready to test yourself?

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