# python随机数random模块详解及实例

“>

random 模块是python自带的模块，除了生成最简单的随机数以外，还有很多功能。

random.random()

>>> import random>>> random.random()0.5038461831828231

random.uniform(a,b)

>>> random.uniform(50,100)76.81733455677832>>> random.uniform(100,50)52.98730193316595

random.randint(a,b)

>>> random.randint(50,100)54>>> random.randint(100,50) traceback (most recent call last): file “”, line 1, in random.randint(100,50) file “c:\python27\lib\random.py”, line 242, in randint return self.randrange(a, b+1) file “c:\python27\lib\random.py”, line 218, in randrange raise valueerror, “empty range for randrange() (%d,%d, %d)” % (istart, istop, width)valueerror: empty range for randrange() (100,51, -49)>>> random.randint(50.5,100.6) traceback (most recent call last): file “”, line 1, in random.randint(50.5,100.6) file “c:\python27\lib\random.py”, line 242, in randint return self.randrange(a, b+1) file “c:\python27\lib\random.py”, line 187, in randrange raise valueerror, “non-integer arg 1 for randrange()”valueerror: non-integer arg 1 for randrange()

random.randrang([start], stop[, step])

>>> random.randrange(100)58>>> random.randrange(10,100,2)54

random.choice(sequence)

>>> random.choice((“stone”,”scissors”,”paper”))’stone’>>> random.choice([“stone”,”scissors”,”paper”])’scissors’>>> random.choice(“random”)’m’

random.shuffle(x[,random])

>>> poker = [“a”,”2″,”3″,”4″,”5″,”6″,”7″,”8″,”9″,”10″,”j”,”q”,”k”]>>> random.shuffle(poker)>>> poker[‘4′, ’10’, ‘8’, ‘3’, ‘j’, ‘6’, ‘2’, ‘7’, ‘9’, ‘q’, ‘5’, ‘k’, ‘a’]

random.sample(sequence,k)

>>> poker = [“a”,”2″,”3″,”4″,”5″,”6″,”7″,”8″,”9″,”10″,”j”,”q”,”k”]>>> random.sample(poker,5)[‘4’, ‘3’, ’10’, ‘2’, ‘q’]

Posted in 未分类