import random num=input(‘请输入你要生成的手机号个数:‘) all_phone=[] with open(‘phones.txt‘,‘a+‘) as f: count = 0 while count<=int(num): start = ‘1891023‘ rand_num = str(random.randint(0, 9999)) new_number = rand_num.zfill(4) phone_num = start + new_number if phone_num not in all_phone: all_phone.append(phone_num) count += 1 for i in range(len(all_phone)): f.write(all_phone[i]+‘\n‘)
优化生成手机号小程序:
1、.zfill是字符串类型的方法所以要把随机数转成字符串才可以使用该方法;随机数不够4位补0补够4位;
2、把列表的值通过循环写下标的方式写入;