PCEP Variable Scope and the `global` keyword 3 — Questions and Answers
Question 1: What is the output? x = 'global' def test(): global x x = 'local' test() print(x)
- local (Correct answer)
- global
- None
- Error
Correct answer: local
global x inside test() makes the assignment modify the module-level x, so it becomes 'local'.
Question 2: Can a function declare multiple names global in a single statement?
- Yes: global a, b, c (Correct answer)
- No: each name needs its own global statement
- Yes: global (a, b, c)
- No: global is limited to one name per function
Correct answer: Yes: global a, b, c
A single global statement can list multiple comma-separated names: global a, b, c.
Question 3: What happens when you use the global keyword on a name that does not yet exist at module level?
- Python creates the variable at module level when it is assigned inside the function (Correct answer)
- Python raises a NameError immediately
- Python raises a SyntaxError at compile time
- The variable is created locally instead
Correct answer: Python creates the variable at module level when it is assigned inside the function
global just declares intent; the global variable is created upon the first assignment inside the function.
Question 4: What is the output of the following code? def outer(): x = 1 def inner(): x = 2 inner() print(x) outer()
- 1 (Correct answer)
- 2
- None
- Error
Correct answer: 1
inner() creates its own local x = 2 without nonlocal, so outer()'s x stays 1.
Question 5: Which scope level is searched LAST in the LEGB rule?
- Built-in (Correct answer)
- Global
- Enclosing
- Local
Correct answer: Built-in
Python searches Local → Enclosing → Global → Built-in, so Built-in is the last resort.
Question 6: What will this code output? total = 0 def add(n): total = total + n return total print(add(5))
- UnboundLocalError (Correct answer)
- 5
- 0
- None
Correct answer: UnboundLocalError
Python sees total = ... and marks it local, so reading total before assignment raises UnboundLocalError.
Question 7: Where is a variable defined inside a for loop (at module level) accessible?
- Anywhere in the module after the loop runs (Correct answer)
- Only inside the for loop block
- Only inside a function that contains the loop
- Nowhere — loops create their own scope
Correct answer: Anywhere in the module after the loop runs
Python loops do not create a new scope; the loop variable leaks into the enclosing (module-level) namespace.
What is the output?
x = 'global'
def test():
global x
x = 'local'
test()
print(x)