Python随机出题的四则运算

img

img

img

img


编写一个能随机出题的四则运算小程序
为了完成本关任务,你需要掌握random函数用法

根据给出的代码修改下就可以了。

补充如下:

参考链接:



import random

random.seed(0)

def calculator(n,maximum):

    correct=0
    
    for i in range(n):
       # https://www.runoob.com/python3/ref-random-randint.html 
        # 产生一个0到maximum之间的随机整数
        b=random.randint(0,maximum)
        # 产生一个b到maximum之间的随机整数
        a=random.randint(b,maximum)

        #  打印题目式子
        print(f'{a}+{b}=',end='')
        # 获取输入的计算结果
        result=float(input())

        # 如果回答正确,则正确题目数+1,
        # 然后打印回答正确的提示信息
        if result==eval(f'{a}+{b}'):
            correct+=1
            print('恭喜你,回答正确')
        else: # 如果回答错误,则打印错误的提示信息
            print('回答错误,你要加油哦!')
    # 打印回答正确的题目数,以及正确率
    print(f'答对{correct}题,正确率为{correct/n*100}%')
                
if __name__ == '__main__':

    # 获取出题数
    n = int(input("请输入出题数量:"))
    # 获取参与计算的最大数字
    maximum=int(input("请输入参与计算的最大数字:"))
    
    # 调用calculator()函数,进行答题
    calculator(n,maximum)


img

import random

random.seed(0)


def calculator(n, maximum):
    correct = 0
    for i in range(n):
        a = random.randint(0, maximum)
        b = random.randint(0, maximum)

        ans = int(input(f'{a}+{b}='))
        if ans == a + b:
            print('恭喜你,回答正确')
            correct += 1
    return correct


if __name__ == '__main__':
    count = int(input('请输入出题数量:'))
    maximum = int(input('请输入参与计算的最大数字:'))
    correct = calculator(count, maximum)
    print(f'答对{correct}题,正确率为{correct/count*100}%')
  • 帮你找了个相似的问题, 你可以看下: https://ask.csdn.net/questions/7595603
  • 你也可以参考下这篇文章:学Python遇到那些坑,引用random随机数模块的问题
  • 除此之外, 这篇博客: Python中利用Random包生成随机密码以及将密码存入文档中的 1首先为大家介绍一下Random包 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • random是内建(built-in)函数,作用是产生随机数,使用较多.

    首先是导入模块

    import randoom

    接着就可以调用random模块下的函数了。

    使用下面命令语句可以查看random包所包含的内容:

    dir(random)
    ['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hashlib', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'division', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

    -random.randint(start,end)  

    简单的使用方法如下

    random.randint(1, 100)  # 54

    -random.choice(seq)

    从序列中随机选取一个元素等等。

    random.choice([1, 2, 3, 5, 8, 13]) #list 5
     
    random.choice('hello') #字符串  h
     
    random.choice(['hello', 'world']) #字符串组成的list  'world'
     
    random.choice((1, 2, 3) #元组 3

     

  • 以下回答由chatgpt基于相关博客总结生成:

    我可以给出一个Python程序示例来随机生成四则运算题目,包括加减乘除,数字范围限制及计算结果不能为负数等条件,具体步骤如下:

    1. 导入random模块来实现随机数生成,定义需要生成的题目数量和数字的最大最小值范围:
    import random
    
    num_range = [1, 100] # 数字范围
    num_total = 10 # 表达式总数
    op = {"+":lambda x, y :x + y, "-":lambda x, y :x - y, "*":lambda x, y :x * y, "/":lambda x, y:x / y}# 定义操作符及其对应的函数
    
    1. 通过循环,生成随机的数值和操作符,并将其加入到生成的题目列表中:
    def generate_expression(num_range):
        # 生成基础题目,包括数字和运算符
        nums = [str(random.randint(num_range[0], num_range[1])) for i in range(2)]
        op_func = random.choice(op.keys())
        exp = nums[0] + " " + op_func + " " + nums[1]
    
        return exp, op_func
    
    def generate(num_total, num_range):
        # 生成题目
        exp_list = []
        for i in range(num_total):
            exp, op_func = generate_expression(num_range)
            tmp = eval(exp)
            while(tmp < 0 or tmp > num_range[1]):
                exp, op_func = generate_expression(num_range)
                tmp = eval(exp)
            exp += " = "
            exp_list.append(exp)
        return exp_list
    
    if __name__ == "__main__":
        exp_list = generate(num_total, num_range)
        print(exp_list)
    
    1. 调用生成函数,输出生成的题目列表即可。

    完整代码如下:

    import random
    
    num_range = [1, 100] # 数字范围
    num_total = 10 # 表达式总数
    op = {"+":lambda x, y :x + y, "-":lambda x, y :x - y, "*":lambda x, y :x * y, "/":lambda x, y:x / y}# 定义操作符及其对应的函数
    
    def generate_expression(num_range):
        # 生成基础题目,包括数字和运算符
        nums = [str(random.randint(num_range[0], num_range[1])) for i in range(2)]
        op_func = random.choice(op.keys())
        exp = nums[0] + " " + op_func + " " + nums[1]
    
        return exp, op_func
    
    
    def generate(num_total, num_range):
        # 生成题目
        exp_list = []
        for i in range(num_total):
            exp, op_func = generate_expression(num_range)
            tmp = eval(exp)
            while(tmp < 0 or tmp > num_range[1]):
                exp, op_func = generate_expression(num_range)
                tmp = eval(exp)
            exp += " = "
            exp_list.append(exp)
        return exp_list
    
    if __name__ == "__main__":
        exp_list = generate(num_total, num_range)
        print(exp_list)
    

    输出结果:

    ['98 - 61 = ', '84 / 14 = ', '25 * 80 = ', '61 + 22 = ', '57 + 44 = ', '5 * 39 = ', '24 + 58 = ', '95 + 4 = ', '5 * 35 = ', '90 - 75 = ']
    
  • 代码运行效果截屏

    img


      稍微再修整一下,就可以作为练习口算能力的小程序哦😊

  • Python 代码

#!/sdcard/qpython python
# coding: utf-8
import random


random.seed(0)
clear = '\033[2J' # Linux 清屏字符串。


def calculator(n, maxnum):
    correct = 0
    tip = f"{'':~^36}"
    print(f"{tip:^50}\n")
    
    for i in range(n):
        b = random.randint(0, maxnum)
        a = random.randint(b, maxnum)
        ### begin

        if b > a:
            a, b = b, a # 如果 b > a ,交换 a、b 的值。

        sign = random.choice('+-*/') # 除法结果是浮点数,判定麻烦,这里不用除法。
        exp = f"{a} {sign} {b}"
        sign = sign if sign not in '*/' else '×' if sign == '*' else '÷' # 如果运算符是'*',换成'×' 。
        exp_str = f"{a} {sign} {b}"
        isright = input(f"\n{i+1:>18}. {exp_str:} = ").strip()
    
        if isright == str(int(eval(exp))):
            correct += 1
    
        ### end
    print(f"{tip:^50}\n")
    print(f"\n\n{'':>12}答对 {correct} 题,正确率 {correct/n*100:.2f}% 。\n{'':~^50}")


if __name__ == '__main__':
    print(f"{clear}\n{' 随机出题整数四则运算 ':~^40}\n")
    n, maxnum = map(int, [input(f"\n{' ':>8}{i}:") for i in ('随机出题数', '运算最大取值')])
    calculator(n, maxnum)
如果帮到您,请您采纳

  稍微再修整一下,就可以作为练习口算能力的小程序哦😊