一、Random 模块
- 注意:random() 是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法。
1.random.random()
- 返回随机生成的一个 [0,1) 范围内的实数
import random
print (random.random())
--> 0.112499651779
2.random.randint(x,y)
- 随机生成 [x,y] 范围内的整数
import random
print (random.randint(1,2))
--> 2
#10内相加计算
import random
a = random.randint(1,10)
b = random.randint(1,10)
c = input(str(a) + "+" + str(b) + "=")
if int(c) == a+b:
print ("答案正确!")
else:
print ("答案错误!")
3.random.randrange(a,b,step)
- 随机生成一个 [a,b) 之间的一个整数,可以定义 step 步长
- 与range()用法类似
import random
print (random.randrange(3))
print (random.randrange(1,2))
print (random.randrange(1,6,2))
4.random.uniform(a,b)
- 返回 [a,b] 内的一个浮点数
import random
print (random.uniform(1,2))
import random
a = "xfs"
print (random.choice(a))
b = [1,2,3]
print (random.choice(b))
"""
#随机生成学员姓名
student = ['张三','李四','王五',]
print (random.choice(student))
"""
#实现3次抽奖,且每人只能抽中一次
import random
stu = ["zhangsan","lisi","wangwu","zhaoliu","niuqi"]
"""
#方案一
for i in range(3):
print (stu.pop(random.choice(range(len(stu)))))
"""
"""
#方案二
for i in range(3):
print (stu.pop(stu.index(random.choice(stu))))
"""
import random
"""
#随机删除列表中一个字符串,直至列表清空
box = ["a","b","c","d","e","f"]
for i in range(len(box)):
ball = random.choice(range(len(box)))
del box[ball]
print (box)
"""
"""
#随机生成手机号一
def phone():
a = ["136","177","186","131"]
return random.choice(a)+"".join(random.choice("0123456789")
for i in range(8))
"""
"""
#随机生成手机号二
def phone():
number = ["138","156","130","177"]
return random.choice(number)+str(random.randint(9999999,99999999))
"""
"""
#随机生成手机号三
def phone():
number = ["138","156","130","177"]
return random.choice(number) + str(random.uniform(1,2))[2:10]
"""
"""
#福利彩票生成
num = ["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']
for i in range(7):
num1 = num.pop(random.randint(0,len(num)-1))
if i == 0:
num2 = num1
elif i == 1:
num3 = num1
elif i == 2:
num4 = num1
elif i == 3:
num5 = num1
elif i == 4:
num6 = num1
elif i == 5:
num7 = num1
elif i == 6:
num8 = num1
print (num2+" "+num3+" "+num4+" "+num5+" "+num6+" "+num7+" "+num8)
"""