Python简单生成随机数的方法示例

时间:2022-10-21 15:47:28

本文实例讲述了Python简单生成随机数的方法。分享给大家供大家参考,具体如下:

主要知识点:

随机整数:

random.randint(a,b):返回随机整数x,a<=x<=b

包含范围的随机整数

random.randrange(start,stop,[,step]):返回一个范围在(start,stop,step)之间的随机整数,不包括结束值。

0-1之间的随机浮点数

随机实数:random.random():返回0到1之间的浮点数

指定范围的随机浮点数

random.uniform(a,b):返回指定范围内的浮点数。

实战演示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
Microsoft Windows [版本 6.1.7601]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。
C:\Users\Administrator>python
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (
AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> print random.randint(1,3)
2
>>> print random.randint(1,3)
1
>>> print random.randint(1,3)
2
>>> print random.randint(1,3)
2
>>> print random.randint(1,10)
1
>>> print random.randint(1,10)
10
>>> print random.randint(1,10)
5
>>> print random.randint(1,10)
1
>>> print random.randint(1,10)
5
>>> print random.randint(1,10)
7
>>> print random.randint(1,10)
4
>>> print random.randint(1,10)
3
>>> print random.randrange(1,5,1)
2
>>> print random.randrange(1,5,1)
4
>>> print random.randrange(1,5,1)
4
>>> print random.randrange(1,5,1)
4
>>> print random.randrange(1,5,1)
3
>>> print random.randrange(1,5,1)
1
>>> print random.randrange(1,5,1)
3
>>> print random.randrange(1,5,1)
1
>>> print random.randrange(1,5,1)
1
>>> print random.randrange(1,5,1)
2
>>> print random.randrange(1,5,1)
1
>>> print random.randrange(1,5,1)
1
>>> print random.randrange(1,5,1)
4
>>> print random.random()
0.395644101608
>>> print random.random()
0.939752210993
>>> print random.random()
0.753840174814
>>> print random.random()
0.6284505895
>>> print random.random()
0.221124079082
>>> print random.random()
0.859997827515
>>> print random.uniform(3,5)
3.68718533467
>>> print random.uniform(3,5)
3.44178711732
>>> print random.uniform(3,5)
3.66400073252
>>> print random.uniform(3,5)
4.90505268541
>>> print random.uniform(3,5)
4.69546962717
>>> print random.uniform(3,5)
4.26153330638
>>>

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/u013421629/article/details/79148854