Practice Quiz 5 (Ch 9–10)¶
Name: ___________________________________
This work complies with the JMU Honor Code.
I have neither given nor received unauthorized assistance.
I will not discuss the quiz contents with anyone who has not taken the quiz.
Initials: ____________
Question 1 (3 pts)¶
When opening a file, which modes can be used to write to a file?
Circle all that apply:
|
The with statement, when used to open a file, does which of the following?
Circle one answer:
|
Question 2 (3 pts)¶
Given the string:
words = "This is a series of words"
Write a slice operation (Ex: words[1:2]
) for each of the following:
Desired Result | Slice Operation |
---|---|
"This" | words[:4] or words[0:4] |
"series" | words[10:16] or words[-15:-9] |
"words" | words[-5:] or words[20:25] |
Question 3 (2 pts)¶
Given the contents of file.txt
:
One
Red
Two
Blue
Three
Green
What does the following code print?
myfile = open("file.txt")
contents = myfile.readlines()
output = ""
for line in contents:
if line.startswith("T"):
output += line
print(output)
Two
Three
# 1 pt for correct words, 1 pt for separate lines
Question 4 (3 pts)¶
What are the contents of the file out.txt
after running this code?
myfile = open("out.txt", "w")
for i in range(1, 20):
if i % 4 == 0:
myfile.write(str(i))
myfile.write(",")
myfile.close()
4,8,12,16, # 1 pt for numbers, 1 pt no spaces, 1 pt no newlines
Question 5 (6 pts)¶
Hint: You can write this function in four lines. Use string methods; don't reinvent the wheel.
def analyze(text): """Count the number of chars, words, and lines. The number of chars must not include any spaces. Ex: "F = ma" has 4 chars. A word is any text separated by spaces or newlines. Ex: "Yo!\nF = ma" has 4 words ("Yo!", "F", "=", "ma"). Lines are separated by newline characters. The last line does not have to end with a newline character. Ex: "Line 1\nLine 2\n" has 2 lines (not 3). Ex: "Line 1\nLine 2" also has 2 lines. Args: text (str): The document to analyze. Returns: tuple: three integers representing the number of chars, words, and lines. """
num_chars = len(text.replace(" ", "")) # 2 pts for chars num_words = len(text.split()) # 1 pt for words num_lines = len(text.splitlines()) # 2 pts for lines return num_chars, num_words, num_lines # 1 pt for return
Question 6 (8 pts)¶
def write_words(filename, sentence): """Write each word of a sentence to a separate line of a file. For example, write_words("test2.txt", "Practice makes progress!") would create a file named test2.txt with the following contents: Practice makes progress! You may assume that each word is separated by a space. Do not worry about punctuation. Args: filename (str): Name of output file. sentence (str): The words to separate. """
with open(filename, "w") as file: # 1 pt for open + 1 pt for close for word in sentence.split(): # 2 pts for loop + 1 pt for split file.write(word + "\n") # 2 pts for write + 1 pt for "\n"