Python: Can someone explain me this code, line by line def fileCount(fileName, s
ID: 3684747 • Letter: P
Question
Python:
Can someone explain me this code, line by line
def fileCount(fileName, s):
inF = open(fileName)
count = 0
content = inF.read()
for thing in content:
if s in thing:
count += 1
inF.close()
return count
w = open('seuss.txt', 'w')
w.write('You are on your own' + ' ')
w.write('and you know what you know' + ' ')
w.close()
print(fileCount('seuss.txt', 'you')) #I know the answer is '0' but, I thought it is '1' ,PLEASE EXPLAIN THANK YOU Sorry for the indentation but, chegg does not allow indentation
Explanation / Answer
content = inF.read() # This command read the whole file as a string and save it in content,
for thing in content: # Using this line, we are iterating each character in the string
The answer we got is 0, because no character match with the argument s.
Let us understand with an example,
content of suess.txt => I am the King.
content = inF.read() // after this command content = I am the king.
for thing in content:
thing = I for 1st entrance in the loop
thing = ' ' for 2nd entrance in the loop
thing = a for 3rd entrance in the loop
thing = m for 4th entrance in the loop
Since, we are dealing with a character in the loop and comparing it with 'you', so there will no match and the answer is 0.
we can update the script (read line in file one by one instead of reading it whole) for desire result
def fileCount(fileName, s):
inF = open(fileName)
count = 0
for line in inF:
if s in thing:
count += 1
inF.close()
return count
w = open('seuss.txt', 'w')
w.write('You are on your own' + ' ')
w.write('and you know what you know' + ' ')
w.close()
print(fileCount('seuss.txt', 'you'))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.