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 will the following code print? x = 10 def foo(): x = 20 foo() print(x)
Answer: 10
The assignment inside foo() creates a local variable; the global x remains 10.
Which statement correctly describes the LEGB rule in Python?
Answer: Local, Enclosing, Global, Built-in — the order Python searches for names
LEGB stands for Local, Enclosing, Global, Built-in — Python's name resolution order.
What error occurs when you read a variable inside a function before assigning it, if the same name exists globally?
Answer: UnboundLocalError
Python detects the assignment later in the function and marks the name as local, so reading it before assignment raises UnboundLocalError.
What does the following code output? count = 0 def increment(): global count count += 1 increment() increment() print(count)
Answer: 2
global count lets increment() modify the module-level variable, so two calls produce 2.
Which of the following is a valid use of the global keyword?
Answer: global x; x = 5
The global statement declares the name, then a separate assignment sets the value; combining them on one line with = is a SyntaxError.
What is the output of the code below? def outer(): y = 100 def inner(): print(y) inner() outer()
Answer: 100
inner() reads y from the enclosing scope of outer() via the LEGB rule without any keyword needed.
Which of the following names is in Python's built-in scope?
Answer: len
len is a built-in function provided by Python; the others are user-defined names.