0

This is a snippet of my code, I'm trying to make a scrabble type game but for some reason this if statement isn't working. The file I'm opening is a list of 238,000 words, the English dictionary, and tempword is predefined by an input which is passed over to this function. So here I'm trying to have the tempword compared to every word in the file, but when it runs through it doesn't add to the tally even though I know that word is in the list. Any thoughts?

def checkvalidword(tempword):
    tally = 0
    file = open("words.txt")
    for x in file:
        if x == tempword:
            tally+=1
            print("Added to the tally")
martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

1

Because you are reading lines from the file each line ends with '\n'

Try doing this instread.

def checkvalidword(tempword):
tally = 0
file = open("words.txt")
for x in file:
    if x.strip() == tempword:
        tally+=1
        print("Added to the tally")

Notice the x.strip()

Vlad
  • 9,180
  • 5
  • 48
  • 67
0

In order to compare the values, you should be using .strip() with if as:

if x.strip() == 'abc':

Because at the end of each line, there is a new line character \n present. You may verify it by printing the repr value of x as:

print repr(x)

You will see something like:

'abc\n'

It is even better to use file.readlines() as it splits the content of file based on \n. Hence you won't have to explicitly strip the new line character.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126