Bird
Raised Fist0

What will be the output of this code snippet?

medium📝 Analysis Q5 of Q15
LLD - Design — Online Shopping Cart
What will be the output of this code snippet?
inventory = {'pen': 20, 'notebook': 15}
item = 'pen'
print(inventory.get(item, 0))
print(inventory.get('pencil', 0))
A0\n15
B20\n0
C20\n15
DError
Step-by-Step Solution
Solution:
  1. Step 1: Understand dictionary get() method

    Returns value for key if exists, else default (0 here).
  2. Step 2: Evaluate get calls

    inventory.get('pen', 0) returns 20; inventory.get('pencil', 0) returns 0.
  3. Final Answer:

    20\n0 -> Option B
  4. Quick Check:

    get() returns value or default = 20 and 0 [OK]
Quick Trick: get() returns default if key missing, else value [OK]
Common Mistakes:
MISTAKES
  • Expecting error for missing key
  • Confusing default value usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes