要在 Python 中生成随机数,可以使用 randint()
函数。这个函数定义在 random 模块中。
源代码
# Program to generate a random number between 0 and 9
# importing the random module
import random
print(random.randint(0,9))
输出
5
请注意,我们可能会得到不同的输出,因为这个程序在 0 和 9 的范围内生成随机数。该函数的语法是
random.randint(a,b)
这将返回一个在闭区间 [a,b]
内的数字 N,意味着 a <= N <= b
,其中端点也包含在范围内。
另请阅读