目录
Range 模块
Range模块常用方法
# encoding: utf-8
'''
# @Author : ccq
# @File : randomtest.py
# @Time : 2019/8/3 15:37
'''
import random
print(random.random()) # 0-1之间的随机数 不能指定区间
print(random.uniform(1,10))# 给定范围之间的随机数 可指定区间
print(random.randint(2, 9)) # 给定范围之间的随机数 头尾都可以取到
print(random.randrange(1, 3)) # 0-1之间的随机数 头可取,尾不可取
print(random.choice("hello")) # 给定范围之间随机取值 范围可以是元组,字符串等等
print(random.sample("hello",3))# 给定范围之间随机取值 范围同上 第二个参数为取值的个数
Range模块实例
4位验证码实例
# encoding: utf-8
'''
# @Author : ccq
# @File : checkcode_test.py
# @Time : 2019/8/3 15:45
'''
import random
checkcode1 = ''
checkcode2 = ''
# 实现4位随机数字验证码
for i in range(4): # 循环四次
checkcode1 += str(random.randint(0, 9)) # 随机生成0-9中的一个数并转换成str类型加到checkcode上
print(checkcode1) # 输出checkcode
# 实现4位随机验证码
for i in range(4): # 循环四次
checkflag = random.randrange(0, 4) # 作为标志位
# 进行判断,若随机生成的标志与当前i的值相等则生成一个字母,若不相等则生成一个数字
if checkflag == i: # 如果相等则生成字母
checkcode2 += str(chr(random.randint(65, 90))) # 随机生成A-Z中的一个字母并转换成str类型加到checkcode上
else:
checkcode2 += str(random.randint(0, 9)) # 随机生成0-9中的一个数并转换成str类型加到checkcode上
print(checkcode2) # 输出checkcode
# chr函数的返回值是当前整数对应的ascii字符。 即chr(66)的值为大写的A。(因为大写的A的ASCII编码值为66)
备注
内置模块我接下来就不再专门写博客进行介绍了,在以后的python练习过程中如果遇到了我们可以再讨论。主要是因为内置模块很多函数并不常用,而且百度一下就能搜索到很多细致的讲解,例如菜鸟教程之类的,因此我就不再赘述了。