gpt4 book ai didi

python - 为什么有时会打印 "Correct!"两次并且不接受输入?

转载 作者:行者123 更新时间:2023-12-01 09:15:33 24 4
gpt4 key购买 nike

'''我正在编写“刽子手游戏”的代码。但它打印的是“正确!”两次了还是不明白为什么...请告诉问题出在哪里'''

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)

最佳答案

当某个字母出现两次时就会发生这种情况。一个快速解决方法是添加一个标志来查看您是否已经找到该信件,如下所示:

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

关于python - 为什么有时会打印 "Correct!"两次并且不接受输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51308741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com