Scope, LEGB Rule & Closures — Concept Check
Questions on Scope, LEGB Rule & Closures. Python resolves names through LEGB — Local, Enclosing, Global, Built-in — and inner functions capture enclosing variables as closures, the mechanism behind decorators.
Questions in this quiz
8 questions on Scope, LEGB Rule & Closures — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.A developer tries to increment a global variable inside a function without using any keywords. What error do they encounter?
- ANameError
- BSyntaxError
- CTypeError
- DUnboundLocalError
2.In a nested function, you want to modify a variable from the enclosing scope. Which keyword should you use?
- Aglobal
- Blocal
- Cstatic
- Dnonlocal
3.A function factory returns a function that applies a percentage rate to an amount. What concept allows this?
- AClosure
- BDecorator
- CGenerator
- DLambda
4.A developer sees 'UnboundLocalError' when reading a variable before assignment in a function. Why?
- AThe variable is local but used before assignment.
- BThe variable is a built-in and cannot be reassigned.
- CThe variable is declared global but not initialized.
- DThe variable is not declared at all.
5.What happens if you try to modify a global variable inside a function without declaring it as global?
- AThe program crashes.
- BA new local variable is created.
- CThe global variable is modified.
- DA SyntaxError is raised.
6.You have two independent counters created by a function. What allows them to maintain separate states?
- AEach counter is a separate instance of a class.
- BEach counter uses a closure with its own state.
- CEach counter uses a static method.
- DEach counter uses a global variable.
7.A developer believes using 'global' inside a nested function will modify the enclosing scope variable. Is this correct?
- ANo, 'global' affects only module-level variables.
- BYes, 'global' modifies the enclosing scope variable.
- CYes, but only if the variable is declared outside the function.
- DNo, 'global' cannot be used in nested functions.
8.Why might a developer use closures instead of global variables for maintaining state?
- AClosures are faster than global variables.
- BClosures allow parallel execution.
- CClosures are easier to debug than global variables.
- DClosures provide encapsulation and avoid global state.