Python 随机出题4个数的四则运算题目,结果及题目作答用分数表示

运行结果: 

 

Python 随机出题4个数的四则运算题目,结果及题目作答用分数表示_第1张图片

fractions 模块:https://www.runoob.com/note/24857

fractions 用法:

https://docs.python.org/zh-cn/3/library/fractions.html

代码如下:

import random
from fractions import Fraction
def expression():
    op = ['+', '-', '*', '/']
    num1 = random.randint(1, 10)  # 随机生成1-10之间的数字
    num2 = random.randint(1, 10)
    num3 = random.randint(1, 10)
    num4 = random.randint(1, 10)
    op1 = random.choice(op)  # 随机生成运算符
    op2 = random.choice(op)
    op3 = random.choice(op)
    formula = str(num1) + str(op1) + str(num2) + str(op2) + str(num3) + str(op3) + str(num4)
    return formula

ret = []
for i in range(20):
    ret.append(expression())

# print(ret)

n = 0
for f1 in ret:
    print(f1+"=?")
    result = Fraction(eval(input())).limit_denominator()
    if result == Fraction(eval(f1)).limit_denominator():  # eval()计算表达式的值
        n += 1
        print('答对啦,你真是个天才!')
    else:
        print('再想想吧,答案似乎是{}喔!'.format(Fraction(eval(f1)).limit_denominator()))
print('你一共答对%d道题,共20道题。' % n)

你可能感兴趣的:(python,python)