首先random函数并不是一个真正的随机数,而是根据随机数算法算出来的数
random 函数返回一个从 0.0 到 1.0 的随机浮点数 (包括 0.0, 但是不包括 1.0)。每次,调用 random,就会的到一个随机数。
- >>> import random
- >>> random.random()
- 0.9536935859948081
- >>> random.random()
- 0.40421571099356646
randint 函数接受一个 low 和 high 参数,返回 low 和 high 之间的一个整数 (包括两者)。
- >>> random.randint(5, 10)
- 5
- >>> random.randint(5, 10)
- 9
随机选取0到100间的偶数
>>> import random
>>> random.randrange(0, 101, 2)
42
要想随机地从一个序列中选取元素,可以使用 choice:
>>> t = [1, 2, 3]
>>> random.choice(t)
2
把原有的顺序打乱,按照随机顺序排列
- >>> import random
- >>> items = [1, 2, 3, 4, 5, 6]
- >>> random.shuffle(items)
- >>> items
- [3, 2, 5, 6, 4, 1]