我在打开文本文件时需要帮助。由于某些原因,它似乎没有正常工作,我想知道是否有人可以指出任何错误,并告诉我如何解决它们。谢谢。
import time
import operator
import random
username=input("What is your name?")
usersClass = input("Which class are you in, 1, 2 or 3?")
print ("Welcome {} to the Math quiz, hope you have fun lets begin".format(username))
start = time.time()
def askquestion():
score = 0
opslist = {operator.add: "+", operator.sub: "-", operator.mul: "x"}
num1,num2 = random.randint(1,10), random.randint(1,10)
ops = random.choice(list(opslist.keys()))
ActualAnswer = (ops(num1,num2))
score = 0
print(num1,opslist[ops],num2)
userAns = (int(input("Answer the above")))
if userAns == ActualAnswer:
print("Awesome, that's correct")
return 1
else:
print("Incorrect sorry")
score = score - 0
return 0
totalScore = 0
for i in range (10):
totalScore += askquestion()
print ("Well done, you have completed the quiz")
print("your final score was " + str(totalScore))
if totalScore > 9:
print("Great work! You got top marks!")
elif totalScore > 7:
print("Good, try harder next time and you might get full marks!")
elif totalScore > 5:
print("You did alright")
elif totalScore > 4:
print("Are you not motivated.. c'mon")
else:
print("Hmmm..dissapointing, however know you know what you need to work on")
end = time.time()
etime = end - start
timeTaken = round(etime)
if usersClass == 1:
with open("class1.txt","a+") as f:
f.write("{}:Scored {} in {} seconds".format(username,totalScore,timeTaken))
elif usersClass == 2:
with open("class2.txt","a+") as f:
f.write("{}:Scored {} in {} seconds".format(username,totalScore,timeTaken))
elif usersClass == 3:
with open("class3.txt","a+") as f:
f.write("{}:Scored {} in {} seconds".format(username,totalScore,timeTaken))
答案 0 :(得分:0)
所以看起来你可能需要改变一些事情。您应该使用raw_input来捕获用户的输入。
您对userClass的if语句可能不会触发,因为它们正在查找int而不是输入中传递的数字的字符串。
您可以将这些输入转换为整数:usersClass = int(usersClass)或者您可以在if语句中的整数中添加引号:if usersClass ==" 1":
另外,看起来你的第一个if语句中有一个无意的缩进。
编辑:刚刚意识到你可能正在使用Python3.x,不需要将输入更改为raw_input,因为它在Python3中不存在......我的错误。
答案 1 :(得分:0)
你必须确保usersClass
的价值不会低于1或大于3.你从来没有这样做,这就是为什么如果你输入一些没有数字的数字呢?为了满足这些条件,文件将无法打开或创建。
我没有理解score = score - 0
最后一行之上askquestion
的含义。这是什么意思?如果您不想更改变量的值,请不要这样做。