Challenge - 5 Problems
Context Manager Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of file handling without context manager
What is the output of this code snippet that opens a file, writes to it, but forgets to close it explicitly?
Python
f = open('test.txt', 'w') f.write('Hello') print(f.closed)
Attempts:
2 left
💡 Hint
Check if the file is closed immediately after writing without using a context manager.
✗ Incorrect
The file is opened and written to, but not closed explicitly. The 'closed' attribute is False until the file is closed.
❓ Predict Output
intermediate2:00remaining
Output of file handling with context manager
What will this code print after writing to a file using a context manager?
Python
with open('test.txt', 'w') as f: f.write('Hello') print(f.closed)
Attempts:
2 left
💡 Hint
The 'with' statement automatically closes the file after the block.
✗ Incorrect
Using 'with' ensures the file is closed when the block ends, so 'f.closed' is True.
🧠 Conceptual
advanced2:00remaining
Why context managers are important for resource cleanup
Which of the following best explains why context managers are needed in Python?
Attempts:
2 left
💡 Hint
Think about what happens if an error occurs while working with files or other resources.
✗ Incorrect
Context managers guarantee that resources are cleaned up properly, preventing resource leaks even if exceptions happen.
❓ Predict Output
advanced2:00remaining
Output of custom context manager with __enter__ and __exit__
What will be printed when running this code?
Python
class MyContext: def __enter__(self): print('Enter') return 'resource' def __exit__(self, exc_type, exc_val, exc_tb): print('Exit') with MyContext() as res: print(res)
Attempts:
2 left
💡 Hint
Remember the order: __enter__ runs first, then the block, then __exit__.
✗ Incorrect
The __enter__ method prints 'Enter' and returns 'resource'. The block prints 'resource'. Then __exit__ prints 'Exit'.
🧠 Conceptual
expert2:00remaining
Handling exceptions with context managers
What happens if an exception occurs inside a 'with' block using a context manager that defines __exit__?
Attempts:
2 left
💡 Hint
Think about how context managers help manage errors and cleanup.
✗ Incorrect
When an exception occurs, __exit__ receives the exception info and can clean up resources and decide whether to suppress the exception.