0

Doing this exercise from ThinkPython and wanting to do a little extra, trying to modify the exercise function (avoid) to prompt the user repeatedly and perform the calculation to find how many words in a text file (fin) contain the user inputted letters (avoidprompt). It works the first time but after it prompts the user for input again it always returns an answer of 0 words.

Feel like the most likely issue is I'm misunderstanding how to use the while loop in this context since it works the first time but doesn't after that. Is there a better way?

fin = open('[location of text file here]')
line = fin.readline()
word = line.strip()

def avoid(word, forbidden):
    for letter in word:
        if letter in forbidden:
            return False
    return True

def avoidprompt():
    while(True):
        n = 0
        forbidden = input('gimmie some letters n Ill tell u how many words have em. \n')
        for line in fin:
            if avoid(line, forbidden) == False:
                n = n+1
        print('\n There are ' + str(n) + " words with those letters. \n")
Rob Duffy
  • 3
  • 2

2 Answers2

2

When you open a file and do for line in file, you've consumed the entire file.

There are two easy solutions:

1) Go back to the start of the file in each iteration of your while(True) loop, by doing fin.seek(0)

2) Just store the file contents in a list, by replacing the first line of your script with fin = open('file.txt').readlines()

happydave
  • 7,127
  • 1
  • 26
  • 25
0

I believe you need to do something along these lines:

def avoidprompt():
    while(True):
        n = 0
        fin.seek(0)
        forbidden = input('gimmie some letters n Ill tell u how many words have em. \n')
        for line in fin:
            if avoid(line, forbidden) == False:
                n = n+1
        print('\n There are ' + str(n) + " words with those letters. \n")

Seek sets your pointer back to a specific line in an open file and since you aleady iterated through the file once, your cursor needs to be brought back to the top of the file in order to reread words

You can see this other stack overflow for more details here

Hope this helps! You used the loop just fine

Scott.F
  • 57
  • 1
  • 11