Hackerrank Functions and Modularity 2 — Questions and Answers
Question 1: What does the `*args` parameter in a Python function allow?
- Passing a variable number of keyword arguments
- Passing a variable number of positional arguments (Correct answer)
- Unpacking a dictionary into function arguments
- Defining default argument values
Correct answer: Passing a variable number of positional arguments
`*args` collects extra positional arguments into a tuple, allowing functions to accept any number of positional inputs.
Question 2: Which statement correctly imports only the `sqrt` function from the `math` module?
- import math.sqrt
- from math import sqrt (Correct answer)
- import sqrt from math
- include math.sqrt
Correct answer: from math import sqrt
`from math import sqrt` selectively imports just the `sqrt` name into the current namespace.
Question 3: What is the output of the following code? ```python def f(x, y=10): return x + y print(f(5)) ```
- Error
- 5
- 15 (Correct answer)
- 10
Correct answer: 15
Since `y` defaults to 10 and only `x=5` is passed, the function returns 5 + 10 = 15.
Question 4: What does `__name__ == '__main__'` check for in a Python module?
- Whether the module has a main() function
- Whether the script is being run directly (not imported) (Correct answer)
- Whether the module name is 'main'
- Whether the Python interpreter is in interactive mode
Correct answer: Whether the script is being run directly (not imported)
When a script is run directly, Python sets `__name__` to `'__main__'`; when imported, it's set to the module's name.
Question 5: What is a closure in Python?
- A function that closes open file handles automatically
- A nested function that captures variables from its enclosing scope (Correct answer)
- A function with no return statement
- A class method that restricts attribute access
Correct answer: A nested function that captures variables from its enclosing scope
A closure is a nested function that retains access to variables from its enclosing function even after that function has returned.
Question 6: Which built-in function applies a function to every item in an iterable and returns a map object?
- apply()
- filter()
- map() (Correct answer)
- reduce()
Correct answer: map()
`map(func, iterable)` applies `func` to each element and returns a lazy map object.
Question 7: What will this code output? ```python def counter(): count = 0 def increment(): nonlocal count count += 1 return count return increment c = counter() print(c(), c()) ```
- 0 1
- 1 1
- 1 2 (Correct answer)
- Error
Correct answer: 1 2
`nonlocal` allows `increment` to modify `count` in the enclosing scope, so successive calls produce 1 then 2.
What does the `*args` parameter in a Python function allow?