All sample questions / Python
Python Scope, Functions and Closures, what does print(t()) print after def counter()?
Block 2, Scope, Functions and Closures, question 1 of the Python sample
def counter():
n = 0
def tick():
n += 1
return n
return tick
t = counter()
print(t())
What does this print?
Show the answer and why each option is right or wrong
Answer, B. UnboundLocalError
- A. 0
- Assumes the read of n inside tick falls back silently to the enclosing scope while the increment is simply dropped.
- B. UnboundLocalError
- Correct. Without a nonlocal declaration, the assignment n += 1 makes n local to tick, so the read of n on the right hand side happens before that local has any value, raising UnboundLocalError.
- C. 1
- Assumes tick can freely mutate the enclosing n with += the same way nonlocal would allow, without declaring it.
- D. NameError
- Confuses the local variable that is known but unassigned with a name that the interpreter has never seen anywhere in the function.
Augmented assignment like n += 1 both reads and writes n, and the write alone is enough to mark n as a local variable for the whole function. Without a nonlocal statement pointing at the enclosing counter's n, tick's own local n has never been assigned when the read happens, which raises UnboundLocalError instead of quietly falling back to the enclosing scope.
The answer above is what the CPython interpreter printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 600 Python interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 600 Python questions, 9 euros
Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros
Or play the free Python sample, twenty questions in the browser, also as a free PDF.
Did this save you a lookup? Buy me a coffee on Ko-fi.