0
0
Pythonprogramming~10 mins

With statement execution flow in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to open a file using the with statement.

Python
with open('example.txt', [1]) as file:
    content = file.read()
Drag options to blanks, or click blank then click option'
A'open'
B'write'
C'r'
D'close'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'write' instead of 'r' causes an error when reading.
Using 'open' or 'close' as mode is invalid.
2fill in blank
medium

Complete the code to ensure the file is automatically closed after the with block.

Python
with open('data.txt', 'r') as file:
    data = file.read()
print(file.[1])
Drag options to blanks, or click blank then click option'
Aopen
Bwrite
Cread
Dclosed
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'open' or 'read' instead of 'closed' attribute.
Trying to manually close the file inside the with block.
3fill in blank
hard

Fix the error in the with statement to correctly handle exceptions.

Python
try:
    with open('log.txt', 'r') as file:
        content = file.read()
except [1] as e:
    print('Error:', e)
Drag options to blanks, or click blank then click option'
AFileNotFoundError
BException
CValueError
DIOError
Attempts:
3 left
💡 Hint
Common Mistakes
Catching a general Exception instead of the specific FileNotFoundError.
Using ValueError which is unrelated.
4fill in blank
hard

Fill both blanks to create a context manager that prints messages before and after the block.

Python
class MessageManager:
    def __enter__(self):
        print([1])
    def __exit__(self, exc_type, exc_val, exc_tb):
        print([2])

with MessageManager():
    print('Inside block')
Drag options to blanks, or click blank then click option'
A'Entering block'
B'Exiting block'
C'Start'
D'End'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the messages between __enter__ and __exit__.
Using generic words like 'Start' and 'End' that are less clear.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps file names to their sizes if size is greater than zero.

Python
files = {'a.txt': 100, 'b.txt': 0, 'c.txt': 50}
sizes = [1]: [2] for [3] in files.items() if [2] > 0
Drag options to blanks, or click blank then click option'
Aname
Bsize
Cname, size
Dfiles
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'files' instead of unpacking variables in the loop.
Not filtering sizes greater than zero.