Functions & Scope · Question 8 · Medium
The tag function uses a dictionary as a default parameter value. What do the three calls print?
def tag(key, seen={}):
seen[key] = seen.get(key, 0) + 1
return seen[key]
print(tag("a"), tag("b"), tag("a"))
- 1 1 1
- 1 2 3
- 1 1 2
- 1 2 2
Answer and explanation
Answer: C. 1 1 2
Explanation: The default dictionary is created once, when the function is defined, and is shared by every call. So the count for "a" survives from the first call and becomes 2 in the third call, while "b" is counted once.
Previous: A function is defined as def book(src, dst, seats=1). Which of these calls is… · Next: A function receives keyword arguments through **info. What does sorted(info)…
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
- The function below collects any number of marks using *marks. What is printed?
- A function assigns to a name that also exists at module level. What does this…
- A function is defined as def book(src, dst, seats=1). Which of these calls is…
- A function receives keyword arguments through **info. What does sorted(info)…
- The hit function tries to increase a module-level counter without declaring it…
- 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…
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