0
0
Pythonprogramming~10 mins

Automatic resource cleanup 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 a context manager.

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

Complete the code to automatically close the file after reading.

Python
with open('data.txt', 'r') as [1]:
    data = file.read()
Drag options to blanks, or click blank then click option'
Afile
Bread
Copen
Df
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'open' or 'read' as variable names causes errors.
Using 'f' is common but here 'file' matches the code below.
3fill in blank
hard

Fix the error in the code to ensure the file is closed automatically.

Python
file = open('log.txt', 'r')
try:
    content = [1].read()
finally:
    file.close()
Drag options to blanks, or click blank then click option'
Afile
Bopen
Cread
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'open.read()' causes an error because open is a function, not the file object.
Using 'read.read()' or 'close.read()' are invalid.
4fill in blank
hard

Fill both blanks to create a dictionary with word lengths for words longer than 3 characters.

Python
lengths = {word: [1] for word in words if len(word) [2] 3}
Drag options to blanks, or click blank then click option'
Alen(word)
B>
C<
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' filters shorter words.
Using 'word' instead of len(word) gives the word itself, not its length.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase keys and values greater than zero.

Python
result = [1]: [2] for k, v in data.items() if v [3] 0}
Drag options to blanks, or click blank then click option'
Ak.upper()
Bv
C>
Dk
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'k' instead of 'k.upper()' keeps keys as original case.
Using '<' instead of '>' filters values less than zero.
Using 'k' or 'v' incorrectly in keys or values.