program ignoring if statement, and printing True when False

后端 未结 4 784
心在旅途
心在旅途 2021-01-27 03:15

I am writing a simple program for a homework problem and It seems to be skipping my if statement. I have looked at other questions posed, and the problems there do not seem to b

相关标签:
4条回答
  • 2021-01-27 03:39

    Replace if i in secretWord == False: with if i not in secretWord

    0 讨论(0)
  • 2021-01-27 03:44

    The other answers explain the error in the code well, but you can simplify your code a bit like this:

    def isWordGuessed(secretWord, lettersGuessed):
        for i in lettersGuessed or ['_']: # uses ['_'] when lettersGuessed = []
            if not i in secretWord:
                return False
        return True
    

    You can do also do this with a generator expression and all():

    def isWordGuessed(secretWord, lettersGuessed):
        return all([i in secretWord for i in lettersGuessed] or [False])
    
    0 讨论(0)
  • 2021-01-27 03:52
            if i in secretWord == False:
    

    This doesn't do what you think it does. If you want this path to be taken when i isn't in secretWord, you want

            if i not in secretWord:
    

    What you have does a chained comparison. First, it checks

    i in secretWord
    

    If that's true, it then checks

    secretWord == False
    

    If that's true (which it won't be), it then takes the if path.

    0 讨论(0)
  • 2021-01-27 03:58

    Wouldnt it be the same just doing:

    ``

    def isWordGuessed(secretWord, lettersGuessed):
    
    if not lettersGuessed:
        return False
    for i in lettersGuessed:
        if i not in secretWord:
            return False
    return True
    

    What your doing is called chained comparisons.

    Edit: My bad, too late

    BR Daniel

    0 讨论(0)
提交回复
热议问题