Functions & Scope · Question 10 · Medium
The hit function tries to increase a module-level counter without declaring it global. What is the result of running this code?
count = 0
def hit():
count += 1
return count
print(hit())
- 1
- 0
- UnboundLocalError
- NameError
Answer and explanation
Answer: C. UnboundLocalError
Explanation: Because count is assigned inside hit, Python treats it as a local variable for the whole function. count += 1 then tries to read that local before it has a value, which raises UnboundLocalError.
Previous: A function receives keyword arguments through **info. What does sorted(info)… · Next: This recursive function steps down by 2 on every call. What value is printed…
Practise functions & scope
Try a fresh set of functions & scope questions with an explanation after every answer, free and without signing up: Functions & Scope practice. Or sit a full placement mock test.
More functions & scope questions
- A function is defined as def book(src, dst, seats=1). Which of these calls is…
- The tag function uses a dictionary as a default parameter value. What do the…
- A function receives keyword arguments through **info. What does sorted(info)…
- This recursive function steps down by 2 on every call. What value is printed…
- A function is passed to another function as an argument. What does twice print…
- Two counters are built from the same closure factory. What does the last line…
- When Python looks up a name used inside a function, in which order does it…
- A function signature mixes normal parameters, *rest and a keyword-only…
- The enclosing variable x is reassigned after the inner function is defined but…
- A default parameter value refers to a module-level variable that is changed…
More python practice
Comprehensions & Generators · Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets
LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge