TypeError:'in <string>' 左侧操作数需要字符串,而不是列表
我正在为我的GCSE计算机项目制作一个猜单词游戏(也叫“吊死鬼”)。我遇到了一个错误,怎么也解决不了。
这是我写的全部代码:
import random
#Creates a tuple with words in
WORDS = ("church","smelly","chicks")
#This picks a word randomly
word = random.choice(WORDS)
print("The word is", len(word), "letters long.")
#This is the game
for i in range(1):
letter1 = input ("Guess a letter:")
if letter1 in word:
print("Correct. This letter is in the word")
else:
print("Incorrect. This letter is not in the word.")
for i in range(1):
letter2 = input ("Guess a letter:")
if letter2 in word:
print("Correct. This letter is in the word")
else:
print("Incorrect. This letter is not in the word.")
for i in range(1):
letter3 = input ("Guess a letter:")
if letter3 in word:
print("Correct. This letter is in the word")
else:
print("Incorrect. This letter is not in the word.")
for i in range(1):
letter4 = input ("Guess a letter:")
if letter4 in word:
print("Correct. This letter is in the word")
else:
print("Incorrect. This letter is not in the word.")
for i in range(1):
letter5 = input ("Guess a letter:")
if letter5 in word:
print("Correct. This letter is in the word")
else:
print("Incorrect. This letter is not in the word.")
for i in range(1):
letter6 = input ("Guess a letter:")
if letter6 in word:
print("Correct. This letter is in the word")
else:
print("Incorrect. This letter is not in the word.")
all_letters = [letter1, letter2, letter3, letter4, letter5, letter6]
# Conditions for winning/losing
if all_letters in word:
print("Well done, you got it.")
else:
print("Sorry, You are the loser.")
当我运行程序时,出现了这个错误:
TypeError: 'in <string>' requires string as left operand, not list
我不知道该怎么修复这个错误,能不能请大家帮帮我?
另外,如果可以的话,能给我一些建议,告诉我哪里可以改进代码的某些部分吗?
*这是我第一次提问,如果我说得有点多,请多包涵。
1 个回答
0
你应该这样做:
if all(i in word for i in all_letters):
print("Well done, you got it.")
else:
print("Sorry, You are the loser.")
这样做的话,只有当所有字母都在单词里时,才会打印出 '干得好,你做到了.'
这个信息。这里用了一个叫 all
的内置函数。