Anh Hoang Anh Hoang - 2 months ago 6
Python Question

Function works correctly only the first time it is called

I have the following function, the second function

count_forbid(a)
can only work 1 time. In this example it count the right value of the word that do not contain letter
'c'
, but for
y
it return zero. So it means the code can only do right first time and for all other time it return zero:

import string
fin = open('words.txt')
def forbid_or_not(word,forb):
for letter in word:
if letter in forb:
return False
return True

def count_forbid(a):
count = 0
for line in fin:
word1 = line.strip()
if forbid_or_not(word1,a):
count += 1
return count

x = count_forbid('c')
y = count_forbid('d')

Answer

After you iterate through the file with:

    for line in fin:

it is going to reach the end and trying to re-iterate will have no effect.

Either change the function to use a context manager that re-opens the file when the function is called:

def count_forbid(a):
    count = 0
    with open('words.txt') as fin:  # closes the file automatically
        for line in fin:
            word1 = line.strip()
            if forbid_or_not(word1,a):
                count += 1
    return count

which is the preferred way of opening files in python.

Or, add fin.seek(0) in between your calls in order to get the file to point to the beginning:

x = count_forbid('c')
fin.seek(0)
y = count_forbid('d')