Variable Scope and the `global` keyword Flashcards
7 cards from real PCEP practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.
Read the first 7 Variable Scope and the `global` keyword flashcards as text
What is the output? result = [] for i in range(3): result.append(i) print(i)
Answer: 2
The loop variable i persists in module scope after the loop and holds its last value, 2.
What does the nonlocal keyword do in a nested function?
Answer: Allows the inner function to rebind a variable in the nearest enclosing function's scope
nonlocal targets the nearest enclosing (non-global) scope, letting the inner function modify that variable.
Which of the following correctly modifies a global list inside a function WITHOUT using the global keyword?
Answer: my_list.append(1)
Calling a method like append() mutates the object in place without rebinding the name, so global is not needed.
What is the output? x = 5 def show(): print(x) show() x = 10 show()
Answer: 5 10
Each call to show() reads x from global scope at the time of the call: first 5, then 10.
What is the scope of a variable defined inside an if block at module level?
Answer: Module (global) scope — if blocks don't create a new scope
Python has no block scope; variables created inside if, for, or with blocks belong to the enclosing function or module scope.
What will this code print? def make_counter(): count = 0 def inc(): nonlocal count count += 1 return count return inc c = make_counter() print(c(), c())
Answer: 1 2
nonlocal count lets inc() modify make_counter's count, which persists between calls, yielding 1 then 2.
If a name is not found in local, enclosing, or global scopes, where does Python look next?
Answer: Built-in scope
The final step in LEGB is the built-in scope, which contains names like print, len, and range.
How this page was made: written with AI tools and published by Nathan Beja, founder of Practice Test Geeks, who is responsible for its content. Exam facts are checked against the official sources listed below. Not reviewed by a subject-matter expert. Editorial policy
Sources & references
Exam facts on this page (fees, format, dates, passing scores) are checked against these official sources; the date is our last check. Editorial policy
- pythoninstitute.org — Fees, exam format, passing score, retake fee, score release, time limit, score validity, test delivery, eligibility, retake policy · verified Oct 2026