>>> random.randrange(1,10) #返回1-10之間的一個隨機數,不包括10
>>> random.randint(1,10) #返回1-10之間的一個隨機數,包括10
>>> random.randrange(0, 100, 2) #隨機選取0到100間的偶數
>>> random.random() #返回一個隨機浮點數
>>> random.choice('abce3#$@1') #返回一個給定數據集合中的隨機字符
'#'
>>> random.sample('abcdefghij',3) #從多個字符中選取特定數量的字符
['a', 'd', 'b']
#生成隨機字符串
>>> import string
>>> ''.join(random.sample(string.ascii_lowercase + string.digits, 6))
'4fvda1'
#洗牌
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(a)
>>> a
[3, 0, 7, 2, 1, 6, 5, 8, 9, 4]
隨機驗證碼練習:
def rand_code(n=4,flag=True): code = '' for i in range(n): rand_num = str(random.randint(0,9)) # print(rand_number,type(rand_number)) if flag: rand_num1 = chr(random.randint(97,122)) # print(rand_number1,type(rand_number1)) rand_num2 = chr(random.randint(65,90)) # print(rand_number2,type(rand_number2)) rand_num = random.choice([rand_num,rand_num1,rand_num2]) code += rand_num return codeprint(rand_code(6))