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? x = 'global' def test(): global x x = 'local' test() print(x)
Answer: local
global x inside test() makes the assignment modify the module-level x, so it becomes 'local'.
Can a function declare multiple names global in a single statement?
Answer: Yes: global a, b, c
A single global statement can list multiple comma-separated names: global a, b, c.
What happens when you use the global keyword on a name that does not yet exist at module level?
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.
What is the output of the following code? def outer(): x = 1 def inner(): x = 2 inner() print(x) outer()
Answer: 1
inner() creates its own local x = 2 without nonlocal, so outer()'s x stays 1.
Which scope level is searched LAST in the LEGB rule?
Answer: Built-in
Python searches Local → Enclosing → Global → Built-in, so Built-in is the last resort.
What will this code output? total = 0 def add(n): total = total + n return total print(add(5))
Answer: UnboundLocalError
Python sees total = ... and marks it local, so reading total before assignment raises UnboundLocalError.
Where is a variable defined inside a for loop (at module level) accessible?
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.
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