使用random随机数要导入模块:
import random
该模块的常用方法有:
random
# 返回[0,1)之间的随机浮点数for num in range(0, 3): result = random.random() print(result)'''0.4533819183090.7869565531470.180587982868'''
randint(m,n)
# 返回[m,n]之间的随机整数,注意 m <= nfor num in range(0, 3): result = random.randint(1, 10) print(result)'''4108'''
randrange(i, j, m)
# 返回 i 到 j 之间间隔为 m 的随机整数for num in range(0, 3): result = random.randrange(1, 100, 2) print(result)'''438177'''
uniform(m,n)
# 返回m到n之间的随机浮点数for num in range(0, 3): result = random.uniform(1.1, 5.4) print(result)'''1.865089962534.093622142545.30874741462'''
choice(tab)
# 返回从序列tab中随机选取一个元素strTab = ['one', 'two', 'three', 'four', 'five']for num in range(0, 3): result = random.choice(strTab) print(result)'''onefourtwo'''
shuffle(tab)
# 将序列中的元素顺序打乱numTab = [1, 3, 5, 6, 7]newnumTab = random.shuffle(numTab) random.shuffle(numTab)print(newnumTab) # 无返回,故为Noneprint(numTab) # [3, 5, 6, 1, 7]
生成随机数11位手机号码的小Demo:
# -*- coding:utf-8 -*-# __author__ = 'Code~'import random'''随机生成有效的11位手机号码,简要说明下:前三位: 网络识别号,比如移动,联通,电信,号码区段如下: 电信:133,149,153,173,177,180,181,189,191,199 联通:130,131,132,145,155,156,166,171,175,176,185,186 移动:134,135,136,137,138,139,147,150,151,152,157,158,159,172,178,182,183,184,187,188,198中间四位: 地区编码,每位的范围为[0,9]最后四位:MDN号码,即用户被叫时,主叫用户所需拨打的号码,每位的范围为[0,9]摘自:'''# 网络识别号列表identyList = [ # 电信 [133,149,153,173,177,180,181,189,191,199], # 联通 [130,131,132,145,155,156,166,171,175,176,185,186], # 移动 [134,135,136,137,138,139,147,150,151,152,157,158,159,172,178,182,183,184,187,188,198],]# 生成随机号码,count为生成的个数def createRandPhone(count=10): # 获取前三位的随机索引 randIndex = random.randint(0, len(identyList)-1) # 随机号码生成个数 for _ in range(0, count): firstStr = str(random.choice(identyList[randIndex])) lastStr = '' # 获取后八位随机字符 for i in range(0, 8): lastStr = lastStr + random.choice("0123456789") print(u'随机手机号为: ' + firstStr + lastStr)createRandPhone(5)输出:随机手机号为: 18264939118随机手机号为: 18814309809随机手机号为: 17898265918随机手机号为: 18845063333随机手机号为: 18251223696