1. 程式人生 > >python常用模塊之random

python常用模塊之random

隨機 int() ice python .sh 產生 aps shuf 個數

一、random的作用

random模塊是一個跟取隨機值相關的模塊,主要用於類似抽獎、驗證碼等場景

二、常用方法

random.random():產生一個0-1之間的隨機數

print(random.random())
--------------------------------------------------------------------------------------
0.13955850706432626

random.randint():產生一個指定範圍的隨機整數,這個範圍是一個閉區間

print(random.randint(1,5))
--------------------------------------------------------------------------------------
5

random.choice():返回指定序列中一個的隨機值

print(random.choice([1,2,‘a‘,‘b‘])) 
--------------------------------------------------------------------------------------
a

random.sample():返回指定序列中指定個數的隨機值

print(random.sample([‘a‘,‘b‘,‘c‘,1,2,3],2))
--------------------------------------------------------------------------------------
[‘b‘, 2]

random.shulffe():用於打亂列表中的元素排列順序

li=[1,2,3]
random.shuffle(li)
print(li)
--------------------------------------------------------------------------------------
[1, 3, 2]

三、驗證碼練習

技術分享 View Code

python常用模塊之random