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

Functions in a programming language

# Why is the use of functions so important? - [ ] It makes your code faster to run > ❌ While functions provide structure, they don't necessarily make code faster. Performance depends on the implementation and context. - [x] It makes your code more reusable > ✅ Functions allow code to be reused across different parts of a program or even in different projects. - [x] It makes your code easier to read > ✅ Functions break up complex code into smaller, manageable sections, improving readability. - [x] It makes your code easier to test > ✅ Testing small, isolated functions is easier than testing larger blocks of code, which may have many dependencies. # What is true? - [ ] A Python function always returns a value > ❌ A function does not always return a value. If there is no return statement, it returns `None` by default. - [x] A Python function can return multiple values > ✅ Python functions can return multiple values, often as tuples. - [ ] Python executes a function when the `def` keyword is met > ❌ The function is only executed when it is called, not when it is defined with the `def` keyword. - [x] A function can be passed as an argument of another function > ✅ Python allows functions to be passed as arguments to other functions, enabling functional programming techniques. # Which call(s) is(are) correct considering the following function prototype? ```python def random_values (nb_points: int, min_v: int = 0, max_v: int = 100) -> List[int]: """ Returns a list of n random integers between minv and maxv (inclusive). In: * nb_points: The number of values to generate. * min_v: The minimum value for the random integers. * max_v: The maximum value for the random integers. Out: * A list of n random integers between min_v and max_v (inclusive). """ ``` - [ ] `l = random_values(5, 0, 100) -> a` > ❌ This syntax is invalid because `-> a` is not a valid Python function call notation. - [x] `l = random_values(5, 0, 100)` > ✅ This is a valid function call, specifying all three arguments. - [x] `l = random_values(5)` > ✅ Since `min_v` and `max_v` have default values, calling with just `nb_points` is valid. - [x] `l = random_values(5, 10)` > ✅ This call overrides `min_v` with `10`, while `max_v` uses its default value of `100`. - [x] `l = random_values(max_v=100, min_v=10, nb_points=5)` > ✅ This call uses keyword arguments to specify the values out of order, which is valid in Python. - [x] `l = random_values(nb_points=5, min_v=10, max_v=100)` > ✅ This is another valid call using keyword arguments in order. - [ ] `l = random_values()` > ❌ The `nb_points` argument is required, so this call would raise an error. - [ ] `l = random_values('100', '0', '100')` > ❌ The arguments must be integers, not strings. - [ ] `l = random_values[5, 0, 100]` > ❌ This syntax uses square brackets, which are not correct for calling a function. # What is the output of the following code? ```python # Define a function def func (*args): s = "" for i in args: s += str(i) + "-" print(s) # Call it func('a', 3, 0.3) ``` 1. [x] `a-3-0.3-` > ✅ The function concatenates the string representations of the arguments, separated by hyphens. 1. [ ] `0.3-` > ❌ The function processes all the arguments, not just the last one. 1. [ ] An error is returned due to argument mismatch > ❌ The function accepts a variable number of arguments (*args), so there is no argument mismatch.

Organizing codes in libraries

{

# What is the main benefit of organizing code into modules? - [x] Reusability of code > ✅ Modules allow code to be reused in multiple projects, reducing duplication. - [ ] Increased program execution speed > ❌ Modules do not necessarily improve the execution speed of a program. - [x] Easier management and maintenance of code > ✅ Breaking code into modules makes it easier to maintain and manage. - [x] Better structure and coherence > ✅ Modules help structure code logically, improving overall coherence. - [ ] Reduced memory usage > ❌ Memory usage is not directly affected by organizing code into modules. # How can you prevent certain parts of code from being executed when a file is imported as a module? - [ ] Use the `import` keyword > ❌ The `import` keyword is used to import modules, not prevent code from being executed. - [ ] Use a `global` declaration for the variables > ❌ `global` only controls variable scope, not the execution of code when importing modules. - [x] Use the `if __name__ == "__main__":` construct > ✅ This construct ensures that code is only executed when the file is run directly, not when it's imported. - [x] Include test cases in the main script only > ✅ By including test cases in the main script, they are not executed when the file is imported. - [ ] Use a `def` statement to encapsulate all the code > ❌ Encapsulating code in a function doesn't prevent it from being executed when imported. # Which Python variable contains the list of directories where Python looks for modules? 1. [ ] `os.path` > ❌ `os.path` handles file path operations, not module search paths. 1. [x] `sys.path` > ✅ `sys.path` contains the list of directories where Python searches for modules. 1. [ ] `__file__` > ❌ `__file__` contains the path of the script being executed, not the search path for modules. 1. [ ] `PYTHONPATH` > ❌ While `PYTHONPATH` can influence module search paths, the correct answer is `sys.path`. 1. [ ] `dir()` > ❌ `dir()` is used to list attributes of objects, not to manage module search paths. # Why is it important to split large codebases into multiple files (modules)? - [x] It allows for better organization and separation of concerns > ✅ Organizing code into modules separates functionality, making the codebase easier to manage. - [x] It improves code maintainability and reusability > ✅ Modular code is easier to maintain and reuse across different projects. - [ ] It reduces the size of each function > ❌ Splitting code into modules does not directly affect the size of individual functions. - [x] It makes testing individual components easier > ✅ Modules allow for more focused and isolated testing of individual components. - [ ] It eliminates the need for the `import` statement > ❌ The `import` statement is still required to use modules, even in a modular codebase. # Which of the following are good practices for organizing code into libraries? - [x] Group related functions into separate files based on themes > ✅ Grouping related functions into files based on their purpose improves organization. - [ ] Avoid splitting code into multiple files for simplicity > ❌ Splitting code into multiple files helps improve maintainability and organization. - [x] Use meaningful file names to avoid name conflicts with Python's standard libraries > ✅ Using descriptive and unique file names prevents conflicts with standard library names. - [ ] Always include all code in one main file > ❌ Including all code in one file leads to cluttered and difficult-to-maintain code. - [x] Use documentation and comments to explain the purpose of each module > ✅ Proper documentation and comments help explain each module's purpose and usage.

Installing Python modules

# What is `pip` used for in Python? - [x] Installing external packages and modules > ✅ `pip` is the standard package installer for Python, used to install external packages. - [ ] Running Python scripts > ❌ `pip` is not used to run Python scripts; it's used to manage packages. - [x] Managing Python package dependencies > ✅ `pip` handles the installation of dependencies for Python packages. - [ ] Compiling Python programs > ❌ `pip` does not compile Python programs; it installs packages. - [x] Installing libraries from the Python Package Index (PyPI) > ✅ `pip` installs libraries from PyPI, the official repository for Python packages. # What is a Python package? - [x] A collection of modules > ✅ A Python package is a collection of modules organized together. - [ ] A single Python script > ❌ A single Python script is not a package; it's just a module. - [x] A directory that contains multiple related modules > ✅ A package is a directory that includes multiple related modules, often with an `__init__.py` file. - [ ] A file installed from the web > ❌ While packages can be downloaded from the web, this does not define a Python package. - [x] A package that allows using dotted module names > ✅ Python packages support dotted module names, which help organize modules in namespaces. # What does command `pip3 install numpy` do? - [x] Installs the NumPy package for Python 3 > ✅ This command installs NumPy for Python 3. - [ ] Updates an existing version of NumPy > ❌ The `install` command installs a package, but does not necessarily update it. - [ ] Installs NumPy for Python 2 only > ❌ `pip3` is for Python 3, not Python 2. - [x] Fetches the package from PyPI and installs it > ✅ `pip` retrieves the NumPy package from PyPI and installs it. - [ ] Uninstalls NumPy from your system > ❌ The command is for installing, not uninstalling. # Which command would you use to upgrade an already installed package? - [ ] `pip install --version latest` > ❌ There is no `--version latest` option for upgrading a package. - [ ] `pip upgrade ` > ❌ `pip upgrade` is not a valid command for upgrading packages. - [x] `pip install --upgrade ` > ✅ This command upgrades an already installed package. - [x] `pip3 install --upgrade ` > ✅ This is the correct syntax for upgrading a package in Python 3. - [ ] `pip update ` > ❌ `pip update` is not a valid command for upgrading packages. # Why might `pip` fail to install a package even though the command is correct? - [x] The package is being installed for the wrong Python version > ✅ If `pip` is associated with a different Python version, the installation may fail. - [x] The package does not exist in the PyPI repository > ✅ If the package isn't listed on PyPI, `pip` won't be able to find it. - [ ] The system has too many installed modules > ❌ The number of installed modules does not affect the ability to install a new package. - [x] The Python executable being used is different from the one associated with pip > ✅ If `pip` is linked to a different Python executable, the installation may fail for the target Python version. - [ ] Python is not installed on the system > ❌ If Python wasn't installed, `pip` itself wouldn't be available to use.

Variables visibility and scope

# What is the output of the following code? ```python # Define a variable x = 30 # Define a function def my_func(): x = 20 print("D1:", x) # Call it my_func() print("D2:", x) ``` 1. [x] `D1: 20` et `D2: 30` > ✅ The variable `x` inside the function is local to the function, so it does not affect the global variable `x`. Hence, `D1: 20` and `D2: 30`. 1. [ ] `D1: 30` et `D2: 30` > ❌ The local variable `x` inside the function does not affect the global variable, so `D1` is `20`, not `30`. 1. [ ] `D1: 20` et `D2: 20` > ❌ The local `x` inside the function is `20`, but it doesn't change the global `x`, which remains `30` after the function call. # What are the main differences between local and global variables? - [x] Local variables are only visible within the function where they are defined > ✅ Local variables are scoped to the function they are defined in and cannot be accessed outside of it. - [x] Global variables can be accessed from anywhere in the program > ✅ Global variables are accessible from any part of the program, including inside functions (unless shadowed by a local variable). - [ ] Local variables exist throughout the program's execution > ❌ Local variables only exist during the execution of the function they are defined in, not throughout the entire program. - [ ] Global variables are deleted after the function finishes executing > ❌ Global variables persist until the program ends, unlike local variables that are confined to function scope. - [ ] Local variables are automatically global after they are used in a loop > ❌ Local variables remain local to their function, even if they are used in a loop within that function. # What happens if you try to access a local variable outside its function? - [ ] The program will print the value of the variable > ❌ Local variables cannot be accessed outside of the function where they are defined, so nothing will be printed. - [ ] The variable will become global > ❌ Local variables do not automatically become global when accessed outside their scope. - [x] A `NameError` will occur > ✅ Accessing a local variable outside its function raises a `NameError` because it is not defined in the global scope. - [x] The interpreter will report that the variable is not defined > ✅ When a local variable is accessed outside its scope, the interpreter raises an error stating that the variable is not defined. - [ ] The function will be called automatically > ❌ Functions are not automatically called if you try to access a local variable outside its scope. # What will be printed if a local and global variable share the same name inside a function? - [x] The local variable will "hide" the global variable > ✅ If a local variable shares the same name as a global variable, the local variable will shadow the global variable within the function's scope. - [ ] Both the global and local variables will be printed > ❌ Only the local variable will be printed inside the function because it shadows the global variable. - [ ] A runtime error will occur > ❌ No error will occur. The local variable will simply hide the global one. - [ ] The global variable will override the local one > ❌ The local variable will override (or shadow) the global variable within the function's scope, not the other way around. - [x] Only the local variable's value will be printed inside the function > ✅ The function will only print the value of the local variable because it takes precedence over the global one within the function.