Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q13 of 15
Python - Context Managers
What will be the output of this code?
class Resource:
    def __enter__(self):
        print('Enter')
        return 'resource'
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Exit')

with Resource() as r:
    print('Using', r)
AUsing resource\nEnter\nExit
BUsing resource\nExit\nEnter
CEnter\nExit\nUsing resource
DEnter\nUsing resource\nExit
Step-by-Step Solution
Solution:
  1. Step 1: Understand the order of with execution

    The __enter__ method runs first, printing 'Enter'. Then the block runs, printing 'Using resource'. Finally, __exit__ runs, printing 'Exit'.
  2. Step 2: Match output order with options

    Enter\nUsing resource\nExit matches the sequence: Enter, Using resource, Exit.
  3. Final Answer:

    Enter Using resource Exit -> Option D
  4. Quick Check:

    __enter__ -> block -> __exit__ = B [OK]
Quick Trick: Remember: enter prints first, then block, then exit prints [OK]
Common Mistakes:
  • Assuming block runs before __enter__
  • Mixing order of print statements
  • Ignoring __exit__ call after block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes