Python Functions and Scope 3 — Questions and Answers
Question 1: What is the result of calling a function that has no `return` statement?
- 0
- None (Correct answer)
- An empty string
- Raises RuntimeError
Correct answer: None
Python functions implicitly return `None` when execution reaches the end without a `return` statement.
Question 2: How do you enforce that a function argument must be passed as a keyword-only argument?
- Place it before *args
- Place it after a bare * or after *args in the signature (Correct answer)
- Use the @keyword decorator
- Prefix the parameter name with **
Correct answer: Place it after a bare * or after *args in the signature
Parameters listed after `*` or `*args` in a function signature can only be passed by keyword, not positionally.
Question 3: What does `**kwargs` capture in a function definition?
- Extra positional arguments as a tuple
- Extra keyword arguments as a dictionary (Correct answer)
- All arguments as a list
- Default argument values
Correct answer: Extra keyword arguments as a dictionary
`**kwargs` collects any extra keyword arguments into a dictionary where keys are argument names.
Question 4: In Python, what is a first-class function?
- A function defined at module level
- A function that can be passed as an argument, returned, or assigned to a variable (Correct answer)
- A built-in function
- A function decorated with @classmethod
Correct answer: A function that can be passed as an argument, returned, or assigned to a variable
First-class functions are treated like any other object — they can be stored in variables, passed to other functions, and returned from functions.
Question 5: What error does Python raise when you try to read a local variable before assigning it?
- NameError
- UnboundLocalError (Correct answer)
- ScopeError
- ReferenceError
Correct answer: UnboundLocalError
`UnboundLocalError` is raised when a local variable is referenced before it has been assigned a value.
Question 6: Which of the following correctly unpacks a list into positional arguments?
- f(**my_list)
- f(*my_list) (Correct answer)
- f(my_list...)
- f(@my_list)
Correct answer: f(*my_list)
The `*` operator before an iterable in a function call unpacks its items as separate positional arguments.
Question 7: What is the purpose of a docstring in a function?
- It is executed before the function body
- It documents the function and is accessible via __doc__ (Correct answer)
- It enforces type checking
- It replaces the return statement
Correct answer: It documents the function and is accessible via __doc__
A docstring is a string literal as the first statement of a function body; Python stores it in the function's `__doc__` attribute.
What is the result of calling a function that has no `return` statement?