Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my if statement return false when using 'and not'?

I am trying to make a hangman game in python for practice(I’m pretty new to coding and a total newbie with python) When i try to check if a ‘chosenLetter’ is in ‘randomWord’ and not in the ‘correctLettersUsed’, it simply decides it is in there, even though it is not. When i loop through the while loop the first time, it does work as intended, but as soon as there is a letter in ‘correctLettersUsed’ and loop through it again, it does not.

#get random word from list
randomWord = wordList[random.randint(0, len(wordList))]

#counters and correct letters used
winAmount = len(randomWord) -1
correctLettersUsed = []
pointCounter = 0
wrongGuesses = 0

#loops until win conditions are met
while len(correctLettersUsed) != winAmount:

    #print for testing
    print(randomWord)

    chosenLetter = input("Pick a letter: ")

    #checks if the chosen letter is in the random word and not in the used letters
    if chosenLetter in randomWord and not correctLettersUsed:
        pointCounter += 1
        print("Correct!")
        correctLettersUsed.append(chosenLetter)
        print("Correct letters: " + str(correctLettersUsed))
    else:
        wrongGuesses += 1
        print("Incorrect. " + "You have " + str(6 - wrongGuesses) + " guesses left.")

I expect the if statement to be true. I have tried completely removing the ‘and not correctLettersUsed’ and then it works as expected. However, you could just use the same letter over and over again to win. All i can think of is that ‘and not’ just checks if there is anything inside of ‘correctLettersUsed’ and if this is the case, that would be true and the if statement would return false, i am not sure how to fix it. I have also tried using the vscode debugging tool but i really can’t figure it out.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The logic should be

if chosenLetter in randomWord and chosenLetter not in correctLettersUsed:

otherwise it is interpeted as

if (chosenLetter in randomWord) and (not correctLettersUsed):

where any truthy (i.e. non-empty) list will evaluate to True

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading