和老黄一起学Python

Python 随机数 random模块

2017-02-06  本文已影响1226人  老黄爱Python

随机数是由程序随即产生的数字,常见的图片验证码,12306的图片验证等,这节我们来认识Python中的随机数模块。

import random

随机数模块常用方法:

>>> import random
>>> random.randint(0, 10)
8
>>> random.randint(0, 10)
7
>>> random.randint(0, 10)
10
>>> 
>>> random.random()
0.8836361984681352
>>> random.random()
0.013648077769505496
>>> random.random()
0.7267135453127417
>>> 
>>> s = 'helloWorld'
>>> random.choice(s)
'o'
>>> random.choice(s)
'r'
>>> random.sample('12345', 2)
['1', '2']
>>> random.sample('12345', 5)
['2', '1', '3', '4', '5']
>>> random.sample('12345', 6)    #k值超出population范围导致程序异常
Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    random.sample('12345', 6)
  File "D:\python36\lib\random.py", line 317, in sample
    raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative
>>> 
>>> s = 'helloWorld'
>>> random.uniform(1,10)
1.9304756617571137
>>> random.uniform(10, 1)
2.872422460231057
>>> 
>>> random.randrange(1, 10, 1)   #[1,10)之间随机整数
5
>>> random.randrange(1, 10, 1)
2
>>> random.randrange(1, 100, 2)  #[1, 100)之间随机奇数
33
>>> random.randrange(1, 100, 2)
5
>>> l = ['C', 'C++', 'Java', 'C#', 'Python']
>>> random.shuffle(l)
>>> l
['C++', 'C', 'Java', 'C#', 'Python']
>>> random.shuffle(l)
>>> l
['C', 'Python', 'C++', 'C#', 'Java']
>>> 

随机数常用的方法就介绍到这里,后面章节中我们会随机数完成一些常见功能,希望大家继续关注。

上一篇下一篇

猜你喜欢

热点阅读