1. 程式人生 > >自動生成手機號-優化

自動生成手機號-優化

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、把列表的值通過迴圈寫下標的方式寫入;