怎么统计答题数和正确数呢?
自己试了几次都不知道在哪里加循环
def Backword(self): # 背单词
with open("danciben.txt", 'r') as worldFile:
world_list = worldFile.readlines()
# 使用random.shuffle函数将单词列表打乱
random.shuffle(world_list)
for index in world_list:
w = index.split(" ")[0]
c = index.split(" ")[1]
count = 1
flag = True
while count <= 3 and flag == True:
en = input(str(w) + "的汉语意思:")
if en + "\n" == c:
print("恭喜答对")
flag = False
if en + "\n" != c:
print("答错了,还有" + str(3 - count) + "次机会:")
count = count + 1
flag = True
print("您已经完成了单词本里的全部单词")
danciben.txt
wind n.胸口,心窝
convey vt.传达;传播;转让
correctly ad.正确地,恰当地
clap n.拍手喝采声;霹雳声
coin vt.铸造(硬币)
popularity n.通俗性;普及,流行
abbreviation n.节略,缩写,缩短
abide vt.遵守;vt.忍受
abolish vt.废除,取消
absent a.不在意的
absorption n.吸收;专注
可以使用两个变量分别记录答题数和正确数。在每次循环中提问答案时,答题数就加 1。如果答案正确,正确数就加 1。
修改后的完整代码如下:
def Backword(self): # 背单词
with open("danciben.txt", 'r') as worldFile:
world_list = worldFile.readlines()
# 使用random.shuffle函数将单词列表打乱
random.shuffle(world_list)
total_count = 0 # 答题数
correct_count = 0 # 正确数
for index in world_list:
w = index.split(" ")[0]
c = index.split(" ")[1]
count = 1
flag = True
while count <= 3 and flag == True:
en = input(str(w) + "的汉语意思:")
total_count += 1 # 答题数加 1
if en + "\n" == c:
correct_count += 1 # 正确数加 1
print("恭喜答对")
flag = False
if en + "\n" != c:
print("答错了,还有" + str(3 - count) + "次机会:")
count = count + 1
flag = True
print("您已经完成了单词本里的全部单词")
print("答题数:", total_count)
print("正确数:", correct_count)
申明变量直接去统计答对的数量,请采纳!!
import random
with open("danciben.txt", 'r',encoding='utf8') as worldFile:
world_list = worldFile.readlines()
# 使用random.shuffle函数将单词列表打乱
random.shuffle(world_list)
count_success = 0
count_error = 0
for index in world_list:
w = index.split(" ")[0]
c = index.split(" ")[1]
count = 1
flag = True
while count <= 3 and flag == True:
en = input(str(w) + "的汉语意思:")
if en + "\n" == c:
print("恭喜答对")
count_success+=1
flag = False
if en + "\n" != c:
print("答错了,还有" + str(3 - count) + "次机会:")
count = count + 1
count_error+=1
flag = True
print("您已经完成了单词本里的全部单词")
print("您共答题"+str(len(world_list))+"道,答对"+str(count_success)+'题,答错'+str(count_error)+'题,继续加油哦!')