0
0
Pythonprogramming~10 mins

Why context managers are needed in Python - Test Your Understanding

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

Complete the code to open a file for reading.

Python
with open('file.txt', [1]) as f:
    content = f.read()
Drag options to blanks, or click blank then click option'
A'r'
B'x'
C'a'
D'w'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' instead of 'r' which overwrites the file.
Forgetting to specify mode, which defaults to 'r' but is better to be explicit.
2fill in blank
medium

Complete the code to ensure the file is closed automatically after reading.

Python
with open('file.txt', 'r') as [1]:
    data = [1].read()
Drag options to blanks, or click blank then click option'
Aopen
Bfile
Cf
Dread
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'open' which is a function, not a variable.
Using 'read' which is a method, not a variable.
3fill in blank
hard

Fix the error in the code to properly handle file closing.

Python
f = open('file.txt', 'r')
content = f.read()
f.[1]()
Drag options to blanks, or click blank then click option'
Awrite
Bopen
Cread
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to close the file causing resource leaks.
Calling 'open()' again instead of 'close()'.
4fill in blank
hard

Fill both blanks to create a dictionary of word lengths only for words longer than 3 letters.

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 '>' causing wrong filtering.
Using 'word' instead of 'len(word)' for values.
5fill in blank
hard

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

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()' for keys.
Using '<' instead of '>' for filtering.