Bird
0
0

Given the following code snippet for an order state machine, what will be the output after calling cancel() twice?

medium📝 Analysis Q13 of 15
LLD - Design — Online Shopping Cart

Given the following code snippet for an order state machine, what will be the output after calling cancel() twice?

class OrderStateMachine:
    def __init__(self):
        self.state = 'Pending'

    def cancel(self):
        if self.state in ['Pending', 'Shipped']:
            self.state = 'Cancelled'
        else:
            print('Cannot cancel from', self.state)

order = OrderStateMachine()
order.cancel()
order.cancel()
print(order.state)
ACancelled
BPending
CCannot cancel from Cancelled\nCancelled
DError
Step-by-Step Solution
Solution:
  1. Step 1: Trace first cancel call

    Initial state is 'Pending', so state changes to 'Cancelled'.
  2. Step 2: Trace second cancel call

    State is now 'Cancelled', so print message 'Cannot cancel from Cancelled' and state stays 'Cancelled'.
  3. Final Answer:

    Cannot cancel from Cancelled\nCancelled -> Option C
  4. Quick Check:

    Second cancel prints message, state remains Cancelled [OK]
Quick Trick: Check state before transition; print if invalid [OK]
Common Mistakes:
  • Assuming second cancel changes state again
  • Ignoring printed message
  • Expecting error instead of print

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes