Functions and Modularity Flashcards
7 cards from real HACKERRANK practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 Functions and Modularity flashcards as text
What does the `*args` parameter in a Python function allow?
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.
Which statement correctly imports only the `sqrt` function from the `math` module?
Answer: from math import sqrt
`from math import sqrt` selectively imports just the `sqrt` name into the current namespace.
What is the output of the following code? ```python def f(x, y=10): return x + y print(f(5)) ```
Answer: 15
Since `y` defaults to 10 and only `x=5` is passed, the function returns 5 + 10 = 15.
What does `__name__ == '__main__'` check for in a Python module?
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.
What is a closure in Python?
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.
Which built-in function applies a function to every item in an iterable and returns a map object?
Answer: map()
`map(func, iterable)` applies `func` to each element and returns a lazy map object.
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()) ```
Answer: 1 2
`nonlocal` allows `increment` to modify `count` in the enclosing scope, so successive calls produce 1 then 2.