python - 生成范围内两个随机整数范围内的结果

标签 python python-3.x

对于一项学校作业,我必须选择 0 到 20 之间的两个随机整数,其结果(通过 sub 或 add 也选择随机)必须在 0 到 20 的范围内。 对于我使用的整数和操作:

def random():
    op={"-": operator.sub, "+": operator.add}
    a = random.randint (0,20)
    b = random.randint (0,20)

    ops = random.choice(list(op.keys()))
    answer=op[ops](a,b)
    return answer

以上代码的源链接:How can I randomly choose a maths operator and ask recurring maths questions with it?

但我不知道如何以只能给出 0 到 20 范围内的结果的方式使用它。Python v3.0 初学者。

最佳答案

如果我没有正确理解你的问题,你只希望你的函数返回一个介于 0 和 20 之间的结果。在这种情况下,你可以使用 while 循环直到你的条件得到满足。

def random():
    while True:
        op={"-": operator.sub, "+": operator.add}
        a = random.randint (0,20)
        b = random.randint (0,20)

        ops = random.choice(list(op.keys()))
        answer=op[ops](a,b)
        if answer in range(0,20):
            return answer

关于python - 生成范围内两个随机整数范围内的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41033690/

相关文章:

python - 如何在我的Mapper和Reducer中使用此代码?我想在Google集群中运行此代码

python - 为什么图像在 Kivy 中不能正确显示为按钮背景?

python - beautifulsoup4 : placing a for loop unwrapping tags into a definition (python3)

python - 删除前导和尾随斜杠/在python中

python - 从 CSV 创建特定格式的 JSON 文件

python - 如何使用Python在BeautifulSoup中提取同一div中具有相同标签的元素?

python-3.x - 比较 keras tensorflow 后端模型训练的结果

python - 如何在 Django + Apache + mod_python 中使用 Staticgenerator

python - tkinter 在窗口关闭之前不会打印

python - Tensorboard:无标量值