Python random模块

 1 #!/usr/bin/python
 2 # -*- coding: utf-8 -*-
 3 
 4 import random
 5 
 6 
 7 # random, 生成0-1的随机浮点数
 8 print(random.random())
 9 
10 
11 # uniform 生成指定区间的随机浮点数
12 print(random.uniform(1,10))
13 
14 
15 # help 返回某方法的说明
16 help(random.random())
17 
18 
19 # randint 返回指定范围的随机整数, 顾头顾尾
20 random.randint(1,3)  # 顾头顾尾, 有可能返回1,2,3
21 
22 
23 # randrange,也是返回整数,但顾头不顾尾
24 random.randage(1,3)  # 顾头不顾尾, 返回1,2
25 
26 # randrange, 随机选取0到100间的偶数
27 print(random.randrange(0,101,2))  # 顾头不顾尾, 所以取0到100, 要写成(0,101)
28 
29 
30 # choice 从序列中获取一个随机元素或随机选取字符串
31 random.choice('choice')
32 random.chioce([1,3,4])
33 random.choice(['apple','pear','peach','orange'])  # 返回apple
34 
35 
36 # sample 从序列中随机取指定数量的字符
37 random.sample('hello',2)  # 返回['e','o']
38 
39 
40 # 洗牌shuffle
41 items = [1,2,3,4,5,6,7]
42 print(items)  # [1,2,3,4,5,6,7]
43 random.shuffle(items)
44 print(items)  # [1,4,7,2,5,3,6]

生成验证码

 1 #!/usr/bin/python
 2 # -*- coding: utf-8 -*-
 3 
 4 import random
 5 
 6 # 生成验证码
 7 checkcode = ''
 8 for i in range(4):
 9     checkcode +=str(i)
10 print(checkcode)
11 
12 
13 # 用random随机生成数字验证码
14 checkcode = ''
15 for i in range(4):
16     current = random.randint(1, 9)  # 1到9的随机数
17     checkcode +=str(current)
18 print(checkcode)
19 
20 
21 # 用random随机生成包含字母和数字的验证码
22 checkcode = ''
23 for i in range(4):
24     current = random.randrange(0,4)  # 若四次都猜不中, 就会出现四个字母的验证码; 若四次都猜中, 则会现出四个数字的验证码.
25     # 字母
26     if current == i:
27         temp = chr(random.randint(65,90))  # chr() 把数字转译成ASCII码表中的字母; 65~90 是大写的A到Z.
28     # 数字
29     else:
30         temp = random.randint(0,9)  # 随机生成0到9的数字
31     checkcode +=str(temp)
32 print(checkcode)
原文地址:https://www.cnblogs.com/cheese320/p/9044144.html