如果答案是正确的python显示一个做得好的消息?

时间:2014-04-15 15:01:45

标签: python list if-statement

我试图设置一个记忆单词游戏,程序读取10个单词的文本文件。程序读取文件并创建一个包含9个单词的列表.pop()最后一个单词no.10。单词被随机洗牌,然后再次显示第二个相同单词列表随机改组,最后一个单词.pop(),第一个被删除的正在替换单词(删除/替换) - 希望有点解释它。

我有一个关于反馈正确回答的问题enter code here用户猜测正确答案(不是)其他一切看起来都有效。

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 个答案:

答案 0 :(得分:2)

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

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

word_list[0:9]

最后一行实际上并没有做任何事情。它返回word_list中的前10个元素,但您从未将它们分配给任何内容,因此它基本上是NOP。而是做

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"