目录
- random.random
- random.uniform
- random.randint
- random.choice
- random.sample
- random.randrange
random.random
In [3]: print(random.random())
0.5227594997790331
In [4]: print(random.random())
0.02706197437697
random.uniform
In [5]: print(random.uniform(1,10))
6.697888509592069
In [6]: print(random.uniform(1,10))
8.507709945883843
random.randint
In [7]: print(random.randint(1,10))
4
In [8]: print(random.randint(1,10))
9
random.choice
In [9]: print(random.choice(['a', 'b', 'c']))
b
In [10]: print(random.choice(('a', 'b', 'c')))
a
In [11]: print(random.choice('abc'))
a
random.sample
In [12]: random.sample(['a', 'b', 'c'], 2)
Out[12]: ['c', 'a']
In [13]: random.sample('abcd', 3)
Out[13]: ['a', 'c', 'b']
random.randrange
- 获取区间内的一个随机数,相当于在
range 函数中使用random.choice 函数
In [14]: random.randrange(0, 100, 1)
Out[14]: 23
In [15]: random.choice(range(0, 100, 1))
Out[15]: 39
实战
import random
gifts = ['iphone', 'ipad', 'car', 'tv']
def choice_gifts():
gift = random.choice(gifts)
print('你得到了%s' % gift)
def choice_gifts_new():
count = random.randrange(0, 100, 1)
if 0 <= count <= 50:
print('你中了一个iPhone')
elif 50 < count <= 70:
print('你中了一个ipad')
elif 70 < count <= 90:
print('你中了一个tv电视')
elif count > 90:
print('恭喜你中了一辆小汽车')
if __name__ == '__main__':
choice_gifts_new()
你中了一个ipad
Process finished with exit code 0
|