使用
随机小数
import random
print(random.random()) # 0.33630703804107664 大于0且小于1之间的小数
print(random.uniform(1, 3)) # 2.0639651365332607 大于1小于3的小数
随机整数
import random
print(random.randint(1,5)) # 2 大于等于1且小于等于5之间的整数
print(random.randrange(1,10,2)) # 1 大于等于1且小于10之间的奇数
随机选择返回
import random
# 随机选择一个返回
print(random.choice([1, '23', [4, 5]])) # 23
# 随机选择多个返回,返回的个数为函数的第二个参数
print(random.sample([1, '23', [4, 5]], 2)) # ['23', [4, 5]]
随机打乱次序
import random
item = [1, 2, 3, 4, 5]
random.shuffle(item) # 打乱次序
print(item) # [4, 2, 5, 3, 1]
示例
生成随机验证码字符串
import random
def v_code():
code = ''
for i in range(5):
num = random.randint(0, 9)
alf = chr(random.randint(65, 90))
add = random.choice([num, alf])
code = "".join([code, str(add)])
return code
print(v_code())
评论区