program ignoring if statement, and printing True when False

南笙酒味 提交于 2019-12-09 03:43:44

问题


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 be my problem so I am hoping you can help.

def isWordGuessed(secretWord, lettersGuessed):
if lettersGuessed == []:
    return False
else:
    for i in lettersGuessed:
        if i in secretWord == False:
            return False

        else:
            if i == lettersGuessed[-1]:
                return True

When I place in some print functions to see what it is doing, it completely skips

if i in secretWord == False:

I have placed right above this line

print i in secretWord

and it will print out the correct Boolean, but even when it prints False, it still skips the if statement. I feel like I must be overlooking something pretty basic, but what it is I can't seem to figure out, so any help would be appreciated. Thanks

Edit:

Here is an example of a call to this function with inputs

isWordGuessed('apple',['a','e','i','k','p','r','s'])

回答1:


        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.




回答2:


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




回答3:


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




回答4:


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])


来源:https://stackoverflow.com/questions/19963399/program-ignoring-if-statement-and-printing-true-when-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!