Python打印到Excel文件

我试图做一个测验,然后将用户的分数存储在一个Excel文件中,但是当我这样做的时候,它会写出用户通过10个问题测验所得到的所有分数 – 它在每个问题之后给我分数,但是所有我想要的是用户的名字和他们的最终分数被放入文件。 我如何在我的代码下面做这个?

import time import random question = 0 score = 0 name = input("What is your full name?") while True: studentclass = input("What is your class name? Please enter 1, 2 or 3.") if studentclass.lower() not in ('1', '2', '3'): print("Not an appropriate choice.") else: break print ("Hello " + name, "welcome to The Arithmetic Quiz. This quiz is for eleven year olds. Use integers to enter the answer!") time.sleep(2) operands1 = list(range(2, 12)) operators = ["+","-","x"] operands2 = list(range(2, 12)) while question < 10: operand1 = random.choice(operands1) operand2 = random.choice(operands2) operator = random.choice(operators) def inputNumber(message): while True: try: userInput = int(input(message)) except ValueError: print("Not an integer! Try again.") continue else: return userInput break user_answer =int(inputNumber('{} {} {} = '.format(operand1, operator, operand2))) if operator == '+': expected_answer = operand1 + operand2 if user_answer==expected_answer: print('This is correct!') score = score + 1 question = question + 1 time.sleep(2) else: print('This is incorrect!') question = question + 1 time.sleep(2) if operator == '-': expected_answer = operand1 - operand2 if user_answer==expected_answer: print('This is correct!') score = score + 1 question = question + 1 time.sleep(2) else: print('This is incorrect!') question = question + 1 time.sleep(2) if operator == 'x': expected_answer = operand1 * operand2 if user_answer==expected_answer: print('This is correct!') score = score + 1 question = question + 1 time.sleep(2) else: print('This is incorrect!') question = question + 1 time.sleep(2) if question==10: endscore = str(score) print ("Your score is {} out of 10".format(score)) if studentclass == "1": text_file = open("groupone.csv", "a") text_file.write (name + "," + (str(score)+ "\n")) text_file.close() elif studentclass == "2": text_file = open("grouptwo.csv", "a") text_file.write(name + "," + (str(score)+ "\n")) text_file.close() else: text_file = open("groupthree.csv", "a") text_file.write(name + "," + (str(score)+ "\n")) text_file.close() 

这是打印每个问题的分数,因为你的条件写入一个csv文件, 并不需要问题的数量是10 。 缩进应该这样做:

 if question==10: endscore = str(score) print ("Your score is {} out of 10".format(score)) # Below are indented, meaning they are included UNDER the if statement above if studentclass == "1": text_file = open("groupone.csv", "a") text_file.write (name + "," + (str(score)+ "\n")) text_file.close() elif studentclass == "2": text_file = open("grouptwo.csv", "a") text_file.write(name + "," + (str(score)+ "\n")) text_file.close() else: text_file = open("groupthree.csv", "a") text_file.write(name + "," + (str(score)+ "\n")) text_file.close() 

这样做意味着只有当问题达到10时,才会写入输出csv文件。