If statement responding negative for no reason

Question:
My if statement is not doing what it is supposed to for no reason that I am aware of. I am simply doing: if answer in dictionaryf. “dictionaryf” is a list that contains every word in the English dictionary. I printed it out and made sure everything was there, and it was all there and exactly how it was supposed to look. “answer” is an input. I printed out answer as well, and it should be matching with an item in dictionaryf. But the if statement somehow says the opposite. I searched my code top to bottom and do not know why it is doing this.
I am a beginner coder, so I might be missing something obvious. Sorry if I am unclear!
Repl link:

if answer in dictionaryf:
  print(f"{answer} is a word!")
  #supposed to do this
else:
  print(f"{answer} is not a word!")
  #somehow does this instead

Again, I am a beginner coder, so it is probably best to check the repl itself in case I missed anything.
Sorry!

with open("Dictionary.txt") as f:
	dictionaryf = []
	for line in f:
		dictionaryf.append(line.strip())

You should have dictionaryf defined outside of this function. EX:

dictionaryf = []
with open("Dictionary.txt") as f:
	for line in f:
		dictionaryf.append(line.strip())
1 Like

I tried that before, it still did the same thing.

Maybe the value of the text you want to match is either case-sensitive or doesn’t match the result?

I printed both, and they seemed fine, I also used .lower() on both and it still did nothing.

1 Like

UPDATE:
I kept testing and for some reason it reacted properly to the word “axe”, but nothing else. After more testing, I found that it worked 50% of the time with any word that started with the letter a. This is really confusing.

1 Like

That sounds like it’s not reading the whole dictionary file then.

1 Like

I printed out dictionaryf and the whole thing was there. Not sure what’s going on, but both variables are all there.

I’ve used this file before and i checked all of the words that ive tested. It’s all there. I think it has something to do with the if statement, because all of the variables are fine, and i’ve done endless debugging to make sure.

It seems like this is indeed the case

Well, in my testing, every time I use a word in the dictionary, it works fine. Your code looks fine.

Edit:

Oh. Yeah I forgot I changed it to use .lower(). lol


Ignoring everything I’ve said:

with open("Dictionary.txt") as f:
    for line in f:
        dictionaryf.append(line.lower().strip())

and

elif answer.lower() in dictionaryf:
1 Like

I checked the list again to make sure, and it’s missing a lot of the words that were originally there. I’m not sure what happened, but when I transferred it over from one of my other projects, it somehow got rid of a lot of words. No idea how that happened. Ill try using a new Dictionary.txt

Well, yeah, but lots of the words are randomly capitalized in the file, try this:

I would like proper nouns to be capitalized, to encourage people to use capitals properly when they play.

That’d make it more confusing, and also impossible if someone’s keyboard happens to be missing shift/caps lock keys.

1 Like

If I am prompted to enter a word with “AT” in reality its asking me for a word that contains “at”.
If i then enter a word that starts with a capital A such as Atari, it will not count because it’s looking specifically for lowercase a and lowercase t for if frfrc not in answer:

This version should work regardless of the capitalization of any letter
import random
import sys
import time

from inputimeout import inputimeout

dictionaryf = []

with open("Dictionary.txt") as f:
  for line in f:
    dictionaryf.append(line.strip().capitalize()) #capitalize each word in the dictionary

debuglist = ['apple','green','red','education']

words = ["Welcome"]
timesUp = False

for typing in words[0]:
  time.sleep(0.07)
  sys.stdout.write(typing)
  sys.stdout.flush()
time.sleep(0.5)
words = [" to..."]

for typing in words[0]:
  time.sleep(0.07)
  sys.stdout.write(typing)
  sys.stdout.flush()
time.sleep(0.5)
print('')

words = [f"WORD BOMB!!!!"]

for typing in words[0]:
  time.sleep(0.07)
  sys.stdout.write(typing)
  sys.stdout.flush()
time.sleep(0.5)
print("")

wordList = []

time.sleep(1)

def word_bomb_game():
  print("nonono")
