• python之random函数


     

     1 #-*- coding:utf-8 -*-
     2 
     3 # random各种使用方法
     4 import random
     5  
     6 # 随机生成[0.1)的浮点数
     7 print("random():", random.random())
     8  
     9 # 随机生成1000-9999之间的整数
    10 print("randint(1000, 9999):", random.randint(1000, 9999))
    11  
    12 # 随机生成0-20之间的偶数
    13 print("randrange(0, 21, 2):", random.randrange(0, 21, 2))
    14  
    15 # 随机生成0-20之间的浮点数
    16 print("uniform(0, 20):", random.uniform(0, 20))
    17  
    18 # 从序列中随机选择一个元素
    19 list_string = ['a', 'b', 'c', 'd', 'e']
    20 print("choice(list):", random.choice(list_string))
    21 print("choice(string):", random.choice('abcd'))
    22  
    23 # 对列表元素随机排序
    24 list_number = [1, 2, 3, 4, 5]
    25 random.shuffle(list_number)
    26 print("shuffle(list):", list_number)
    27  
    28 # 从指定序列中随机获取指定长度的片断
    29 print("sample(sequence):", random.sample('abcdefg', 2))

     

    结果:

    random(): 0.39840036736565154
    randint(1000, 9999): 5736
    randrange(0, 21, 2): 2
    uniform(0, 20): 15.785447740011865
    choice(list): b
    choice(string): b
    shuffle(list): [5, 3, 4, 1, 2]
    sample(sequence): ['f', 'b']

    编写一个生成验证码:

     1 import random
     2 def v_code():
     3     code=''
     4     for i in range(5):
     5         code+=str(random.choice([random.randrange(10),chr(random.randrange(65,91))]))
     6        
     7     print(code)
     8      
     9      
    10 v_code()

    结果:

    04TT3

     

  • 相关阅读:
    随便发泄几句
    四年有感
    测试产品杂谈
    质量管理杂谈
    提升
    下半年工作方向
    测试资源分配
    2013思路
    微博吐槽汇总
    招聘
  • 原文地址:https://www.cnblogs.com/Mengchangxin/p/9256336.html
Copyright © 2020-2023  润新知