PCEP-30-02 · Question #191
def func(data): data = [7, 23, 42] print('Function scope: ', data) data = ['Peter', 'Paul', 'Mary'] print('Outer scope: ', data)
The correct answer is B. Function scope: [7, 23, 42] Outer scope: ['Peter', 'Paul', 'Mary']. Option B is correct because inside func, the line data = [7, 23, 42] creates a new local variable named data - it does not modify the outer data. Python's scoping rules (LEGB: Local, Enclosing, Global, Built-in) mean that any assignment inside a function creates a local…
Question
Options
- AFunction scope: ['Peter', 'Paul', 'Mary'] Outer scope: ['Peter', 'Paul', 'Mary']
- BFunction scope: [7, 23, 42] Outer scope: ['Peter', 'Paul', 'Mary']
- CNone of the above.
- D1 Function scope: [7, 23, 42] 2 Outer scope: [7, 23, 42]
How the community answered
(37 responses)- A16% (6)
- B76% (28)
- C5% (2)
- D3% (1)
Explanation
Option B is correct because inside func, the line data = [7, 23, 42] creates a new local variable named data - it does not modify the outer data. Python's scoping rules (LEGB: Local, Enclosing, Global, Built-in) mean that any assignment inside a function creates a local binding, leaving the outer data = ['Peter', 'Paul', 'Mary'] completely untouched.
Why the distractors are wrong:
- A is wrong because it assumes the function somehow printed the outer list - but the local assignment
data = [7, 23, 42]overrides the parameter inside the function's scope. - D is wrong because the outer scope never gets reassigned; the function's local
datadies when the function returns, so the outer print still sees['Peter', 'Paul', 'Mary'], not[7, 23, 42]. - C ("None of the above") is wrong because B is a valid and correct output.
Memory tip: Think of a function as a "Vegas rule" - what happens inside the function, stays inside the function. Assigning a variable inside a function never reaches outside unless you explicitly use global or return the value.
Community Discussion
No community discussion yet for this question.