random随机模块
【1】随即小数
import random
res = random. random( )
print ( res)
res = random. uniform( 2 , 4 )
print ( res)
【2】随机整数
import random
res = random. randint( 1 , 2 )
print ( res)
res = random. randrange( 1 , 3 , 2 )
print ( res)
【3】随机选择返回
import randomchoice_list = [ "tom" , "lucy" , "kan" ]
res = random. choice( choice_list)
print ( res)
res = random. sample( choice_list, 2 )
print ( res)
res = random. choices( choice_list, weights= [ 3 , 2 , 1 ] , k= 2 )
print ( res)
【4】随机打乱列表顺序
import randomchoice_list = [ "tom" , "lucy" , "kan" ]
choice_set = { 1 , 2 , 3 , 4 }
choice_tuple = ( 1 , 2 )
res = random. shuffle( choice_list)
print ( res)
【5】应用(生成随机验证码)
import random
import stringdef generate_n_verify_code ( n) : choice_list = ( string. digits + string. ascii_uppercase + string. ascii_lowercase) verify_code_list = random. choices( choice_list, k= n) verify_code_str = "" . join( verify_code_list) return verify_code_strprint ( generate_n_verify_code( 4 ) )