PCAP Functions and Modules 2 — Questions and Answers
Question 1: What is a closure in Python?
- A class with private attributes
- A function that captures variables from its enclosing scope (Correct answer)
- A module with restricted access
- A decorator pattern
Correct answer: A function that captures variables from its enclosing scope
A closure is a function that remembers the variables from its enclosing scope even after that scope has exited.
Question 2: What does the `global` keyword do inside a function?
- Creates a new global variable
- Declares that a variable refers to the global scope (Correct answer)
- Prevents variable modification
- Imports a global module
Correct answer: Declares that a variable refers to the global scope
`global` tells Python that the variable inside the function refers to the global namespace, not a local one.
Question 3: What is a decorator in Python?
- A special comment syntax
- A function that wraps another function to add behavior (Correct answer)
- A class attribute marker
- A module-level constant
Correct answer: A function that wraps another function to add behavior
A decorator is a callable that takes a function and returns a new function with added behavior.
Question 4: What does the `__name__ == '__main__'` guard do?
- Sets the module name
- Prevents code from running when the module is imported (Correct answer)
- Defines the main function
- Checks Python version
Correct answer: Prevents code from running when the module is imported
Code under `if __name__ == '__main__':` runs only when the script is executed directly, not when imported.
Question 5: What is a generator function in Python?
- A function that generates random numbers
- A function using `yield` to produce a sequence lazily (Correct answer)
- A function that returns a list
- A factory function
Correct answer: A function using `yield` to produce a sequence lazily
A generator function uses `yield` to produce values one at a time, suspending state between calls.
Question 6: Which keyword is used in a generator function to produce a value?
- return
- emit
- yield (Correct answer)
- send
Correct answer: yield
`yield` suspends the function and sends a value to the caller, resuming on the next iteration.
What is a closure in Python?