多次运行测验时分离分数时出错

时间:2015-06-22 13:46:21

标签: python

对于我的工作,我必须进行3次测验并打印3个单独的分数。但是,当我运行代码时,它会运行测验3次,但只会将最终的测验分数打印到python和文本文件。

我目前正在尝试处理的代码的主要部分是;

NB_QUESTIONS = 2
NB_QUIZNUMBER = 3 

for _ in range(NB_QUIZNUMBER):
    score = 0
    for _ in range(NB_QUESTIONS):
       num1 = random.randint(1,25)
       num2 = random.randint(1,25)
       op, symbol = random.choice(OPERATIONS)
       print("What is", num1, symbol, num2)
       if get_int_input() == op(num1, num2):
           print("Correct")
           score += 1
       else:
           print("Incorrect")

如果需要,这是完整的代码:

import random
import operator

OPERATIONS = [
    (operator.add, "+"),
    (operator.mul, "*"),
    (operator.sub, "-")
    ]

NB_QUESTIONS = 2
NB_QUIZNUMBER = 3
def get_int_input(prompt=''):
    while True:
      try:
        return int(input(prompt))
      except ValueError:
        print("Not a valid input (integer is expected)")

def get_bool_input(prompt=''):
    while True:
        val = input(prompt).lower()
        if val == 'yes':
            return True
        elif val == 'no':
            return False
        else:
            print("Not a valid input (yes/no is expected)")

if __name__ == '__main__':
    name = input("What is your name?").title()
    class_name = input("Which class do you wish to input results for? ")
    print(name, ", Welcome to the OCR Controlled Assessment Maths Test")

    for _ in range(NB_QUIZNUMBER):
        score = 0
        for _ in range(NB_QUESTIONS):
           num1 = random.randint(1,25)
           num2 = random.randint(1,25)
           op, symbol = random.choice(OPERATIONS)
           print("What is", num1, symbol, num2)
           if get_int_input() == op(num1, num2):
               print("Correct")
               score += 1
           else:
               print("Incorrect")

    print("Well done", name, "you scored", score, "/", NB_QUESTIONS)

    filename = class_name + ".txt"

    with open(filename, 'a') as f:
        f.write(str(name) + " : " + str(score) + '\n')

    with open(filename, 'a') as f:
        f = open(filename, "r")
        lines = [line for line in f if line.strip()]
        f.close()
        lines.sort()

    if get_bool_input("Do you wish to view previous results for your class"):
        for line in lines:
            print (line)
    else:
        input ("Press any key to exit")

1 个答案:

答案 0 :(得分:0)

如果你想打印每个测验的分数,你应该在循环中打印 - for _ in range(NB_QUIZNUMBER):,假设这是你为每个测验迭代的循环。

代码 -

for _ in range(NB_QUIZNUMBER):
    score = 0
    for _ in range(NB_QUESTIONS):
       num1 = random.randint(1,25)
       num2 = random.randint(1,25)
       op, symbol = random.choice(OPERATIONS)
       print("What is", num1, symbol, num2)
       if get_int_input() == op(num1, num2):
           print("Correct")
           score += 1
       else:
           print("Incorrect")
    print("Well done", name, "you scored", score, "/", NB_QUESTIONS)