• random模块


    1.基本用法

     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 # Author:James Tao
     4 import random
     5 
     6 print(random.random())#生成0-1之间的随机浮点数
     7 
     8 print(random.uniform(1,3))#生成1-3之间的随机浮点数
     9 
    10 print(random.randint(1,3))#生成1-3之间的整数,前后都能取到
    11 
    12 print(random.randrange(1,3))#生成1-3之间的整数,包含1不包含3
    13 
    14 print(random.choice('asdas'))#a、元组、列表、字符串,产生随机值
    15 
    16 print(random.sample('hello',2))#从字符串中随机取两位返回
    17 
    18 L=[1,2,3,4,5]
    19 random.shuffle(L)#洗牌,打乱顺序
    20 print(L)

    运行结果:

    2.运用random模块编写验证码生成模块

     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 # Author:James Tao
     4 
     5 #使用random模块生成验证码
     6 
     7 import random
     8 
     9 checkcode=''
    10 
    11 code_length=6#长度固定为6
    12 
    13 for i in range(code_length):
    14 
    15     currentcode=random.randrange(0,code_length)
    16 
    17     if i==currentcode:
    18         tempcode=chr(random.randint(65,90))#获取ASCII表中65到90之间对应字母
    19     else:
    20         tempcode=str(random.randint(0,9))#转换成字符串
    21 
    22     checkcode+=tempcode#字符串拼接
    23 
    24 print(checkcode)
  • 相关阅读:
    airpods2连接win10的方法步骤
    JSON学习笔记
    TCP-IP总线与CAN总线优缺点对比
    svn切换目录
    SQLite学习笔记
    python-opencv安装及入门
    python数据可视化
    python-opencv视觉巡线
    python-opencv进阶应用
    QT窗口和部件
  • 原文地址:https://www.cnblogs.com/BIT-taozhen/p/9864801.html
Copyright © 2020-2023  润新知