函数和常用模块【day06】:random模块(三)

时间:2023-03-09 17:39:31
函数和常用模块【day06】:random模块(三)

本节内容

1、简述

2、random模块

3、string模块

4、生成随机数

一、简述

  我们经常会使用一些随机数,或者需要写一些随机数的代码,今天我们就来整理随机数模块:random模块

二、random模块

1、random.random()

功能:随机返回一个小数

1
2
3
>>> import random
>>> random.random()
0.14090974546903268  #随机返回一个小数

2、random.randint(a,b)

功能:随机返回a到b之间任意一个数,包括b

1
2
3
4
5
>>> import random
>>> random.randint(1,5)
5   #可以返回5
>>> random.randint(1,5)
2

3、random.randrange(start, stop=None, step=1)

功能:随机返回start到stop,但是不包括stop值

1
2
3
4
5
>>> import random
>>> random.randrange(5)  #不能随机返回5
4
>>> random.randrange(5)
1

4、random.sample(population, k)

功能:从population中随机获取k个值,以列表的形式返回

1
2
3
4
5
>>> import random
>>> random.sample(range(10),3)  #从0-9返回3个随机数
[310]
>>> random.sample('abcdefghi',3)  #从'abcdefghi'中返回3个字符
['a''h''b']

三、string模块

1、string.ascii_letters

功能:返回大小写字母的字符串

1
2
3
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'  #返回大小写字母字符串

2、string.ascii_lowercase

功能:返回小写字母的字符串

1
2
3
>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'  #返回小写字母的字符串

3、string.ascii_uppercase

功能:返回大写字母的字符串

1
2
3
>>> import string
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'  #返回大写字母的字符串

4string.digits

功能:返回0-9数字的字符串

1
2
3
>>> import string
>>> string.digits
'0123456789'    #返回0-9数字的字符串

5、string.punctuation

功能:返回所有特殊字符,并以字符串形式返回

1
2
3
>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'  #返回所有特殊字符,并以字符串的形式返回

四、生成随机数

1、用random和string模块生成随机数

1
2
3
4
5
6
>>> import random,string
>>> str_source = string.ascii_lowercase + string.digits  #大写字母字符和0-9数字字符串拼接
>>> random.sample(str_source,6)    #取6个随机字符
['f''1''a''m''j''h']
>>> ''.join(random.sample(str_source,6))  #生成一个随机数字符串
'f84bsj'

2、程序实现

1
2
3
4
5
6
7
8
9
10
import random
checkcode = ''
for in range(4):
    current = random.randrange(0,4)
    if current != i:   #如果当前的loop  i不等于随机数,就取出65-90中的随机字符
        temp = chr(random.randint(65,90))
    else:
        temp = random.randint(0,9)
    checkcode += str(temp)
print(checkcode)