import random
随机 : 在某个范围内取到每一个值的概率是相同的
0-1之内的随机小数
import random
print(random.random())
任意范围内的随机小数
import random
print(random.uniform(1,5))
随机整数
import random
print(random.randint(1,2)) #[1,2]包含2在内的范围内随机取整数
import random
print(random.randrange(1,2)) #[1,2)不包含2在内的范围内随机取整数
import random
print(random.randrange(1,10,2))# [1,10)不包含10在内的范围内随机取奇数
随机抽取一个值
import random
lst=[1,2,3,4,"aaa",("a","b")]
ret=random.choice(lst)
print(ret)
随机抽取多个值
import random
lst=[1,2,3,4,"aaa",("a","b")]
ret=random.sample(lst,2)
print(ret)
打乱顺序
import random
lst=[1,2,3,4,"aaa",("a","b")]
random.shuffle(lst)
print(lst)
生成随机验证码
4位数字
import random
s=""
for i in range(4):
num=random.randint(0,9)
s=s+str(num)
print(s)
函数:
import random
def func(n=4):
s=""
for i in range(n):
num=random.randint(0,9)
s=s+str(num)
return s
print(func())
print(func(6))
6位,数字加字母
import random
s=""
for i in range(6):
num=random.randint(0,9)
num1=chr(random.randint(97,122))
num2=chr(random.randint(65,90))
a=random.choice([num,num1,num2])
s+=str(a)
print(s)
函数
import random
def func(n=6):
s = ""
for i in range(6):
num = random.randint(0, 9)
num1 = chr(random.randint(97, 122))
num2 = chr(random.randint(65, 90))
a = random.choice([num, num1, num2])
s += str(a)
return s
ret=func()
print(ret)
数字/数字+字母
import random
def func(n=6,alph_flag=True):
s = ""
for i in range(6):
num = random.randint(0, 9)
if alph_flag:
num1 = chr(random.randint(97, 122))
num2 = chr(random.randint(65, 90))
num = random.choice([num, num1, num2])
s += str(num)
return s
ret=func()
print(ret)
import random
def func(n=6,alph_flag=True):
s = ""
for i in range(n):
num = str(random.randint(0, 9))
if alph_flag:
num1 = chr(random.randint(97, 122))
num2 = chr(random.randint(65, 90))
num = random.choice([num, num1, num2])
s += num
return s
ret=func(n=6,alph_flag=False)
print(ret)
import random
def func(n=6,alph_flag=True):
s = ""
for i in range(n):
num = str(random.randint(0, 9))
if alph_flag:
num1 = chr(random.randint(97, 122))
num2 = chr(random.randint(65, 90))
num = random.choice([num, num1, num2])
s += num
return s
ret=func(n=4)
print(ret)