nerdexam
Python_Institute

PCEP-30-02 · Question #194

What is the expected output of the following code? people = {} def add_person(index): if index in people: people[index] += 1 else: people[index] = 1 add_person('Peter') add_person('Paul')…

The correct answer is D. 1. There appears to be an error in the stated correct answer. Tracing through the properly-indented version of this code, add_person('Peter') creates people['Peter'] = 1, then add_person('Paul') creates people['Paul'] = 1, and the second add_person('Peter') finds 'Peter' already…

Question

What is the expected output of the following code? people = {} def add_person(index): if index in people: people[index] += 1 else: people[index] = 1 add_person('Peter') add_person('Paul') add_person('Peter') print(len(people))

Options

  • AThe code is erroneous.
  • B2
  • C3
  • D1

How the community answered

(30 responses)
  • A
    10% (3)
  • B
    7% (2)
  • C
    3% (1)
  • D
    80% (24)

Explanation

There appears to be an error in the stated correct answer. Tracing through the properly-indented version of this code, add_person('Peter') creates people['Peter'] = 1, then add_person('Paul') creates people['Paul'] = 1, and the second add_person('Peter') finds 'Peter' already in the dict and increments its value to 2. The dict ends up as {'Peter': 2, 'Paul': 1} - two distinct keys - so len(people) prints 2, making B the actual correct answer.

Why the distractors fail: A is wrong because the code (when properly indented) is valid Python - the function correctly modifies the global people dict without needing a global declaration, since subscript assignment (people[index] = 1) modifies the existing object rather than rebinding the name. C (3) would be wrong because len() counts unique keys, not total calls - 'Peter' is called twice but only occupies one slot. D (1) would only be correct if the function were called once, or if somehow only one unique name was ever added.

Memory tip: Think of a Python dict as a tally board - len() counts the number of labels on the board, not the total tally marks. Adding the same name twice updates its count but doesn't add a new label.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice