Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to open a file named 'data.txt' for reading.
Python
with open([1], 'r') as file: content = file.read()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong file name.
Forgetting to put quotes around the file name.
✗ Incorrect
The file name 'data.txt' is the correct file to open for reading as per the instruction.
2fill in blank
mediumComplete the code to open two files 'input.txt' and 'output.txt' safely using a single with statement.
Python
with open('input.txt', 'r') as infile, [1] as outfile: data = infile.read() outfile.write(data)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Opening the output file in read mode instead of write mode.
Using the wrong file name.
✗ Incorrect
To write data to 'output.txt', it must be opened in write mode 'w'.
3fill in blank
hardFix the error in the code to correctly open and read from two files using nested with statements.
Python
with open('file1.txt', 'r') as f1: with [1] as f2: data1 = f1.read() data2 = f2.read()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Opening the second file in write mode.
Using the wrong file name for the second file.
✗ Incorrect
The second file should be opened in read mode 'r' with the correct file name 'file2.txt'.
4fill in blank
hardFill both blanks to create a dictionary with word lengths only for words longer than 4 characters.
Python
words = ['apple', 'bat', 'carrot', 'dog'] lengths = {word: [1] for word in words if len(word) [2] 4 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself instead of its length.
Using '<' instead of '>' in the condition.
✗ Incorrect
We want the length of each word (len(word)) and only words longer than 4 characters (len(word) > 4).
5fill in blank
hardFill all three blanks to create a dictionary with uppercase keys and values only for items with positive values.
Python
data = {'a': 1, 'b': -2, 'c': 3}
result = { [1]: [2] for k, v in data.items() if v [3] 0 } Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using original keys instead of uppercase.
Using '<' instead of '>' in the condition.
Using k instead of v for values.
✗ Incorrect
Keys are converted to uppercase (k.upper()), values are kept as v, and only positive values (v > 0) are included.