Python-random模块

2023-10-22 14:42:42 浏览数 (1)

代码语言:javascript复制
 1 import random
 2 
 3 
 4 print(random.random())  # 随机从0-1之间的随机数
 5 
 6 print(random.randint(1,10))  # 随机从0-1之间的随机数
 7 
 8 print(random.choice('hello'))  # 随机其中一个字符串
 9 print(random.choice([1,2,['hello'],'gg']))
10 
11 print(random.sample([1,2,4,5,7,8,9,6],2))  # 随机取多个值
12 
13 print(random.randrange(1,10))  # 1-10
14 
15 #练习随机数案例
16 # 生成验证码
17 def v_code():
18     code=''
19     for i in range(0,10):
20         code =str(random.randrange(0,10))
21         code =chr(random.randrange(65,91))
22     # print(code)
23     generate_code=random.sample(code,5)
24     str_generate_code="".join(generate_code)
25     return str_generate_code
26 code=v_code()
27 print(code)

0 人点赞