Program Ignoring If Statement, And Printing True When False
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 m
Solution 1:
if i insecretWord== 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.
Solution 2:
Replace if i in secretWord == False:
with if i not in secretWord
Solution 3:
Wouldnt it be the same just doing:
``
defisWordGuessed(secretWord, lettersGuessed):
ifnot lettersGuessed:
returnFalsefor i in lettersGuessed:
if i notin secretWord:
returnFalsereturnTrue
What your doing is called chained comparisons.
Edit: My bad, too late
BR Daniel
Solution 4:
The other answers explain the error in the code well, but you can simplify your code a bit like this:
defisWordGuessed(secretWord, lettersGuessed):
for i in lettersGuessed or ['_']: # uses ['_'] when lettersGuessed = []ifnot i in secretWord:
returnFalsereturnTrue
You can do also do this with a generator expression and all()
:
defisWordGuessed(secretWord, lettersGuessed):
returnall([i in secretWord for i in lettersGuessed] or [False])
Post a Comment for "Program Ignoring If Statement, And Printing True When False"