0
0
Pythonprogramming~20 mins

With statement execution flow in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
With Statement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this with statement?
Consider this Python code using a custom context manager class. What will it print when run?
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('Inside with:', res)
AEnter\nInside with: resource\nExit
BInside with: resource\nEnter\nExit
CEnter\nExit\nInside with: resource
DExit\nEnter\nInside with: resource
Attempts:
2 left
💡 Hint
Remember, __enter__ runs before the block, __exit__ runs after.
Predict Output
intermediate
2:00remaining
What happens if an exception occurs inside the with block?
Look at this code. What will be printed when the exception is raised inside the with block?
Python
class CM:
    def __enter__(self):
        print('Start')
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('End')
        print('Exception:', exc_type.__name__ if exc_type else 'None')

with CM():
    print('Inside')
    raise ValueError('Oops')
AStart\nInside\nException: ValueError\nEnd
BStart\nEnd\nInside\nException: ValueError
CStart\nInside\nEnd\nException: ValueError
DStart\nInside\nEnd\nException: None
Attempts:
2 left
💡 Hint
The __exit__ method receives exception info if an error happens.
Predict Output
advanced
2:00remaining
What is the output when __exit__ suppresses the exception?
This context manager suppresses exceptions by returning True from __exit__. What will be printed?
Python
class SuppressError:
    def __enter__(self):
        print('Begin')
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Cleanup')
        return True

with SuppressError():
    print('Running')
    raise RuntimeError('Fail')
print('After with')
ABegin\nRunning\nCleanup\nAfter with
BBegin\nRunning\nAfter with
CBegin\nCleanup\nRunning\nAfter with
DBegin\nRunning\nCleanup
Attempts:
2 left
💡 Hint
Returning True from __exit__ stops the exception from propagating.
Predict Output
advanced
2:00remaining
What is the output of nested with statements with context managers?
Given these two context managers used in nested with statements, what will be printed?
Python
class CM1:
    def __enter__(self):
        print('Enter CM1')
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Exit CM1')

class CM2:
    def __enter__(self):
        print('Enter CM2')
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Exit CM2')

with CM1():
    with CM2():
        print('Inside both')
AEnter CM2\nEnter CM1\nInside both\nExit CM1\nExit CM2
BEnter CM1\nEnter CM2\nInside both\nExit CM2\nExit CM1
CEnter CM1\nEnter CM2\nExit CM2\nInside both\nExit CM1
DEnter CM2\nEnter CM1\nExit CM1\nInside both\nExit CM2
Attempts:
2 left
💡 Hint
The inner with runs fully before the outer with exits.
🧠 Conceptual
expert
3:00remaining
What is the value of variable 'result' after this with statement?
Analyze this code. What will be the value of 'result' after the with block finishes?
Python
class CM:
    def __enter__(self):
        return 10
    def __exit__(self, exc_type, exc_val, exc_tb):
        return True

result = None
with CM() as val:
    result = val + 5
    raise Exception('Error')
print('Done')
A10
BNone
CException is raised, so no value assigned
D15
Attempts:
2 left
💡 Hint
Even if an exception is raised, if __exit__ returns True, the block completes and variables keep their values.