运行 print(n),可以看到生成的随机数为 1。新建终端,运行 touch simplerand.py,生成 Python 文件,复制代码并保存,使用 !python3 simplerand.py 运行文件,得到随机数 3。再次运行,得到随机数 1。直接在 notebook 中运行命令也能得到结果,但更推荐使用 %run 命令。若要排除范围最外层的数字,...
使用 Python 中生成随机数字
在 Python 程序中使用随机数有着广泛的应用。例如,在玩《龙与地下城》等游戏时,你可以创建一个小程序来自动掷骰子,虽然实体骰子带来的满足感不可替代,但这样的程序也是学习 Python 随机数功能的不错方法。
使用平台:OpenBayes贝式计算
登录平台后,打开「公共教程」,找到「如何在 Python 中生成随机数字」的教程,点击右上角的「克隆」。
等待资源分配完成,点击「打开工作空间」,双击左侧导航栏中的 Random.ipynb 文件,进入教程。
运行 import random 导入 random 模块。定义变量 n,使用 randint 函数生成 0 到 10 之间的随机数,注意 randint 前面需加上 random,以指明其来自 random 库。
运行 print(n),可以看到生成的随机数为 1。
新建终端,运行 touch simplerand.py,生成 Python 文件,复制代码并保存,使用 !python3 simplerand.py 运行文件,得到随机数 3。再次运行,得到随机数 1。
直接在 notebook 中运行命令也能得到结果,但更推荐使用 %run 命令。
若要排除范围最外层的数字,可以使用 randrange 函数,例如 n = random.randrange(0,10),得到 1 到 9 的随机数。
设计一个更复杂的随机数生成器,接受用户输入作为范围,导入 random 模块,定义 number_1 变量接收输入,将输入转换为整数,运行 n = random.randint(0, int(number_1)),得到随机数 n。
创建新文件,复制代码并保存,使用 !python3 rando.py 运行,输入数字得到随机数。在 notebook 中运行需将 Python 换为 run 命令。
使用 while 循环不断获取用户输入,生成随机数:import random,while True: number_1 = input("Enter the number of sides on your dice..."), n = random.randint(0, int(number_1)), print(n)2024-08-19