import random
# print(random.random()) # 隨機浮點數,默認取0-1,不能指定范圍
# print(random.randint(1, 20)) # 隨機整數,顧頭顧尾
# print(random.choice('sdfsd233')) # 隨機取一個元素
# print(random.sample('hello234234史蒂夫34', 4))#從序列中隨機取幾個元素,返回是一個list
# f =random.uniform(1, 9) # 隨機取浮點數,可以指定范圍
# x = [1, 2, 3, 4, 6, 7]
# random.shuffle(x) # 洗牌,打亂順序,會改變原list的值
# print(x)
利用隨機數生成11位手機號
import string def phone_num(num): all_phone_nums=set() num_start = ['134', '135', '136', '137', '138', '139', '150', '151', '152', '158', '159', '157', '182', '187', '188', '147', '130', '131', '132', '155', '156', '185', '186', '133', '153', '180', '189'] for i in range(num): start = random.choice(num_start) end = ''.join(random.sample(string.digits,8)) res = start+end+'\n' all_phone_nums.add(res) with open('phone_num.txt','w',encoding='utf-8') as fw: fw.writelines(all_phone_nums) phone_num(1000)