【问题标题】:Python quiz, need guidancePython测验,需要指导
【发布时间】:2014-04-24 15:35:05
【问题描述】:

这是我的第一个代码,所以如果你能忍受我并尽可能彻底。

此测验提出一个问题,有 4 个可能的答案,您可以选择 1-4。它读取的文件如下所示。正确答案显示在问题上方。

A
Which sport uses the term LOVE ?
A)Tennis
B)Golf
C)Football
D)Swimming
B
What is the German word for WATER ?
A)Wodar
B)Wasser
C)Werkip
D)Waski

我想要做的是抓住这个块,而不是它现在所做的问题的答案,只有问题和可能的答案。当您猜测时,它会将您的答案与真实答案进行比较,看是否匹配,如果匹配,您将获得分数,如果不匹配,您不会。我最大的疑问是如何比较它并在没有答案的情况下获得这些块。

quiz_file = '/home/wryther/Desktop/QUIZ.DAT'
num_questions = 146

def get_chunk(buf, n):

    while buf:
        chunk = [buf.readline() for _ in range(n)]

         if not any(chunk):
             chunk = None

         yield chunk

def get_awns(ans):  #This transfomrs the ints answers to str so it could compare if its right or wrong.
   if ans == 1:
         ans = 'A'
    elif ans == 2:
         ans = 'B'
    elif ans == 3:
         ans = 'C'
    elif ans == 4:
         ans = 'D'



with open(quiz_file) as quiz_contents:

    choices = [None] * num_questions

    i = 0

    for chunk in get_chunk(quiz_contents, 6):
            if not chunk:
            break

            print()
            for line in chunk:
            print(line)

            choices[i] = int(input("1   3\n2    4?\n:"))
            get_awns(choices[i])

感谢所有回复,无论是批评、提示还是帮助,只要它与我的主题相关。

【问题讨论】:

  • 这是我的第一个代码,所以如果你能告诉我:不是bare,而是bear。请。
  • 在每个chunk中,chunk[0]是答案键,chunk[1]是问题,chunk[2:]是答案文本行
  • 感谢 gee 帮了大忙!知道如何将 chunk[0] 与他们的答案进行比较并加分吗?太好了,提前谢谢。

标签: python compare


【解决方案1】:

如果我正确阅读了您的答案,您的问题是关于如何在每个块中将问题与答案分开。正如@jonrsharpe 评论的那样,您必须分别访问每个块的项目。要么使用 jonrsharpe 说的下标,要么直接解压。

def readChunk(buf, n):
    for _ in range(n):
        yield next(buf).strip() #get rid of newlines

with open('questions.txt', 'r') as lines:
    while True:
        try:
            #Unpacking into separate values
            correct, question, *answers = readChunk(lines, 6)
        except ValueError:
            #End of file
            break
        print('The question is', question)
        print('And the answers are', answers)
        print('And the correct answers is', answers[ord(correct) - ord('A')])

使用您的示例文件,此 sn-p 输出:

The question is Which sport uses the term LOVE ?
And the answers are ['A)Tennis', 'B)Golf', 'C)Football', 'D)Swimming']
And the correct answers is A)Tennis
The question is What is the German word for WATER ?
And the answers are ['A)Wodar', 'B)Wasser', 'C)Werkip', 'D)Waski']
And the correct answers is B)Wasser

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-15
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    相关资源
    最近更新 更多