python common module built-in module -random

random module: generating a random number

'''关于数据类型序列相关,参照https://www.cnblogs.com/yyds/p/6123692.html'''
random()

Acquiring random floating point number between 0 and 1, i.e., 0.0 <= num <1.0

import random
# 使用random模块,必须导入

num = random.random()
print(num)  # 0.0 <= num < 1.0
randint (m, n)

Obtaining a random integer between m to n, i.e. m <= num <= n

num = random.randint(2, 10)
print(num)  # 2 <= num <= 10, 注意:是整数
randrange (start, stop, [step])

Random integer to obtain start stop, and a step of step, the default is one. I.e., start <= num <stop

Default step size, random.randrange (1, 5) is equivalent to random.randint (1, 4)

# 默认步长
num = random.randrange(1, 5)
print(num)

# 设置步长为2
num_step = random.randrange(1, 10, 2)
# num_step的取值范围是:1到9之间的任意一个奇数
print(num_step)
shuffle(list)

The order of elements in the list of upset, similar to shuffle operations ( uncertainty is a list or iterable, wrong please correct me )

code_list = ['l', 'd', 'e', 'a', 'w', 'e', 'n']
random.shuffle(code_list)  # 返回值为None,直接在原列表中操作
print(code_list)
choice()

Remove a random element from a non-empty sequence returns

code_turple = ('l', 'd', 'e', 'a', 'w', 'e', 'n')
res = random.choice(code_turple)
print(res)

The following is a small case to obtain random verification code

'''
获取随机验证码小案例
chr(int(n)):用于将ASCⅡ码的数值转换成对应的字符,n的取值范围在0~255,返回值为字符串类型
ord(str('a')):用于将单字符字符串转换成对应的ASCⅡ码,返回值为整型
在ASCⅡ码中,数值65-90:大写英文字符;数值97-122:小写英文字符
'''
def get_code(n):
    '''n:生成几位的验证码'''
    code = ''
    for line in range(n):
        # 随机获取任意一个小写字符的ASCⅡ码
        l_code = random.randint(97, 122)
        # 将ASCⅡ码转换成对应的字符
        l_code = chr(l_code)
        # 随机获取任意一个大写字符的ASCⅡ码
        u_code = random.randint(65, 90)
        # 将ASCⅡ码转换成对应的字符
        u_code = chr(u_code)
        # 随机获取任意一个0-9之间的数字
        n_code = random.randint(0, 9)
        # 将上述3个随机字符存储起来
        code_list = [l_code, u_code, n_code]
        # 从列表中任意取出一个
        random_code = random.choice(code_list)
        # 将字符拼接起来
        code += str(random_code)
    return code


print(get_code(5))

Guess you like

Origin www.cnblogs.com/xiaodan1040/p/12235316.html
Recommended