Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q13 of Q15
Python - Context Managers
What will be the output of this code?
with open('test.txt', 'w') as f:
    f.write('Hello')
print(f.closed)
AError: f is not defined
BFalse
CHello
DTrue
Step-by-Step Solution
Solution:
  1. Step 1: Understand the with block effect

    The file is opened and written inside the with block, which automatically closes the file after the block ends.
  2. Step 2: Check the f.closed property after block

    After the block, the variable f is out of scope and not defined, so accessing f.closed raises a NameError.
  3. Final Answer:

    Error: f is not defined -> Option A
  4. Quick Check:

    Variable f is local to with block, so f.closed access outside causes error [OK]
Quick Trick: f is only defined inside with block; outside it is undefined [OK]
Common Mistakes:
MISTAKES
  • Thinking file stays open after with block
  • Expecting file content as output
  • Assuming f is defined outside with

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes