random模块提供各种生成随机数的函数。

1.生成随机整数:

random.randint(a,b)

random.randint(a,b) #返回一个随机整数&#xff0c;范围是a <&#61;x <&#61; b
>>> random.randint(888,999)
897
>>> random.randint(888,999)
989
>>> random.randint(888,999)
995

random.randrange(start, stop[, step]) #返回指定范围的整数
>>> random.randrange(2,20,2)
6
>>> random.randrange(2,20,2)
4
>>> random.randrange(2,20,2)
14

2.浮点数

random.random() #返回一个浮点数&#xff0c;范围是0.0 到1.0
>>> random.random()
0.22197993728352594
>>> random.random()
0.8683996624230081
>>> random.random()
0.29398514954873434

random.uniform(a,b)#返回一个指定范围的浮点数
>>> random.uniform(1, 10)
3.0691737651343636
>>> random.uniform(1, 10)
9.142357395475619
>>> random.uniform(1, 10)
6.927435868405478

3.随机序列

random.choice()#从非空序列中返回一个随机元素
>>> name
[&#39;du&#39;, &#39;diao&#39;, &#39;han&#39;, &#39;jiang&#39;, &#39;xue&#39;]
>>> random.choice(name)
&#39;xue&#39;
>>> random.choice(name)
&#39;xue&#39;
>>> random.choice(name)
&#39;du&#39;
>>> random.choice(name)
&#39;du&#39;
>>> random.choice(name)
&#39;du&#39;
>>> random.choice(name)
&#39;jiang&#39;

#随机返回指定长度的子序列
>>> random.sample(name,2)
[&#39;xue&#39;, &#39;du&#39;]
>>> random.sample(name,2)
[&#39;diao&#39;, &#39;jiang&#39;]
>>> random.sample(name,2)
[&#39;xue&#39;, &#39;du&#39;]

生成指定长度的随机密码&#xff1a;

[root&#64;zhu ~]# python jiang.py
GrDUytJE
[root&#64;zhu ~]# python jiang.py
8XaCoUTz
[root&#64;zhu ~]# cat jiang.py
import random,string
chars&#61;string.ascii_letters&#43;string.digits
print &#39;&#39;.join([random.choice(chars) for i in range(8)])