首页 > 代码库 > day6 random随机数模块

day6 random随机数模块

    random

    我们经常看到网站的随机验证码,这些都是由随机数生成的,因此我们需要了解一下随机数的模块。如何生成随机数。

    random 生成随机数

    random.random()    生成0-1之间的小数

    >>> import random
  >>> random.random()
  0.7386445925394346

    random.randint(1,3)    生成1-3之间的整数随机数

    >>> random.randint(1,5)
  4
  >>> random.randint(1,5)
  5

    randrange(self,start,stop=None,step=1,_int=int)    def randrange(self, start, stop=None, step=1, _int=int):
    """Choose a random item from range(start, stop[, step]).

    This fixes the problem with randint() which includes the
    endpoint; in Python this is usually not what you want.

    """

    # This code is a bit messy to make it fast for the
    # common case while still doing adequate error checking.

    randrange(self,start,stop,sep)生成随机数,可以定义步长。

    >>> random.randrange(1,9,2)
  3
  >>> random.randrange(1,8,2)
  1
  >>> random.randrange(1,8,2)
  3
    生成5位随机数,例:

    >>> random_num = random.randint(10000,99999)
  >>> random_num
  90821

    方法二:

    import random
  nums = []
  for i in range(5):
    if i == random.randint(1,5):
      nums.append(str(i))
    else:
      nums.append(chr(random.randint(65,90)))
  else:
    print("".join(nums))

    运行结果如下:

    CU23M

day6 random随机数模块