将测验的分数输出到 .txt 文件
outputting scores from a quiz to a .txt file
我已经完成了将分数输出到 .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()
乍一看不确定其他所有内容,但我可以肯定地看到一个逻辑错误:
user_class = input('What class are you in?: ').lower()
if user_class=="A":
您将 .lower()
应用于字符串,然后检查大写字母 "A",这永远不会发生。
更改这部分代码:
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')
我已经完成了将分数输出到 .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()
乍一看不确定其他所有内容,但我可以肯定地看到一个逻辑错误:
user_class = input('What class are you in?: ').lower()
if user_class=="A":
您将 .lower()
应用于字符串,然后检查大写字母 "A",这永远不会发生。
更改这部分代码:
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')