python模块-random

1.random模块

import random

number = random.randint(1,10) #整数
f = random.uniform(1,100)#随机的小数
# print(round(f,2))
l = [1,2,3,4,23,23,52,32,632,362,362,36,2362]
s = 'gslkjlk2352525'
print(random.sample(s,2)) #随机选择n个元素
print(random.choice(s)) #随机选择1个元素

random.shuffle(l) #洗牌,没有返回值,它会改变传入list的值
print(l)

2.小练习

#账号和密码
#账号,必须包含字母和数字,长度在6-12之间
#密码,必须包含大小写字母、数字、特殊符号,长度在8-12之间
#输入几,就产生几条,并且用户名不能重复

import string,random
number = input("请输入产生数据的条数:").strip()
if number.isdigit():
    number = int(number)
else:
    print("请输入整数!")

def check_username(username):
    return set(username) & set(string.ascii_letters) and set(username) & set(string.digits)

def check_password(password):
    return set(password) & set(string.ascii_uppercase) and set(password) &  \
    set(string.ascii_lowercase) and set(password) & set(string.digits) and \
    set(password) & set(string.punctuation)

l = {}

count = 0
while count<number:#1、2
    username_length = random.randint(6,12)
    username_list = random.sample(string.ascii_letters
                                  +string.digits,username_length)
    if check_username(username_list):
        username = ''.join(username_list)
    else:
        continue

    password_length = random.randint(8,12)
    password_list = random.sample(string.ascii_letters
                                  +string.digits+string.punctuation,password_length)
    if check_password(password_list):
        password = ''.join(password_list)
    else:
        continue

    if username not in l:
        count+=1
        l[username] = password

print(l)

 

posted @ 2021-01-10 22:47  chenghuahua  阅读(70)  评论(0编辑  收藏  举报