Bird
0
0

What is the issue with the following inventory update code snippet?

medium📝 Analysis Q6 of 15
LLD - Design — Online Shopping Cart
What is the issue with the following inventory update code snippet?
inventory = {'eggs': 12}
inventory['eggs'] -= 4
inventory['cheese'] = inventory['cheese'] + 3
AUsing '+=' operator instead of '=' causes syntax error
BSubtracting from 'eggs' is invalid since quantity cannot decrease
CAccessing 'cheese' key before initialization causes a KeyError
DThe dictionary should use lists instead of integers for quantities
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the code

    The code initializes 'eggs' with 12 units and decreases it by 4, which is valid.
  2. Step 2: Identify the problem

    It then tries to add 3 to 'cheese' without initializing 'cheese' in the dictionary.
  3. Step 3: Understand Python dictionary behavior

    Accessing a non-existent key like 'cheese' with '+' operator raises a KeyError.
  4. Final Answer:

    Accessing 'cheese' key before initialization causes a KeyError -> Option C
  5. Quick Check:

    Check if all keys exist before updating values [OK]
Quick Trick: Always initialize keys before updating values [OK]
Common Mistakes:
  • Assuming keys can be updated without initialization
  • Confusing syntax errors with runtime KeyErrors
  • Believing quantities cannot be decreased

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes