四则运算

作业目标

实现小学四则运算

代码

    import random
    import math
    import fractions

    question = []
    answer = []

    #整数运算

    def first(question,ans):
        symbol = random.choice(['+','-','×','÷']) 
        if symbol == '+':
            a = random.randint(0,10)
            b = random.randint(0,10)
            question.append(str(a)+'+'+str(b)+'=')
            answer.append(a + b)
        elif symbol == '-':
            a = random.randint(0,10)
            b = random.randint(0,10)
            a,b = max(a,b),min(a,b)         
            question.append(str(a)+'-'+str(b)+'=')
            answer.append(a - b)
        elif symbol == '×':
            a = random.randint(0,10)
            b = random.randint(0,10)
            question.append(str(a)+'×'+str(b)+'=')
            answer.append(a * b)
        else:
            a = random.randint(0,10)
            if a == 0:
                b = random.randint(1,10)
            else:
                b = random.randint(1,a+1)
            question.append(str(a)+'÷'+str(b)+'=')
            answer.append(fractions.Fraction(a,b))
    #输出函数
    n=k=int(input("你需要多少道题:"))
    print("题目已生成")
    while n>0:
        first(question,answer)
        n -= 1
        f = open("Exercises.txt",'w')
        g = open("Answers.txt",'w')
        j = 0
    while j<k:
        question1=question[j]
        answer1=str(answer[j])
        x=j+1
        f.write("第""%d""个问题:"%x)
        f.write(question1)
        g.write(answer1)
        f.write('\n')
        g.write('\n')
        j += 1
    
    f.close()
    g.close()

    #统计错题判断对错
    print("完成作业并把答案写在Answer.txt里")
    words = input("完成请输入\'yes':")
    if words == 'yes':
        yours=open('Answers.txt')
        an=open('Answers.txt')
        x=list(yours)
        y=list(an)
        o=0
        C=0
        v=[]
        i=[]
        while o<k:
            if x[o]==y[o]:
                C+=1
                t=o+1
                v.append(t)
            else:
                p=o+1
                i.append(p)
            o+=1
        X=k-C
        G=open('Grade.txt','w')
        G.write('Correct:')
        G.write(str(k))
        G.write(str(v))
        G.write('\n')
        G.write('Wrong:')
        G.write(str(k))
        G.write(str(i))
        G.close()

运行


posted @ 2021-11-27 14:02  20211423袁艺  阅读(16)  评论(0)    收藏  举报