random模块基本使用
import random
a = random.random() #随机0-1浮点数
b = random.randint(1,7) #随机整数,1、7都能随机到
c = random.choice('kkkkssff') #随机序列类型如字符串或列表、或元组中的某个值
d = random.sample('hello',2) #随机序列类型如字符串或列表、或元组中的某区间值
e = random.uniform(1,3) #指定区间的浮点数
items = [1,2,3,4,5,6]
f = random.shuffle(items) #将有序列表顺序打乱
print('随机0-1浮点数:random.random()--> ',a)
print('随机整数:random.randint(1,7)--> ',b)
print('随机字符串或列表、或元组中的某个值:random.choice("kkkkssff")--> ',c)
print('随机序列类型如字符串或列表、或元组中的某区间值:random.sample("hello",2)--> ',d)
print('指定区间的浮点数:random.uniform(1,3)--> ',e)
print('将有序列表顺序打乱:random.shuffle([1,2,3,4,5,6])--> ',items)
随机0-1浮点数:random.random()--> 0.6411443673066869
随机整数:random.randint(1,7)--> 6
随机字符串或列表、或元组中的某个值:random.choice("kkkkssff")--> f
随机序列类型如字符串或列表、或元组中的某区间值:random.sample("hello",2)--> ['h', 'o']
指定区间的浮点数:random.uniform(1,3)--> 2.1752091111168035
将有序列表顺序打乱:random.shuffle([1,2,3,4,5,6])--> [5, 3, 1, 2, 6, 4]
小练习:生成4位只含有大写字母及数字的校验码
def getcode():
checkcode = ''
for i in range(4):
current = random.randrange(0,4) #只取0,1,2,3
if current == i:
tem = chr(random.randint(65,90)) #65和90均能取到,chr(65)转换为大写字母
else:
tem = random.randint(0,9)
checkcode += str(tem)
if checkcode.isdigit() or checkcode.isalpha():
code = getcode()
return code
else:
return checkcode
code = getcode()
print(code)
网友评论