试图通过随机选择一个琐事游戏

时间:2014-03-27 23:26:30

标签: python python-2.6

import random

file1 = open ("Questions_tf.txt","r")

q = [] #True/false questions
a = [] #True/false answers
dict1 = {}


with open ("Questions_tf.txt", "r") as file1:
        q = [line.strip() for line in file1]

with open ("tf_answers.txt", "r") as file2:
        a = [line.strip() for line in file2]

random_number = 0

def answers(a, file2):
    global tf_randno
    print a [random_number]
    print random_number
    return a

def Questions(q, file1, random_number):
    random_number = random.randrange(0, 5)
    print q[random_number]
    print random_number
    return q
    return random_number

def intro():
    print "Welcome to the game"

def main():
    intro()
    Questions(q, file1, random_number)
    answers(a, file2)


    file1.close()
 main()

这是我的最新代码。

def main(questions, answers):
while len(questions) != 0:
    shuffle(questions)
    print questions.pop(r)
    print answers.pop(r)
    ask_true_false(questions)
    if response == answers.pop(r):

首先,我的代码还远没有完成,至少它现在是怎么回事。但无论如何,这是代码的开始。我现在如何拥有它,我试图将它从具有问题的文本文件中选择一个随机问题,然后从文本文件中找到与答案相同的数字,以便它们是相同的。但我无法弄清楚为什么会这样。另外,我尝试用类来做,但也不能这样做。有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

首先,您不必在Python中初始化变量。它通常会根据需要创建它们。只需这段代码即可:

import random

with open('questions.txt', 'r') as question_file:
    questions = [line.strip() for line in question_file]

with open('answers.txt', 'r') as answer_file:
    answers = [line.strip() for line in answer_file]

# Make a list of tuples: [(q0, a0), (q1, a1), ...]
trivia = zip(questions, answers)
# Shuffle it in place
random.shuffle(trivia)
# Then iterate over it
for question, answer in trivia:
    # play the game
    pass

希望您能看到这如何轻松融入您的主要内容。顺便说一下,你可以使用:

if __name__ == '__main__':
    # code here
    pass

定义在命令行上调用程序时应运行的代码。您也不需要显式close个文件,因为with语句会自动执行此操作。

答案 1 :(得分:0)

由于每个答案都属于一个问题,因此您可以将它们保持配对。您可以在一个包含问题和答案对的列表qas(问答)中阅读。然后,您可以使用random.choice随机选择一个。

这些方面的东西:

import random

with open ('Questions_tf.txt', 'r') as qs, open ('tf_answers.txt', 'r') as ass:
    qas = [map (str.strip, qa) for qa in zip (qs, ass) ]

def randomQA ():
    return random.choice (qas)

for _ in range (10):
    question, answer = randomQA ()
    #actual quiz goes here
    print 'The question is', question
    print 'The answer is', answer