如何用Python生成计算题?

Python030

如何用Python生成计算题?,第1张

这道题我回答过的,不知道怎么被删除了。下面是上次回答的代码。

import random

cnt_n = int(input("题目数量:"))

max_n = int(input("最大数字:"))

# 产生乘法查找表

times_list = []

for i in range(max_n):

    for j in range(max_n):

        if i * j <= max_n:

            qst = str(i) + "*" + str(j)

            rst = str(i*j)

            if qst not in times_list:

                times_list.append([qst, rst])

# 题目表

question_list = []

for _ in range(cnt_n):

    # 随机运算,0+,1-,2*,3/

    op = random.randint(0, 3)

    # +

    if op == 0:

        x1 = random.randint(0, max_n)

        x2 = random.randint(0, max_n - x1)

        result = x1 + x2

        qst = str(x1) + "+" + str(x2) + "="

        question_list.append([qst, result])

    # -

    elif op == 1:

        x1 = random.randint(0, max_n)

        x2 = random.randint(0, x1)

        result = x1 - x2

        qst = str(x1) + "-" + str(x2) + "="

        question_list.append([qst, result])

    # *

    elif op == 2:

        tmp = random.sample(times_list, 1)

        qst = tmp[0][0] + "="

        question_list.append([qst, tmp[0][1]])

    # /

    elif op == 3:

        tmp = random.sample(times_list, 1)

        x1, x2 = tmp[0][0].split("*")

        result = tmp[0][1]

        while int(x1) == 0:

            tmp = random.sample(times_list, 1)

            x1, x2 = tmp[0][0].split("*")

            result = tmp[0][1]

        qst = result + "/" + x1 + "="

        question_list.append([qst, x2])

print("开始回答:")

wrong = ""

for i, qst in enumerate(question_list):

    x = input("第{:>2d}题:{}".format(i+1, qst[0]))

    if int(x) != int(qst[1]):

        wrong += str(i+1) + "  "

w_item = wrong.split()

print("回答正确{}道题目。".format(len(question_list) - len(w_item)))

print("回答错误的题号是:{}".format(wrong))

用Python编程随机产生10个随机整数,并输出整数的和,方法如下

准备材料:python、电脑

1、本文需要加载的模块是:random。

2、给出0到10之间的随机整数:import random,a = random.randint(0,10),print(a)。

3、给出9到10之间的随机实数:import random,a = random.uniform(9,10),print(a)。

4、从9、19、29、39、……、99之间,随机选取一个实数:import random,a = random.randrange(9, 100, 10),print(a)。

5、从列表[5,6,7,8,9]里面,随机选取一个数:import random,a = random.choice([5,6,7,8,9]),print(a)。

6、从一个字符串里面,随机选取一个字符:import random,a = random.choice("从一个字符串里面,随机选取一个字符!"),print(a)。

7、随机打乱列表里面的字符顺序:import random,a = ["p","q","r","s","t","p","q","r","s","t","p","q","r","s","t",],random.shuffle(a),print(a)。

8、从列表里面随机选取9个数字:import random,a = range(3,100,2),b = random.sample(a, 9),print(b)。