Bird
0
0

What will be the output of this code?

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

with Context() as value:
    print(value * 2)
AEnter 20 Exit
B20 Enter Exit
CEnter Exit 20
DExit Enter 20
Step-by-Step Solution
Solution:
  1. Step 1: Follow __enter__ execution

    On entering the with block, __enter__ prints 'Enter' and returns 10, assigned to value.
  2. Step 2: Execute block and __exit__

    The block prints 10 * 2 = 20. After block ends, __exit__ prints 'Exit'.
  3. Final Answer:

    Enter 20 Exit -> Option A
  4. Quick Check:

    Order: __enter__, block, __exit__ [OK]
Quick Trick: Return value from __enter__ is assigned inside with [OK]
Common Mistakes:
  • Printing value before __enter__
  • Mixing order of prints

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes