Self-assessment quiz

Presentation & objectives

The following quizzes are here to help you check that you understood the articles you had to study. At the end of a quiz, you will be given explanations on your answers. If some of them are wrong, you will have the possibility to click on the question you failed to try again.

These quizzes are provided for self-assessment and will not be graded or stored.

Don’t hesitate to reach out on the Discord server for any precision/explanation!

Quizzes

Exceptions and assertions

# What is an exception in programming? - [x] An event that disrupts the normal flow of a program > ✅ Exceptions are events that occur during the execution of a program and disrupt its normal flow. - [ ] An error that always terminates the program > ❌ Exceptions do not necessarily terminate a program; they can be caught and handled. - [x] An error that can be caught and handled by the program > ✅ Programs can catch and handle exceptions to prevent crashes and maintain smooth execution. - [ ] A type of loop in programming > ❌ Exceptions are not loops; they are mechanisms for handling errors during execution. - [x] An event raised when invalid data or a missing file is encountered > ✅ Exceptions are often raised when invalid data is provided or a required file is missing. # What is the purpose of the `try-except` block? - [x] To catch exceptions that may occur in the try block > ✅ The `try-except` block is used to catch and handle exceptions, preventing the program from crashing. - [ ] To loop through a block of code repeatedly > ❌ The `try-except` block is not a loop; it is for error handling. - [x] To handle specific types of exceptions > ✅ The `except` clause can specify the type of exception to be handled. - [ ] To terminate the program when an error occurs > ❌ The `try-except` block is designed to prevent the program from terminating by handling exceptions. - [x] To provide a clean way to manage errors without crashing the program > ✅ The `try-except` block allows for graceful error handling and program recovery. # What happens if an exception occurs and is not caught by the program? - [x] The program terminates with an error message > ✅ If an exception is not caught, the program terminates and prints an error message explaining the issue. - [ ] The exception is ignored and the program continues running > ❌ Unhandled exceptions are not ignored; they cause the program to terminate. - [ ] The program continues after skipping the exception > ❌ An unhandled exception stops the program from continuing its execution. - [ ] The program enters an infinite loop > ❌ Exceptions do not cause infinite loops; they cause the program to terminate unless handled. - [x] The type of exception is printed along with a traceback > ✅ The exception type and a traceback showing where the error occurred are printed when an exception is not caught. # What is the difference between exceptions and assertions? - [x] Exceptions handle errors during execution, while assertions check conditions during development > ✅ Exceptions are for handling errors during execution, while assertions are checks to validate conditions during development. - [ ] Assertions are for catching user input errors, while exceptions are for handling logic errors > ❌ Assertions are not for catching user input errors; they are used to check conditions during development. - [x] Assertions are used to ensure certain conditions are true during runtime > ✅ Assertions are used to validate that certain conditions hold true during program execution. - [ ] Exceptions are only used during development > ❌ Exceptions are used during runtime to handle errors in production as well as development. - [x] Assertions can be disabled in production environments > ✅ Assertions are often disabled in production environments to avoid unnecessary checks and performance overhead. # When should you use assertions in your code? - [x] To validate assumptions during development > ✅ Assertions are used to validate assumptions in the code, ensuring expected conditions are met during development. - [ ] To handle user input errors > ❌ Assertions should not be used for handling user input errors; exceptions are more appropriate for that purpose. - [x] To check invariants and enforce constraints > ✅ Assertions are useful for checking invariants and enforcing constraints in the code. - [ ] To replace all error handling in production > ❌ Assertions are typically disabled in production and should not replace error handling mechanisms like exceptions. - [x] To catch logical errors early during the development phase > ✅ Assertions help catch logical errors during development by checking for expected conditions in the code. # What should assertions NOT be used for? - [x] Handling user input errors > ✅ Assertions should not be used for handling user input errors. Input validation is better handled by exceptions. - [ ] Checking that the state of the program is correct > ❌ Assertions are meant to check the state of the program during development. - [x] Checking conditions that may be caused by external factors (e.g., user input) > ✅ Assertions should not be used for checking conditions that may be affected by external factors, like user input or network issues. - [ ] Verifying assumptions during development > ❌ Assertions are designed to verify assumptions during development. - [x] Performing tasks with side effects, like opening files or modifying data > ✅ Assertions should not perform actions that modify the state of the program; they are for checks, not side effects.

Defensive programming

# What is defensive programming? - [x] A way of writing code that anticipates possible user errors > ✅ Defensive programming focuses on anticipating user errors to prevent crashes and improve error handling. - [ ] A method to write code that runs faster > ❌ Defensive programming is not about optimizing speed, but rather about improving resilience and reliability. - [x] A programming approach that aims to reduce crashes due to bad input > ✅ By anticipating errors and validating inputs, defensive programming helps prevent crashes caused by bad input. - [ ] A technique to ensure all user input is ignored > ❌ Defensive programming does not ignore input; it ensures that input is properly validated. - [x] A strategy for making programs more resilient to unexpected conditions > ✅ Defensive programming aims to make programs more resilient by preparing for unexpected inputs or conditions. # What are the key principles of defensive programming? - [x] Input validation > ✅ Input validation ensures that inputs are correctly formatted and prevent invalid or malicious data from causing issues. - [ ] Always assuming the user knows what they are doing > ❌ Defensive programming assumes that users can make mistakes, so it validates input rather than trusting it completely. - [x] Fail-safe defaults > ✅ A fail-safe default ensures that when something goes wrong, the program enters a safe state rather than proceeding with an incorrect or dangerous action. - [x] Avoiding assumptions > ✅ Defensive programming involves avoiding assumptions about the correctness of input or system states, preparing for errors instead. - [ ] Assuming that errors will never occur > ❌ The opposite is true in defensive programming. It assumes errors will occur and prepares for them. # What is the purpose of input validation in defensive programming? - [x] To ensure that user input is valid before processing it > ✅ Input validation checks that input is properly formatted and safe before processing it, preventing unexpected errors. - [ ] To allow the program to run faster > ❌ Input validation may add processing steps, but its purpose is to ensure safety, not speed. - [x] To prevent malicious or malformed input from causing errors > ✅ Proper input validation helps prevent security vulnerabilities and crashes caused by invalid input. - [ ] To assume that all input is always correct > ❌ Defensive programming does not assume that input is always correct; it validates it to ensure safety. - [x] To improve the security and robustness of the program > ✅ By validating input, programs become more secure and robust against attacks and user errors. # What are assertions used for in defensive programming? - [x] To check conditions that should never occur during normal operation > ✅ Assertions are used to check for conditions that should not occur under normal circumstances, catching bugs early in development. - [ ] To replace input validation > ❌ Assertions are not a replacement for input validation. They are used to check assumptions made during development. - [x] To help catch logical errors during the development phase > ✅ Assertions help catch logical errors early by verifying that certain conditions are met during execution. - [ ] To handle all user errors in production > ❌ Assertions are typically disabled in production and should not be used to handle user input errors. - [x] To enforce conditions that must always be true for the system to function correctly > ✅ Assertions enforce conditions that must be true for the system to function correctly, such as invariants in a program. # Which of the following are examples of defensive programming practices? - [x] Validating user inputs > ✅ Validating inputs ensures that data provided by the user is correct and safe to process. - [ ] Using global variables to share data across the program > ❌ Using global variables is discouraged in defensive programming because it can lead to hard-to-find bugs and unintended side effects. - [x] Providing meaningful error messages when something goes wrong > ✅ Providing meaningful error messages helps users understand the problem and adjust their behavior. - [x] Using fail-safe defaults > ✅ Fail-safe defaults ensure that when something goes wrong, the system behaves in a safe and predictable manner. - [ ] Ignoring edge cases to simplify code > ❌ Ignoring edge cases can lead to bugs and unpredictable behavior. Defensive programming involves considering edge cases and handling them appropriately.

Writing tests

# What is the purpose of writing tests in software development? - [x] To verify that code behaves as expected > ✅ Writing tests ensures that each part of the program functions as expected and meets its specifications. - [ ] To make the code run faster > ❌ Tests are not designed to improve the speed of the code; they are used to verify correctness. - [x] To detect bugs and regressions early in the development process > ✅ Tests help detect bugs and regressions early, reducing the cost of fixing errors later in the development cycle. - [x] To ensure new changes do not break existing functionality > ✅ By running tests after code changes, developers can confirm that new features or fixes do not introduce new bugs or break existing code. - [ ] To automatically fix errors in the code > ❌ Tests help identify errors but do not automatically fix them. # What are the benefits of automated testing? - [x] It facilitates maintenance by detecting issues quickly > ✅ Automated tests quickly detect issues in the code, making it easier to maintain and update software. - [ ] It replaces the need for human review of the code > ❌ Automated testing complements human review, but it does not replace the need for thorough code review by developers. - [x] It supports continuous integration and deployment (CI/CD) > ✅ Automated tests are essential in CI/CD pipelines, ensuring that code changes are thoroughly tested before being integrated or deployed. - [x] It boosts developer confidence when making changes to the code > ✅ Knowing that tests will catch errors allows developers to refactor and improve code with confidence. - [ ] It guarantees that the software will never have bugs > ❌ Automated testing helps reduce bugs, but it cannot guarantee that all bugs will be caught. # What are unit tests? - [x] Tests that focus on individual units or components of the software > ✅ Unit tests focus on testing individual units, such as functions or methods, in isolation from the rest of the application. - [ ] Tests that verify the interaction between multiple components > ❌ This describes integration tests, not unit tests. Unit tests focus on individual components. - [x] Tests that ensure a single function or method works as expected > ✅ Unit tests verify that individual functions or methods behave correctly. - [ ] Tests that check the security of the entire application > ❌ Unit tests do not cover security; this is the purpose of security tests. - [x] Tests that are written to run quickly and independently > ✅ Unit tests are designed to run quickly and independently, ensuring that individual components work as expected. # Why is it important to write tests before the code (test-driven development)? - [x] Tests define the expected behavior of the code before it is implemented > ✅ Writing tests first (as in test-driven development) defines the expected behavior of the code before it is implemented. - [ ] It ensures the code will have no bugs > ❌ Writing tests first does not guarantee that there will be no bugs, but it helps reduce them by clarifying expectations. - [x] It encourages developers to think critically about the design and functionality > ✅ Writing tests first encourages developers to think about the design and functionality of the code before implementation begins. - [ ] It makes the code run faster > ❌ Test-driven development focuses on improving code quality, not speed. - [x] It promotes communication and ensures shared understanding of project goals > ✅ Writing tests before coding promotes better communication and ensures that all stakeholders have a shared understanding of the project’s goals.

Documenting and commenting the code

# Why is documenting code important? - [x] It makes the code easier to read and maintain > ✅ Documenting code ensures that other developers can easily understand and maintain it without needing to decipher the logic on their own. - [ ] It makes the code run faster > ❌ Documentation improves readability and maintainability, not performance. - [x] It helps new developers get up to speed quickly > ✅ Well-documented code allows new developers to understand the purpose and structure of the project faster, reducing onboarding time. - [x] It improves collaboration among team members > ✅ Good documentation fosters collaboration by providing a shared understanding of the codebase. - [ ] It eliminates the need for comments in the code > ❌ Documentation does not replace the need for comments within the code, which explain specific logic or decisions. # What is the role of comments in code? - [x] To make the code easier to understand > ✅ Comments explain how parts of the code work, making it easier for others to understand complex or non-trivial logic. - [ ] To rewrite the code in plain English > ❌ Comments should not paraphrase the code itself; they should explain its purpose, logic, and design decisions. - [x] To provide additional information about algorithms or decisions > ✅ Comments are useful for describing algorithms, design decisions, limitations, or future improvements (TODOs). - [x] To explain the purpose of complex parts of the code > ✅ For non-trivial sections of code, comments are essential to explain the purpose and ensure maintainability. - [ ] To avoid the need for documentation > ❌ Comments complement documentation but do not replace it. Both serve different purposes in the development process. # What should comments NOT do? - [x] Paraphrase the code > ✅ Comments should not simply restate the code in plain English; they should provide additional insights and explanations. - [ ] Explain non-trivial parts of the code > ❌ Comments should explain non-trivial or complex logic to aid understanding. - [ ] Provide context for design decisions > ❌ Comments can be used to explain why certain design decisions were made. - [x] Overwhelm the code with unnecessary details > ✅ Too many comments can make the code harder to read. It's important to strike a balance and only comment where necessary. - [x] Replace good variable and function names > ✅ Good variable and function names should make the code self-explanatory in many cases, reducing the need for excessive comments. # What is the primary goal of documenting function and class signatures? - [x] To describe input parameters and return values > ✅ Documenting function and class signatures helps explain the input parameters, return values, and any exceptions that may be raised. - [ ] To rewrite the logic of the function in comments > ❌ The purpose is not to rewrite the function logic but to describe its inputs, outputs, and behavior. - [x] To make the code easier to understand and use > ✅ Providing clear documentation for function and class signatures makes it easier for developers to use and understand the code. - [ ] To automatically generate unit tests > ❌ While function signatures help in testing, their documentation is not meant to generate tests automatically. - [x] To facilitate the generation of external documentation > ✅ Documentation of function and class signatures can be used to generate external documentation that developers can refer to when using the code. # How do docstrings support automatic documentation? - [x] Tools like `pydoc` can extract docstrings to generate documentation > ✅ Docstrings can be extracted by tools like `pydoc` to generate human-readable documentation automatically. - [ ] They replace the need for comments in the code > ❌ Docstrings provide documentation but do not replace comments, which explain specific parts of the code or logic. - [x] They provide detailed descriptions of functions, methods, or classes > ✅ Docstrings describe the purpose and behavior of functions, methods, or classes, which can then be used to generate documentation. - [x] They are written directly in the source code > ✅ Docstrings are embedded directly in the source code, making them easily accessible for both developers and documentation tools. - [ ] They are only used in compiled languages > ❌ Docstrings are not exclusive to compiled languages; they are widely used in interpreted languages like Python.