Python如果答案正确,如何显示祝贺信息?

0 投票
1 回答
586 浏览
提问于 2025-04-18 02:49

我正在尝试做一个记忆单词游戏,程序会读取一个包含10个单词的文本文件。程序会从文件中读取这些单词,然后创建一个包含9个单词的列表,最后一个单词(第10个)会被移除。接着,这些单词会被随机打乱,然后再显示出来,同时会有第二个列表,里面也是这些单词,但顺序也是随机的,移除的第一个单词会替换掉最后一个单词(被移除/替换)——希望这样能解释清楚。

我在用户猜对答案时反馈正确响应方面遇到了问题(其他部分似乎都正常工作)。

import time
from random import shuffle

file =open('Words.txt', 'r')
word_list = file.readlines()

word_list [0:9]
shuffle(word_list)
extra_word=(word_list.pop())

 print (extra_word)#substitute word for 2nd question (delete this line)
 print '...............'

 print (word_list)

print ('wait and now see the new list')
time.sleep(3)
print ('new lists')

word_list [0:9]
shuffle(word_list)
newExtra_word=(word_list.pop())

 print (newExtra_word)#replace word for 1st question (delete this line)    

 word_list.insert(9,extra_word)# replace word 

 print (word_list)

上面的代码运行得很好(符合我的需求)。但是下面这部分:

#ALLOW FOR 3 GUESSES
user_answer = (raw_input('can you guess the replaced word: ')).lower()
count = 0
while count <=1:
     if user_answer == newExtra_word:
          print("well done")
          break
     else:
          user_answer = (raw_input('please guess again: ')).lower()
          count+=1
else:
     print ('Fail, the answer is' +  extra_word)

这段代码允许用户猜三次,但不接受被移除的列表项。有没有人知道这是为什么呢?

1 个回答

2

好吧,因为你上面的代码并没有按照你想要的方式工作。

file = open('Words.txt', 'r')
word_list = file.readlines()
# you should do file.close() here

word_list[0:9]

最后一行其实没有做任何事情。它返回了word_list中的前10个元素,但你并没有把它们赋值给任何东西,所以这基本上是个无效操作。你应该这样做:

word_list = word_list[0:9] # now you've removed the extras.

其实先打乱顺序可能更好,这样你就能得到真正随机的10个元素。为什么是10个?为什么要限制数据的数量?哦,好吧……

# skipping down a good ways
word_list.insert(9, extra_word) # replace word

我们为什么要这样做?我其实不太明白这个操作的目的是什么。

关于允许三次猜测:

count = 0
while count < 3:
    user_answer = raw_input("Can you guess the replaced word: ").lower()
    count += 1
    if user_answer == newExtra_word:
        print("well done")
        break
else:
    print("Sorry, the answer is " + extra_word)

等等,你注意到了吗?你在检查用户输入是否和newExtra_word匹配,然后你把正确答案报告为extra_word。你确定你的代码逻辑是对的吗?

听起来你想做的是这个:

with open("Words.txt") as inf:
    word_list = [next(inf).strip().lower() for _ in range(11)]
    # pull the first _11_ lines from Words.txt, because we're
    # going to pop one of them.

word_going_in = word_list.pop()
random.shuffle(word_list)

print ' '.join(word_list)

random.shuffle(word_list)
word_coming_out = word_list.pop()
# I could do word_list.pop(random.randint(0,9)) but this
# maintains your implementation

word_list.append(word_going_in)
random.shuffle(word_list)

count = 0
while count < 3:
    user_input = raw_input("Which word got replaced? ").lower()
    count += 1
    if user_input == word_coming_out:
        print "Well done"
        break
else:
    print "You lose"

撰写回答