def game():
  global answer
  global frfrc
  rc = ['at', 'av', 'aw', 'ax', 'ay', 'eb', 'ec', 'ed', 'ef', 'eg', 'eh', 'ej', 'ek', 'el', 'em', 'en', 'ep', 'eq', 'er', 'es', 'et', 'ev', 'ew', 'ex', 'ey', 'ib', 'ic', 'id', 'if', 'ig', 'ih', 'ij', 'ik', 'il', 'im', 'in', 'ip', 'ir', 'is', 'it', 'ob', 'oc', 'od', 'of', 'og', 'oh', 'ok', 'ol', 'om', 'on', 'op', 'or', 'os', 'ot', 'ov', 'ow', 'ox', 'oy', 'ub', 'uc', 'ud', 'uf', 'ug', 'uh', 'uk', 'ul', 'um', 'un', 'up', 'ur', 'us', 'ut', 'uv', 'uw', 'ux', 'uy']
  debugrc = ['ap','ed','re']
  frfrc = random.choice(rc)
  print(f'TYPE A WORD WITH "{frfrc.upper()}"')
  # first, we get user input
  try: 
    answer = ''
    answer = inputimeout(prompt='>', timeout=10)
    answer = str(answer).capitalize() #capitalize the user's input
    print(f'"{answer}"')
    checkAnswer()
  except Exception: 
    print("")
    answer = 'TIMES UP!'
    print(answer) 
    time.sleep(1)
    print("NEXT PLAYER!")
    print("")
    time.sleep(1)
    game()

def checkAnswer():
  global dictionaryf
  global answer
  global frfrc
  if frfrc not in answer.lower(): # check if frfrc is in the all lowercase version of the user's answer
    print('')
    print("WORD DOESN'T MATCH!")
    time.sleep(1)
    print("NEXT PLAYER!")
    time.sleep(1)
    print('')
    game()
  elif answer in wordList:
    print('')
    print('WORD ALREADY SAID!')
    time.sleep(1)
    print("NEXT PLAYER!")
    time.sleep(1)
    print('')
    game()
  elif answer in dictionaryf:
    wordList.append(answer)
    congratsmsg = ['AMAZING', 'WONDERFUL', 'GOOD', 'GREAT']
    cmsg = random.choice(congratsmsg)
    print(f'{cmsg} JOB!')
    time.sleep(1)
    print('NEXT PLAYER!')
    time.sleep(1)
    print('')
    game()
  else:
    print('')
    print("THAT'S NOT A WORD, LOL!")
    time.sleep(1)
    print("NEXT PLAYER!")
    time.sleep(1)
    print('')
    game()


time.sleep(0.5)
print('')
print('type "start" to play')
print('type "settings" to open settings')
print('')
def startinput():
  strt = input('> ')
  if "start" not in strt:
    print(f'Error: Unknown Command: "{strt}"')
    startinput()
  else:
    game()
startinput()

We capitalize all words in the dictionary and then capitalize the user’s answer so they will match, but then we user a lowercase version of the users answer to check if it contains rc, which wouldn’t work if it was capitalized.

image
image

It also would make sense for every word to begin with a capital letter?

Though this does kind of defeat the purpose if you want this.


Sorry I’ve edited the code multiple times here please make sure if you use this you are using the most recent version.

Apologies for the multiple responses @SethMiller2

I believe I understand your intentions better now.

If you do want to specifically require capitalization for proper nouns you can leave your code as it was when it started, except just changeif frfrc not in answer: to if frfrc not in answer.lower():

import random
import sys
import time

from inputimeout import inputimeout

dictionaryf = []

with open("Dictionary.txt") as f:
  for line in f:
    dictionaryf.append(line.strip())

debuglist = ['apple','green','red','education']

words = ["Welcome"]
timesUp = False

for typing in words[0]:
  time.sleep(0.07)
  sys.stdout.write(typing)
  sys.stdout.flush()
time.sleep(0.5)
words = [" to..."]

for typing in words[0]:
  time.sleep(0.07)
  sys.stdout.write(typing)
  sys.stdout.flush()
