I have a modual(Is that the right term?)called WordPlay which has severl functions for exercises in Chapter 9 of "How to Think Like a (Python) Programmer". Below is my code for Ex9.3.2, which has the user input a string letters and then searches a .txt file(Attachment) for words that do not contain any of the letters in the string. The function returns the number of word that did not contain any of the letters.
fin = open ('E:/words.txt')
def avoid(word,forbid):
###Function to search word for any letter if list forbid. Returns True in no letters in word###
i=0
answer='True'
while i<len(forbid):
if forbid[i] in word:
answer='False'
return answer
else:
i=i+1
return answer
def has_none():
###Function to take a string of letters from the user and search a list of words. The number of words that do not cotain any of the letters will be given###
contain=0
notcontain=0
input=raw_input("Please input a string of letters i.e. jdheu")
for line in fin:
if avoid(line,input)=='True':
notcontain+=1
elif avoid(line,input)=='False':
contain+=1
print str(notcontain) +" out of " + str(contain+notcontain) + " did not contain the letters " + input
The Problem:
The first time I call the function it run correctly but if I call the function again with a different set of letter I get 0 returned regardless of the string(Below is an example). I am sure the problem is that the .txt file needs to be reloaded, but I do not know the best way to do this, or any way really.
>>> from WordPlay import*
>>> has_none()
Please input a string of letters i.e. jdheuou
50582 out of 113809 did not contain the letters ou
>>> has_none()
Please input a string of letters i.e. jdheuo
0 out of 0 did not contain the letters o
>>>
Thanx in advance for the help! Let me know if any thing is unclear, and I apologize if it is.
Lanier