将测验中的分数输出到.txt文件

时间:2016-04-28 19:51:39

标签: python output text-files

我已经完成了这个代码,可以将分数输出到.txt文件,但没有错误,但仍然无法输出分数。任何人都可以帮我找出为什么考虑我是一个非常新的编程。谢谢你:)

from random import shuffle
print ("Welcome to the quiz! ")
name = input('What is your name?: ')


with open ("questions.txt") as f:
    lines = f.readlines ()

shuffle (lines)
numRight = 0
wrong = []

numQuestions = int(input("How many questions? "))

for line in lines [:numQuestions]:
    question, rightAnswer = line.strip().split("\t")
    answer = input(question + '  ')
    rightAnswer = rightAnswer.lower()
    if answer.lower() == rightAnswer:
        print ("Right!")
        numRight +=1
    else:
        print ("No, the answer is", rightAnswer)
        wrong.append(question)


print ("You got %d right  " % (numRight))
if (wrong):
    print ("You got these wrong: ")
    for q in wrong:
        print (q)

user_class = input('What class are you in?: ').lower()
if user_class=="A":
    my_file = open("classAScores.txt")
    my_file.write(name + ' ' +str(numRight))
    my_file.close()

elif user_class =="B":
    my_file = open("classBScores.txt")
    my_file.write(name + ' ' + str(numRight))
    my_file.close()

elif user_class=="C":
    my_file = open("classCScores.txt")
    my_file.write(name + ' ' +str(numRight))
    my_file.close()

2 个答案:

答案 0 :(得分:0)

乍一看不确定其他所有内容,但我肯定会看到一个逻辑错误:

user_class = input('What class are you in?: ').lower()
if user_class=="A":

您将.lower()应用于字符串,然后检查大写" A",这将永远不会发生。

答案 1 :(得分:0)

更改代码的这一部分:

user_class = input('What class are you in?: ').lower()
if user_class=="a":
    with open("classAScores.txt",'a') as my_file:
        my_file.write(name + ' ' + str(numRight) + '\n')