python模块之random模块

之前我们讲到了time模块

那我们今天来谈一谈random模块

random模块可谓是python模块中最为简单的一个模块了

那,接下来我们步入正堂

首先,我们要导入random包来使用相关函数

import random

接下来我们使用help函数来看看random包里都有一些什么呢

print(help(random))

Help on module random:

NAME
    random - Random variable generators.

MODULE REFERENCE
    https://docs.python.org/3.8/library/random
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete,incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt,consult the module reference at the
    location listed above.

DESCRIPTION
        integers
        --------
               uniform within range
    
        sequences
        ---------
               pick random element
               pick random sample
               pick weighted random sample
               generate random permutation
    
        distributions on the real line:
        ------------------------------
               uniform
               triangular
               normal (Gaussian)
               lognormal
               negative exponential
               gamma
               beta
               pareto
               Weibull
    
        distributions on the circle (angles 0 to 2pi)
        ---------------------------------------------
               circular uniform
               von Mises
    
    General notes on the underlying Mersenne Twister core generator:
    
    * The period is 2**19937-1.
    * It is one of the most extensively tested generators  existence.
    * The random() method is implemented in C,executes  a single Python step,and is,therefore,threadsafe.

CLASSES
    _random.Random(builtins.object)
        Random
            SystemRandom
    
    class Random(_random.Random)
     |  Random(x=None)
     |  
     |  Random number generator base  used by bound module functions.
     |  
     |  Used to instantiate instances of Random to get generators that don't
     |  share state.
     |  
     |  Class Random can also be subclassed if you want to use a different basic
     |  generator of your own devising:  that case,override the following
     |  methods:  random(),seed(),getstate(), setstate().
     |  Optionally,implement a getrandbits() method so that randrange()
     |  can cover arbitrarily large ranges.
     |  
     |  Method resolution order:
     |      Random
     |      _random.Random
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  __getstate__(self)
     |      # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
     |       longer called; we leave it here because it has been here since random was
     |       rewritten back in 2001 and why risk breaking something.
     |  
     |  __init__(self,x=None)
     |      Initialize an instance.
     |      
     |      Optional argument x controls seeding,as for Random.seed().
     |  
     |  __reduce__(self)
     |      Helper  pickle.
     |  
     |  __setstate__(self,state)
     |  
     |  betavariate(self,alpha,beta)
     |      Beta distribution.
     |      
     |      Conditions on the parameters are alpha > 0 and beta > 0.
     |      Returned values range between 0 and 1.
     |  
     |  choice(self,seq)
     |      Choose a random element from a non-empty sequence.
     |  
     |  choices(self,population,weights=None,*,cum_weights=None,k=1)
     |      Return a k sized list of population elements chosen with replacement.
     |      
     |      If the relative weights or cumulative weights are not specified,|      the selections are made with equal probability.
     |  
     |  expovariate(self,lambd)
     |      Exponential distribution.
     |      
     |      lambd is 1.0 divided by the desired mean.  It should be
     |      nonzero.  (The parameter would be called "lambda",but that is
     |      a reserved word in Python.)  Returned values range  0 to
     |      positive infinity if lambd is positive,1)"> negative
     |      infinity to 0  negative.
     |  
     |  gammavariate(self,1)">      Gamma distribution.  Not the gamma function!
     |      
     |      Conditions on the parameters are alpha > 0  0.
     |      
     |      The probability distribution function :
     |      
     |                  x ** (alpha - 1) * math.exp(-x / beta)
     |        pdf(x) =  --------------------------------------
     |                    math.gamma(alpha) * beta ** alpha
     |  
     |  gauss(self,mu,sigma)
     |      Gaussian distribution.
     |      
     |      mu is the mean,1)">and sigma is the standard deviation.  This is
     |      slightly faster than the normalvariate() function.
     |      
     |      Not thread-safe without a lock around calls.
     |  
     |  getstate(self)
     |      Return internal state; can be passed to setstate() later.
     |  
     |  lognormvariate(self,1)">      Log normal distribution.
     |      
     |      If you take the natural logarithm of this distribution,youll get a
     |      normal distribution with mean mu  standard deviation sigma.
     |      mu can have any value,1)"> sigma must be greater than zero.
     |  
     |  normalvariate(self,1)">      Normal distribution.
     |      
     |      mu  the standard deviation.
     |  
     |  paretovariate(self,alpha)
     |      Pareto distribution.  alpha  the shape parameter.
     |  
     |  randint(self,a,b)
     |      Return random integer  range [a,b],including both end points.
     |  
     |  randrange(self,start,stop=None,step=1,_int=<class int'>)
     |      Choose a random item  range(start,stop[,step]).
     |      
     |      This fixes the problem with randint() which includes the
     |      endpoint; in Python this is usually  what you want.
     |  
     |  sample(self,k)
     |      Chooses k unique random elements from a population sequence  set.
     |      
     |      Returns a new list containing elements from the population while
     |      leaving the original population unchanged.  The resulting list is
     |      in selection order so that all sub-slices will also be valid random
     |      samples.  This allows raffle winners (the sample) to be partitioned
     |      into grand prize  second place winners (the subslices).
     |      
     |      Members of the population need not be hashable  unique.  If the
     |      population contains repeats,then each occurrence  a possible
     |      selection  the sample.
     |      
     |      To choose a sample  a range of integers,use range as an argument.
     |      This is especially fast and space efficient for sampling  a
     |      large population:   sample(range(10000000),60)
     |  
     |  seed(self,a=None,version=2)
     |      Initialize internal state  hashable object.
     |      
     |      None or no argument seeds from current time or  an operating
     |      system specific randomness source  available.
     |      
     |      If *a*  an int,all bits are used.
     |      
     |      For version 2 (the default),all of the bits are used if *a*  a str,|      bytes,1)">or bytearray.  For version 1 (provided  reproducing random
     |      sequences from older versions of Python),the algorithm for str and
     |      bytes generates a narrower range of seeds.
     |  
     |  setstate(self,state)
     |      Restore internal state  object returned by getstate().
     |  
     |  shuffle(self,x,random=None)
     |      Shuffle list x in place,1)">return None.
     |      
     |      Optional argument random is a 0-argument function returning a
     |      random float in [0.0,1.0); if it  the default None,the
     |      standard random.random will be used.
     |  
     |  triangular(self,low=0.0,high=1.0,mode=      Triangular distribution.
     |      
     |      Continuous distribution bounded by given lower  upper limits,|      and having a given mode value in-between.
     |      
     |      http://en.wikipedia.org/wiki/Triangular_distribution
     |  
     |  uniform(self,b)
     |      Get a random number in the range [a,b)  [a,b] depending on rounding.
     |  
     |  vonmisesvariate(self,kappa)
     |      Circular data distribution.
     |      
     |      mu is the mean angle,expressed in radians between 0 and 2*pi,1)">and
     |      kappa is the concentration parameter,which must be greater than or
     |      equal to zero.  If kappa  equal to zero,this distribution reduces
     |      to a uniform random angle over the range 0 to 2*pi.
     |  
     |  weibullvariate(self,1)">      Weibull distribution.
     |      
     |      alpha is the scale parameter and beta  the shape parameter.
     |  
     |  ----------------------------------------------------------------------
     |  Class methods defined here:
     |  
     |  __init_subclass__(**kwargs)  builtins.type
     |      Control how subclasses generate random integers.
     |      
     |      The algorithm a subclass can use depends on the random() and/or
     |      getrandbits() implementation available to it  determines
     |      whether it can generate random integers  arbitrarily large
     |      ranges.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables ( defined)
     |  
     |  __weakref__
     |      list of weak references to the object ( defined)
     |  
     |  ----------------------------------------------------------------------
     |  Data  other attributes defined here:
     |  
     |  VERSION = 3
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited  _random.Random:
     |  
     |  __getattribute__(self,name,/      Return getattr(self,name).
     |  
     |  getrandbits(self,k,1)">)
     |      getrandbits(k) -> x.  Generates an int with k random bits.
     |  
     |  random(self,1)">)
     |      random() -> x in the interval [0,1).
     |  
     |  ----------------------------------------------------------------------
     |  Static methods inherited __new__(*args,**kwargs)  builtins.type
     |      Create return a new object.  See help(type)  accurate signature.
    
     SystemRandom(Random)
     |  SystemRandom(x=None)
     |  
     |  Alternate random number generator using sources provided
     |  by the operating system (such as /dev/urandom on Unix or
     |  CryptGenRandom on Windows).
     |  
     |   Not available on all systems (see os.urandom()  details).
     |  
     |      SystemRandom
     |  Methods defined here:
     |  
     |  getrandbits(self,k)
     |      getrandbits(k) -> x.  Generates an int with k random bits.
     |  
     |  getstate = _notimplemented(self,*args,**kwds)
     |  
     |  random(self)
     |      Get the next random number in the range [0.0,1.0).
     |  
     |  seed(self,1)">kwds)
     |      Stub method.  Not used  a system random number generator.
     |  
     |  setstate = _notimplemented(self,1)">kwds)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited  Random:
     |  
     |  )
     |  
     |  shuffle(self,1)"> the shape parameter.
     |  
     |  ----------------------------------------------------------------------
     |  Class methods inherited       ranges.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited and other attributes inherited  Random:
     |  
     |  VERSION = 3
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited  accurate signature.

