random 及 账号生成代码练习

1. 取随机数  random 

 1 import random
 2 
 3 user = random.randint(1,10) #整数
 4 y = random.uniform(1,100)#随机的小数
 5 # print(round(f,2))
 6 x = [159,753,8,5,2,5,6,96,6,3,36]
 7 z = 'duhdhud8huidj5959562596'
 8 print(random.sample(z,2)) #随机选择n个元素
 9 print("==========================")
10 print(random.choice(z)) #随机选择1个元素
11 print("==========================")
12 random.shuffle(x) #洗牌,没有返回值,它会改变传入list的值
13 print(x)

2. 账号密码生成器

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

 1 import string,random
 2 number = input("请输入产生数据的条数:").strip()
 3 if number.isdigit():
 4     number = int(number)
 5 else:
 6     print("请输入整数!")
 7 
 8 def check_username(username):
 9     return set(username) & set(string.ascii_letters) and set(username) & set(string.digits)
10 
11 def check_password(password):
12     return set(password) & set(string.ascii_uppercase) and set(password) &  
13     set(string.ascii_lowercase) and set(password) & set(string.digits) and 
14     set(password) & set(string.punctuation)
15 
16 l = {}
17 
18 count = 0
19 while count<number:#1、2
20     username_length = random.randint(6,12)
21     username_list = random.sample(string.ascii_letters
22                                   +string.digits,username_length)
23     if check_username(username_list):
24         username = ''.join(username_list)
25     else:
26         continue
27 
28     password_length = random.randint(8,12)
29     password_list = random.sample(string.ascii_letters
30                                   +string.digits+string.punctuation,password_length)
31     if check_password(password_list):
32         password = ''.join(password_list)
33     else:
34         continue
35 
36     if username not in l:
37         count+=1
38         l[username] = password
39 
40 print(l)
原文地址:https://www.cnblogs.com/huajie-chj/p/14276622.html