zoukankan      html  css  js  c++  java
  • Python之Random模块

    Random模块生成随机数

    >>> print random.random()        #随机生成0-1的小数
    0.772367387029
    >>> print random.randint(1,200)     #随机生成整数小于或者等于
    107
    >>> print random.randrange(1,200)           #随机生成整数小于最大的数

    152

    假如想随机生成字母可以使用python里面的chr方法结合random生成字母

    chr(random.randint(65,121))

    使用以上方法生成一个带大写字母和数字的随机数

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    
    import random
    checkcode = ''                          #定义一个空的字符串
    for i in range(4):                      #循环4次
        current = random.randrange(0,4)     #随机生成0,1,2,3
        if current != i:                    #如果生成的随机数刚刚好等于i则随机生成一个大写字母赋值给temp
            temp = chr(random.randint(65,90))       
        else:                               #否则随机生成0,1,2,3,4,5,6,7,8,9数字赋值给temp
            temp = random.randint(0,9)
        checkcode += str(temp)              #一次循环生成的一个数字或者大写字符赋值给字符串
    print checkcode                         #四次循环以后打印字符串
    

    执行

  • 相关阅读:
    去除图片水印
    CALayer
    UIKit Animation
    CoreAnimation
    3DTouch
    键盘事件
    weChat聊天发送图片带有小尖角的实现
    webView 和 js 交互 之 屏蔽 样式
    iOS socket编程
    tableView尾部多处一部分空白高度
  • 原文地址:https://www.cnblogs.com/minseo/p/6897935.html
Copyright © 2011-2022 走看看