import random
random.seed(100)#选择随机数种子,只要种子相同,每次产生的随机数相同
a = random.random()#生成0-1之间的小数print(a)
b = random.randint(10,100)#生成10-100之间的随机整数print(b)
c = random.randrange(10,100,10)#生成10-100之间,以10为步长的随机整数print(c)
d = random.getrandbits(4)#生成一个4比特长的随机整数print(d)
e = random.uniform(10,100)#生成一个10-100之间的随机小数print(e)
s =[1,2,3,4,5,6,7,8,9,0]
f = random.choice(s)#从s序列中随机选择一个元素print(f)
random.shuffle(s)#打乱s print(s)
二、实例
#圆周率计算from random import random #直接引入函数,节省代码from time import perf_counter
dar =10000*10000
hits =0.0
start = perf_counter()for i inrange(1,dar +1):
x, y = random(), random()#x,y的值为0-1
dist =pow(x **2+ y **2,0.5)if dist <=1.0:
hits +=1
pi =4*(hits / dar)print('圆周率为:{}'.format(pi))print('运行时间为:{:.5f}s'.format(perf_counter()- start))
圆周率为:3.14156572
运行时间为:100.58975s