time.sleep(0.5)
print('')

words = [f"WORD BOMB!!!!"]

for typing in words[0]:
  time.sleep(0.07)
  sys.stdout.write(typing)
  sys.stdout.flush()
time.sleep(0.5)
print("")

wordList = []

time.sleep(1)

def word_bomb_game():
  print("nonono")
def game():
  global answer
  global frfrc
  rc = ['ab', 'ac', 'ad', 'af', 'ag', 'ah', 'aj', 'ak', 'al', 'am', 'an', 'ap', 'aq', 'ar', 'as', 'at', 'av', 'aw', 'ax', 'ay', 'eb', 'ec', 'ed', 'ef', 'eg', 'eh', 'ej', 'ek', 'el', 'em', 'en', 'ep', 'eq', 'er', 'es', 'et', 'ev', 'ew', 'ex', 'ey', 'ib', 'ic', 'id', 'if', 'ig', 'ih', 'ij', 'ik', 'il', 'im', 'in', 'ip', 'ir', 'is', 'it', 'ob', 'oc', 'od', 'of', 'og', 'oh', 'ok', 'ol', 'om', 'on', 'op', 'or', 'os', 'ot', 'ov', 'ow', 'ox', 'oy', 'ub', 'uc', 'ud', 'uf', 'ug', 'uh', 'uk', 'ul', 'um', 'un', 'up', 'ur', 'us', 'ut', 'uv', 'uw', 'ux', 'uy']
  debugrc = ['ap','ed','re']
  frfrc = random.choice(rc)
  print(f'TYPE A WORD WITH "{frfrc.upper()}"')
  # first, we get user input
  try: 
    answer = ''
    answer = inputimeout(prompt='>', timeout=10) 
    answer = str(answer)
    print(f'"{answer}"')
    checkAnswer()
  except Exception: 
    print("")
    answer = 'TIMES UP!'
    print(answer) 
    time.sleep(1)
    print("NEXT PLAYER!")
    print("")
    time.sleep(1)
    game()

def checkAnswer():
  global dictionaryf
  global answer
  global frfrc
  if frfrc not in answer.lower(): #this needs to be lowercase 
    print('')
    print("WORD DOESN'T MATCH!")
    time.sleep(1)
    print("NEXT PLAYER!")
    time.sleep(1)
    print('')
    game()
  elif answer in wordList:
    print('')
    print('WORD ALREADY SAID!')
    time.sleep(1)
    print("NEXT PLAYER!")
    time.sleep(1)
    print('')
    game()
  elif answer in dictionaryf:
    wordList.append(answer)
    congratsmsg = ['AMAZING', 'WONDERFUL', 'GOOD', 'GREAT']
    cmsg = random.choice(congratsmsg)
    print(f'{cmsg} JOB!')
    time.sleep(1)
    print('NEXT PLAYER!')
    time.sleep(1)
    print('')
    game()
  else:
    print('')
    print("THAT'S NOT A WORD, LOL!")
    time.sleep(1)
    print("NEXT PLAYER!")
    time.sleep(1)
    print('')
    game()


time.sleep(0.5)
print('')
print('type "start" to play')
print('type "settings" to open settings')
print('')
def startinput():
  strt = input('> ')
  if "start" not in strt:
    print(f'Error: Unknown Command: "{strt}"')
    startinput()
  else:
    game()
startinput()

The only thing that needs to be changed is if frfrc not in answer: specifically in the case where the two letters it gives you happens to be both the first two letters of the word AND the first letter is capitalized.

In this corrected version, if you do capitalize a word that isn’t a proper noun, it will count as wrong, and if you don’t capitalize a word that is a proper noun it will also count as wrong.

But this will correct the error, where if the two letters you are given, (TYPE A WORD WITH “AT”), which is really “at”, are the first two letters of a proper noun, and thus are capitalized, (like in Atari) , it will still pass if frfrc not in answer.lower():, since we are checking if at is in atari instead of Atari, regardless of how the user typed it in.

I think this is closer to what you want?

1 Like