'''''我正在编写“ Hangman游戏”的代码。但是它正在打印“正确!”两次而没有得到原因...请告诉问题出在哪里 '''
import random
def rand_word():
fp=open("30.txt","r")
list=fp.readlines()
random_word=random.choice(list)
return random_word
fp.close()
def game(list):
done=len(list)
correct=0
while correct!=done:
letter=input(("Guess a letter: "))
for i in range(done):
if letter==list[i]:
print("Correct!") #this line is unexpected being printed two times sometimes
correct+=1
print("The word was {}".format(str(list)))
if __name__=="__main__":
random_word=rand_word()
list=list(random_word.lower())
list.remove(list[len(list)-1])
print(list)
print("Welcome to Hangman Game!!")
game(list)
答案 0 :(得分:1)
这是在您出现2次字母的情况下。一种快速的解决方法是添加一个标记,以查看是否已经找到该字母,例如:
while correct!=done:
letter=input(("Guess a letter: "))
found = False
for i in range(done):
if letter==list[i]:
if not found:
print("Correct!") #this line is unexpected being printed two times sometimes
found = True
correct+=1
答案 1 :(得分:0)
我猜单词中的字母是两次,因为random_word.lower()可能会产生带有重复字母的单词。如果您不希望这样做,只需在print语句之后添加一个break语句,以在单击后停止for循环。