FUNCTIONS
    betavariate(alpha,beta) method of Random instance
        Beta distribution.
        
        Conditions on the parameters are alpha > 0  0.
        Returned values range between 0 .
    
    choice(seq) method of Random instance
        Choose a random element empty sequence.
    
    choices(population,weights=None,1)">) method of Random instance
        Return a k sized list of population elements chosen with replacement.
        
        If the relative weights  divided by the desired mean.  It should be
        nonzero.  (The parameter would be called 
        a reserved word  0 to
        positive infinity  negative
        infinity to 0  negative.
    
    gammavariate(alpha,beta) method of Random instance
        Gamma distribution.  Not the gamma function!
        
        Conditions on the parameters are alpha > 0  0.
        
        The probability distribution function :
        
                    x ** (alpha - 1) * math.exp(-x / beta)
          pdf(x) =  --------------------------------------
                      math.gamma(alpha) * beta ** alpha
    
    gauss(mu,sigma) method of Random instance
        Gaussian distribution.
        
        mu 
        slightly faster than the normalvariate() function.
        
        Not thread-safe without a lock around calls.
    
    getrandbits(k,/) method of Random instance
        getrandbits(k) -> x.  Generates an int with k random bits.
    
    getstate() method of Random instance
        Return internal state; can be passed to setstate() later.
    
    lognormvariate(mu,sigma) method of Random instance
        Log normal distribution.
        
        If you take the natural logarithm of this distribution,youll get a
        normal distribution with mean mu  standard deviation sigma.
        mu can have any value,1)"> sigma must be greater than zero.
    
    normalvariate(mu,sigma) method of Random instance
        Normal distribution.
        
        mu  the standard deviation.
    
    paretovariate(alpha) method of Random instance
        Pareto distribution.  alpha  the shape parameter.
    
    randint(a,b) method of Random instance
        Return random integer ).
    
    randrange(start,stop=None,1)">) method of Random instance
        Choose a random item  what you want.
    
    sample(population,k) method of Random instance
        Chooses k unique random elements  set.
        
        Returns a new list containing elements while
        leaving the original population unchanged.  The resulting list is
        slices will also be valid random
        samples.  This allows raffle winners (the sample) to be partitioned
        into grand prize  second place winners (the subslices).
        
        Members of the population need  unique.  If the
        population contains repeats,then each occurrence  a possible
        selection  the sample.
        
        To choose a sample  a
        large population:   sample(range(10000000),1)">)
    
    seed(a=None,1)">) method of Random instance
        Initialize internal state  hashable object.
        
        None  an operating
        system specific randomness source  available.
        
        If *a*  reproducing random
        sequences 
        bytes generates a narrower range of seeds.
    
    setstate(state) method of Random instance
        Restore internal state  object returned by getstate().
    
    shuffle(x,random=None) method of Random instance
        Shuffle list x  None.
        
        Optional argument random argument function returning a
        random float None) method of Random instance
        Triangular distribution.
        
        Continuous distribution bounded by given lower between.
        
        http://en.wikipedia.org/wiki/Triangular_distribution
    
    uniform(a,b) method of Random instance
        Get a random number 
        kappa 
        equal to zero.  If kappa pi.
    
    weibullvariate(alpha,beta) method of Random instance
        Weibull distribution.
        
        alpha  the shape parameter.

