python使用列表来保存最近3次练习的题目和答案。首先,每次练习随机生成10个不重复的 题目,同时生成答案;然后,用户练习最新生成的题目,并输出成绩和答案;最后,输出所有 历史成绩。

import random
import pickle
import os
#定义练习系统函数
def practice():
    formular =setQuestion();        #调用题目生成函数,获得最新题目列表
    answerQuestion(formular)        #调用函数,以便用户完成练习
#定义题目生成函数,返回值是最新题目列表
def setQuestion():
    count = 0       #count用于计算出题的数目
    opr={1:'+',2:'-',3:'*',4:'/'}
    formular=[]
    #判断存放旧题的文件是否存在
    if os.path.exists('g:\\测试\\question.dat'):
        pkFile = open('g:\\测试\\question.dat','rb')
        #把文件中的列表元素赋值给列表对象
        data1=pickle.load(pkFile)
        pkFile.close()
    else:
        data1=[]        #否则,列表对象置空
    while True:         #不限次数循环,用于产生不同的题目
        num1=random.randint(1,100)
        num2=random.randint(1,100)
        opnum=random.randint(1,4)
        op=opr.get(opnum)
        result = {
            '+': lambda x, y: x + y,
            '-': lambda x, y: x - y,
            '*': lambda x, y: x * y,
            '/': lambda x, y: x / y,
        }[op](num1, num2)
        #生成一个元组,作为列表中的一个对象
        tmp=(num1,op,num2,result)
        if tmp in formular or tmp in data1:     #若题目重复,则重新出题
            continue
        formular.append(tmp)
        count+=1
        if(count==10):      #不重复添加到列表,总共10break;
    data2=data1[-21:-1]         #从旧题列表中取倒数20个题目
    data2.extend(formular)      #增加新题
    pkFile=open('g:\\测试\\question.dat','wb')
    pickle.dump(data2,pkFile,-1)        #把列表保存到文件中
    pkFile.close()
    return formular         #返回新生成的题目列表
def answerQuestion(formular):
    grade=0     #初始化成绩
    for item in formular:       #遍历列表
        print('{0}{1}{2}='.format(item[0],item[1],item[2]),end=' ')
        #输出题目
        ans=int(input())
        if ans == item[3]:
            grade+=10       #答案正确+10
    if os.path.exists('g:\\测试\\grade.dat'):
        pkFile=open('g:\\测试\\grade.dat','rb')
        allGrade=pickle.load(pkFile)
        pkFile.close()
    else:
        allGrade=[]
    print('本次成绩为:{0}'.format(grade))
    if allGrade:
        print('历史成绩为:{0}'.format(allGrade))
    allGrade.append(grade)
    pkFile=open('g:\\测试\\grade.dat','wb')
    pickle.dump(allGrade,pkFile,-1)
    pkFile.close()
    #输出本次练习答案
    print('本次练习答案为:')
    for item in formular:
        print('{0}{1}{2}={3}'.format(item[0],item[1],item[2],item[3]))
if __name__ == '__main__' :
    practice()

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值