Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to open a file named 'output.txt' for writing.
Python
file = open('output.txt', '[1]')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'r' mode which is for reading only.
Using 'a' which appends instead of overwriting.
✗ Incorrect
Use 'w' mode to open a file for writing. It creates the file if it doesn't exist and overwrites if it does.
2fill in blank
mediumComplete the code to write the string 'Hello, world!' to the file.
Python
file.write('[1]')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Missing the comma or exclamation mark.
Using lowercase 'hello' instead of capital 'Hello'.
✗ Incorrect
The string must exactly match 'Hello, world!' including punctuation and capitalization.
3fill in blank
hardFix the error in the code to properly close the file after writing.
Python
file.[1]() Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'closed' which is an attribute, not a method.
Using 'closing' or 'close_file' which are invalid.
✗ Incorrect
The method to close a file is close().
4fill in blank
hardFill both blanks to write 'Python' followed by a newline to the file.
Python
file.write('[1]'[2]'\n')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using ',' which does not concatenate strings.
Putting the newline inside the first blank without concatenation.
✗ Incorrect
Use string concatenation with '+' to add a newline character '\n' after 'Python'.
5fill in blank
hardFill all three blanks to write each word in the list to the file on separate lines.
Python
words = ['apple', 'banana', 'cherry'] for [1] in words: file.write([2] + [3])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'words' as the loop variable which is the list itself.
Forgetting to add the newline character.
✗ Incorrect
Use 'word' as the loop variable and write each word plus a newline '\n' to the file.