python学习-47 random模块

random模块

随机模块

random 的方法:

print(random.random())                # [0,1] 的浮点数
print(random.randint(1,3))
print(random.randrange(1,3))
print(random.choice([11,22,33]))
print(random.sample([11,22,33,44,55],2))
print(random.uniform(1,4))


item=[1,2,3,4,5,6]
random.shuffle(item)      # 打乱顺序
print(item)

运行结果:

0.14206775234701097
3
1
33
[44, 55]
3.7181594889462453
[6, 3, 2, 1, 4, 5]

Process finished with exit code 0

例如:

随机的字母加数字组合

import random
def a_code():
    ret = ''
    for i in range(5):
        num=random.randint(0,9)                     # 随机数字
        alf=chr(random.randint(65,122))             #随机字母
        res=str(random.choice([num,alf]))
        ret += res
    return ret
print(a_code())
        
GsN13

Process finished with exit code 0

猜你喜欢

转载自www.cnblogs.com/liujinjing521/p/11259114.html