我有一个功能可以测量某人回答乘法和所需的时间,但我希望能够显示用户完成使用后所需的平均时间功能(它在while循环中)。这是功能:
def withTimer():
playAgain = "yes"
correct = 0
total = 0
while playAgain == "yes":
total = total + 1
random1 = random.choice(tablesUsed)
random2 = random.randint(1, 12)
realAnswer = random1 * random2
start = time.time()
humanAnswer = int(input("What is the answer to this multiplication sum?\n" + str(random1) + " * " + str(random2) + "\n"))
if realAnswer == humanAnswer:
elapsed = round((time.time() - start), 1)
correct = correct + 1
score = str(int(correct / total * 100)) + "%"
if elapsed < 2:
print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nThat is a very good time!\nScore: " + score)
else:
print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nNow work on your time.\nScore: " + score)
else:
score = str(int(correct / total * 100)) + "%"
print("Unforunately, you got this one incorrect, the actual answer was " + str(realAnswer) + ".\nScore: " + score)
elapsed1 =
playAgain = input("Do you wish to play again? (yes or no)\n")
if playAgain == "yes":
settings()
else:
print("Thank you for practicing your multiplication tables\nwith me\nFinal Score: " + score + "\nAverage Time: " + averageTime)
我已经写了averageTime变量来显示我想要显示的平均时间。
我试过这个:
if realAnswer == humanAnswer:
elapsed = round((time.time() - start), 1)
times = times.append(elapsed)
我在另一个函数中定义了变量times = []
和global times
,但这会产生错误:
'NoneType' object has no attribute 'append', line 26
请帮助我尝试了解正在发生的事情和解决方案! 提前谢谢。
答案 0 :(得分:0)
您可以创建经过时间的列表,然后通过将所有已用时间相加并除以列表中的项目数来计算平均值,但是您不需要。只要您保持经过时间的总计,平均回答时间就是总经过时间除以答案总数。
以下版本的程序以这两种方式计算平均值,并显示两者以显示结果相同。
import time,random
def withTimer():
playAgain = "yes"
correct = 0
total = 0
totalTime = 0
etime = []
while playAgain[0] == "y":
total = total + 1
random1 = random.randint(1, 12)
random2 = random.randint(1, 12)
realAnswer = random1 * random2
start = time.time()
humanAnswer = int(input("What is the answer to this multiplication sum?\n" + str(random1) + " * " + str(random2) + "\n"))
if realAnswer == humanAnswer:
elapsed = round((time.time() - start), 1)
etime.append(elapsed)
correct = correct + 1
score = str(int(correct / total * 100)) + "%"
if elapsed < 2:
print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nThat is a very good time!\nScore: " + score)
else:
print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nNow work on your time.\nScore: " + score)
else:
score = str(int(correct / total * 100)) + "%"
print("Unforunately, you got this one incorrect, the actual answer was " + str(realAnswer) + ".\nScore: " + score)
totalTime += elapsed
playAgain = input("Do you wish to play again? (yes or no)\n")
averageTime = totalTime / total
averageTime1 = sum(etime) / len(etime)
if playAgain[0] != "y":
print("Thank you for practicing your multiplication tables\nwith me\nFinal Score: " + score + "\nAverage Time: " + str(averageTime) + " AverageTime1 = " + str(averageTime))
withTimer()