I am new to python, I have written the following code but it will not reduce the score if B is entered, it increases the score by 1 if How, Hi etc are entered but not it 8 is entered and does not reduce the score if B is entered. Can anyone help.
grid=[8,"B","How", "Hi", "Hey", "How are you doing", "How's it going", "How", "Hello"]
def Play():
count=0
score=0
while (count<11):
I=input("Enter your guess")
if I in grid:
score+=1
print("Your score is:", score)
elif I in grid == "B":
score=0
print("Your score is:",score)
else:
print("I don't understand")
count+=1
1 Answer 1
input() stores input as a string. Therefore, if the user enters 8, it will be stored as "8". "8" is not the same as 8, so if I in grid will evaluate to False. To solve this, you can change 8 to "8" in the list, or add elif I == "8":
elif I in grid == "B": will never evaluate as true. This is because you are checking (I in grid) == ("B"). I in grid will in always be True or False, so you are comparing "B" with a boolean, which is always False.
An easier way to accomplish this is to change 8 to "8" in `grid:
grid=["8","B","How", "Hi", "Hey", "How are you doing", "How's it going", "How", "Hello"]
And check if I == "B" in the first if statement:
if I in grid:
if I == "B":
score=0
else:
score+=1
print("Your score is:",score)
else:
print("I don't understand")
1 Comment
if I in grid: is True even for "B" so elif I in grid == "B": is never even evaluated anyway in the OP's approach since it breaks out at the first True evaluation.
elif I in grid == "B":doesn't make sense. Take B out of grid and put it in a different list. Otherwise you needelif I in grid and I == 'B':or something similar, which is counter-intuitive as a setup.I in gridreturns abool. You're asking "If I is in grid..." (which returnsTrueorFalse) "is equal to the letter B, do this".TrueandFalsewon't be equal to the letter B.