Python Functions and Scope 2 — Questions and Answers
Question 1: What does the `global` keyword do inside a function?
- Creates a new local variable
- Declares that a variable refers to the global scope (Correct answer)
- Deletes a global variable
- Makes a variable read-only
Correct answer: Declares that a variable refers to the global scope
The `global` keyword tells Python that assignments to that name should affect the module-level variable, not create a new local one.
Question 2: What is the output of: `def f(x=[]): x.append(1); return x` called three times?
- [1], [1], [1]
- [1], [1,1], [1,1,1] (Correct answer)
- Error on second call
- [1], [], [1]
Correct answer: [1], [1,1], [1,1,1]
Mutable default arguments are created once and shared across calls, so the list grows with each call.
Question 3: Which LEGB scope is checked first when resolving a variable name in Python?
- Enclosing
- Global
- Built-in
- Local (Correct answer)
Correct answer: Local
Python's LEGB rule checks Local scope first, then Enclosing, then Global, then Built-in.
Question 4: What does `*args` capture in a function definition?
- Keyword arguments as a dict
- Positional arguments as a tuple (Correct answer)
- All arguments as a list
- Only the first extra argument
Correct answer: Positional arguments as a tuple
`*args` collects any extra positional arguments passed to the function into a tuple.
Question 5: What is a closure in Python?
- A function that calls itself
- A function that modifies global variables
- A nested function that remembers its enclosing scope's variables (Correct answer)
- A function with no return value
Correct answer: A nested function that remembers its enclosing scope's variables
A closure is an inner function that retains access to variables from its enclosing function's scope even after that function has returned.
Question 6: What will `print(type(lambda x: x))` output?
- <class 'lambda'>
- <class 'function'> (Correct answer)
- <class 'method'>
- <class 'builtin_function_or_method'>
Correct answer: <class 'function'>
Lambda expressions create regular function objects; their type is `function`, the same as functions defined with `def`.
Question 7: Which statement about `nonlocal` is correct?
- It allows access to global variables
- It allows a nested function to assign to an enclosing (non-global) variable (Correct answer)
- It creates a new variable in the built-in scope
- It is only available in Python 2
Correct answer: It allows a nested function to assign to an enclosing (non-global) variable
`nonlocal` lets an inner function rebind a variable in the nearest enclosing scope that is not the global scope.
What does the `global` keyword do inside a function?