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? def f(): global z z = 99 f() print(z)
Answer: 99
f() creates global z = 99, so it is accessible at module level after the call.
Which of the following statements about variable shadowing is TRUE?
Answer: A local variable with the same name as a global variable hides the global inside that function
Shadowing means the local name takes precedence inside the function; the global is unaffected.
What is printed? a = 1 def outer(): a = 2 def inner(): a = 3 print(a) inner() print(a) outer() print(a)
Answer: 3 2 1
Each function has its own local a; inner prints 3, outer prints 2, module level prints 1.
Which built-in function lets you inspect the global namespace dictionary?
Answer: globals()
globals() returns a dictionary of the current module's global namespace.
What is the result of the following code? x = 'outside' def test(): global x del x test() print(x)
Answer: NameError
del x with global x deletes the module-level variable, so print(x) raises NameError.
At what point does Python decide whether a variable name inside a function is local or global?
Answer: At compile time (when the function is defined), based on whether an assignment exists in the function body
Python's compiler scans the function body; if any assignment to a name exists (without global), it is marked local for the entire function.
What does the following code demonstrate? pi = 3.14 def area(r): return pi * r * r print(area(2))
Answer: A function reading a global variable without the global keyword (read-only access)
Functions can read global variables freely; global is only required when you want to rebind (assign to) the name inside the function.