PCEP Variable Scope and the `global` keyword 2 — Questions and Answers
Question 1: What will the following code print? x = 10 def foo(): x = 20 foo() print(x)
- 10 (Correct answer)
- 20
- None
- Error
Correct answer: 10
The assignment inside foo() creates a local variable; the global x remains 10.
Question 2: Which statement correctly describes the LEGB rule in Python?
- Local, Enclosing, Global, Built-in — the order Python searches for names (Correct answer)
- Local, External, Global, Binary — the order of variable declarations
- Loop, Enclosing, Global, Block — scoping rules for loops
- Local, Evaluated, Generated, Bound — the order Python assigns values
Correct 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.
Question 3: What error occurs when you read a variable inside a function before assigning it, if the same name exists globally?
- UnboundLocalError (Correct answer)
- NameError
- SyntaxError
- AttributeError
Correct answer: UnboundLocalError
Python detects the assignment later in the function and marks the name as local, so reading it before assignment raises UnboundLocalError.
Question 4: What does the following code output? count = 0 def increment(): global count count += 1 increment() increment() print(count)
- 2 (Correct answer)
- 0
- 1
- Error
Correct answer: 2
global count lets increment() modify the module-level variable, so two calls produce 2.
Question 5: Which of the following is a valid use of the global keyword?
- global x; x = 5 (Correct answer)
- global x = 5
- x = global 5
- def global x(): pass
Correct 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.
Question 6: What is the output of the code below? def outer(): y = 100 def inner(): print(y) inner() outer()
- 100 (Correct answer)
- None
- Error
- 0
Correct answer: 100
inner() reads y from the enclosing scope of outer() via the LEGB rule without any keyword needed.
Question 7: Which of the following names is in Python's built-in scope?
- len (Correct answer)
- x
- count
- result
Correct answer: len
len is a built-in function provided by Python; the others are user-defined names.
What will the following code print?
x = 10
def foo():
x = 20
foo()
print(x)