练习1: 随机产生注册用账号
需求:
产生的账号是以@163.com结尾,长度由用户输入,产生多少条也由用户输入,用户名不能重复,用户名必须由大写字母、小写字母、数字组成
import random,string def gen_username(): endwith = '@163.com' success_username =0 duplicate_flag = 0 # 密码是否重复 duplicate_num = 0 # 重复的次数 with open('usernamefile.txt', 'w') as fnew: # 没有文件的话新建,已有会清空 pass username_len = int(input('请输入用户名的长度:').strip()) #接收的为字符,需要转为int username_num = int(input('请输入产生账号的条数:').strip()) while username_len <4: print('用户名必须由大写、小写、数字组成,长度必须大于3,请重新输入:') username_len = int(input('请输入用户名的长度:').strip()) else: while success_username < username_num: username_list = [] upper_name = random.choice(string.ascii_uppercase) lower_name = random.choice(string.ascii_lowercase) username_list.append(upper_name) username_list.append(lower_name) for digit_num in range(username_len-2): digit_name = random.randint(0,9) username_list.append(str(digit_name)) #要用到list 的join方法,list中的每个元素需为字符串 digit_name +=1 random.shuffle(username_list) #打乱顺序 username = ''.join(username_list) + endwith with open('usernamefile.txt','r') as f_dup: for line in f_dup: if username == line: duplicate_flag = 1 duplicate_num = duplicate_num + 1 if duplicate_flag ==0: #没有和文件里已有的用户名重复则写入 with open('usernamefile.txt','a+') as f_write: f_write.write(username) f_write.write('\n') success_username += 1 else: print("用户名生成完成,重复次数 %d" % duplicate_num) gen_username()