231k views
5 votes
Consider the following Python program. fin = open('words.txt') for line in fin: word = line.strip() print(word) What is word?

a. A file object
b. A list of characters
c. A list of words
d. A string that may have a newline
e. A string with no newline

1 Answer

2 votes

Answer:

(c) A list of words

Step-by-step explanation:

First let's format the code properly

fin = open('words.txt')

for line in fin:

word = line.strip()

print(word)

Second, let's explain each line of the code

Line 1:

The open() function is a built-in function that takes in, as argument, the name of a file, and returns a file object that can be used to read the file.

In this case, the name of the file is words.txt. Therefore, the variable fin is a file object which contains the content of the file - words.txt

Line 2:

The for loop is used to read in each line of the content of the file object (fin).

Line 3:

Each line of the contents is stripped to remove any trailing and leading white spaces by calling on the strip() function. The result of the strip is stored in the variable word.

Line 4:

The content of word at each of the cycles of the loop is printed to the console.

Therefore, the overall output of the program is a list of words where each word represents a line in the target file (words.txt)

User Michael Covelli
by
4.9k points