DATA
    __all__ = [Random',seedrandomuniformrandintchoice'\lib\random.py


None

Process finished with exit code 0
View Code

那么接下来我们就来挨个看看

1. random.random() 随机产生一个0~1之内的小数

print(help(random.random))
print(random.random())  产生0 ~ 1 之间的小数

1 Help on built- function random:
2 
3 random() method of random.Random instance
4     random() -> x ).
5 
6 None
7 0.46211947242172047
View Code

2. random.randint(a,b)  随机产生一个在指定范围内的整数

(help(random.randint))
print(random.randint(0,8))  产生0 ~ 8的整数(包括 8 )

Help on method randint  module random:

randint(a,b) method of random.Random instance
    Return random integer View Code

3.random.randrange(a,b) 随机产生一个在指定范围内的整数

(help(random.randrange))
print(random.randrange(0,1)"> 产生0 ~ 8的整数(不包括 8 )

Help on method randrange  module random:

randrange(start,1)">) method of random.Random instance
    Choose a random item  what you want.

None
3

Process finished with exit code 0
View Code

但是这个与上者的区别可要注意看了,前者包括b,后者不包括b

我们通常大多数情况下基本会采用randrange(a,b)这种形式的

4.random.choice() 在所给序列里随机挑出一个随机数(字符)

(help(random.choice))
print(random.choice(21414'))  在所给序列里随机挑出一个随机数(字符)
qwqwfqcxws))
print(random.choice([1,2,3,[2,3],[5,6]]))

Help on method choice  module random:

choice(seq) method of random.Random instance
    Choose a random element empty sequence.

None
4
w
[5,6]
View Code

5.random.sample() 在所给序列里随机挑出指定个随机数(字符),并以列表形式返回

(help(random.sample))
print(random.sample(qeqrqwt 在所给序列里随机挑出自定义个随机数(字符)

Help on method sample  module random:

sample(population,k) method of random.Random instance
    Chooses k unique random elements  set.
    
    Returns a new list containing elements 
    leaving the original population unchanged.  The resulting list is
    slices will also be valid random
    samples.  This allows raffle winners (the sample) to be partitioned
    into grand prize  second place winners (the subslices).
    
    Members of the population need  unique.  If the
    population contains repeats,1)"> a possible
    selection  the sample.
    
    To choose a sample  a
    large population:   sample(range(10000000),1)">)

None
[qte']
View Code

6.random.shuffe() 将所给序列随机乱序,这要注意的一点就是它并没有返回值

(help(random.sample))
a=[1,4,5,6,[7,7,8,8]]
random.shuffle(a)  将所给序列随机乱序
print(a)

Help on method sample )

None
[6,1,8],5]
View Code

随机数模块我们便到此结束。

下面,我们可以使用上述知识来简单的写一个随机验证码的程序:

import random


 实现验证码的实现
def auth_code():
    code = ''
    for i in range(4):
        code_choice = [str(random.randint(0,9)),chr(random.randint(97,122))]  为了实现数字和字母的随机分布
        code += random.choice(code_choice)
     code

 string
 auth_code_2():
    code_choice = string.ascii_lowercase + string.digits
    code = random.sample(code_choice,4)
    code=''.join(code)
     auth_code_3():
    code = ):
        if i == random.randint(0,1)">):
            code += str(random.randint(0,9))
        else:
            code += chr(random.randint(97,122))
     code


(auth_code())

(auth_code_2())

print(auth_code_3())

 

相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...