我正在尝试做一个测验,然后将用户的分数存储在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文件。
关于python - Python打印到Excel文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36884689/