Python基础——常用内置模块-random

random模块用于生成随机数,常用的函数如下:

1.生成随机浮点数(0<=n<1)

import random
res1 = random.random()
print(res1)

2.生成一个指定范围内的整数(生成的随机数n: a <= n <= b)

import random
res2 = random.randint(20,30)
print(res2)

3.从指定范围内,按指定基数递增的集合中,获取一个随机数.
random.randrange的函数原型为:random.randrange([start], stop[, step])

 import random
res3 = random.randrange(10, 100, 2)     #从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。
res30 = random.randrange(10,100)        #从[10, 11, 12, 13, ... 98, 99]序列中获取一个随机数。
print(res3, res30)

4.从序列中获取一个随机元素
random.choice(sequence),参数sequence表示一个有序类型,如list,string,tuple

res4 = random.choice("学习Python")
print(res4)
res40 = random.choice(["Go","is","a","handsome","boy"])
print(res40)
res41 = random.choice(("Tuple","List","Dict"))
print(res41)

5.将一个列表中的元素打乱,random.shuffle(x[, random])

import random
lit = [1,2,3,4,5,6,7,8,9]
random.shuffle(lit)
print(lit)                      #[6, 1, 9, 8, 4, 5, 7, 2, 3]

6.指定序列中随机获取指定长度的片断,random.sample(sequence, k),sample函数不会修改原有序列

import random
list = [1,2,3,4,5,6,7,8,9]
res5 = random.sample(list, 4)
print(res5)                     #[7, 2, 9, 6]
print(list)                     #[1, 2, 3, 4, 5, 6, 7, 8, 9]

ASCII数字转换

print(chr(65),chr(90),chr(97),chr(122))   #A Z a z

生成一个5位校验码(包含字母和数字)

def V_CODE():
    code = " "
    for i in range(5):
        #  random.randrange(10)                   #生成数字(0-9)
        #  chr(random.randrange(65,91))           #生成大写字母(A-Z)
        #  chr(random.randrange(97,123))          #生成大写字母(a-z)
        #取任一一个字符
        character = random.choice([random.randrange(10), chr(random.randrange(65,91)), chr(random.randrange(97,123))])
        code +=str(character)
    print(code)
V_CODE()

你可能感兴趣的:(Python学习)