python------模塊定義、導入、優化 ------->random模塊


2.random模塊

#隨機浮點數

 random.random()   #生成0到1之間的隨機浮點數,不能自己指定

random.uniform(1,10)   #可以指定

 

#隨機整數

random.randint(1,7)   #生成1到7之間的隨機整數1<=n<=7

 

#隨機選取0到100間的偶數:

 random.randrange(0,101,2)    #生成隨機整數  

 

#隨機字符

random.choice('')       #傳的是一個序列(包括字符串,元組,列表)

 

#多個字符中選取特定數量的字符

random.sample(‘序列’,長度)  

 

#洗牌

random.shuffle([1,2,3,4,5,6,7,8,9])

 

例子:

1 #4位純數字的驗證碼
2 import random 3 checkcode=''
4 for i in range(4): 5     current=random.randint(1,9) 6     checkcode+=str(current) 7 print(checkcode)
 1 #數字加字母的驗證碼
 2 import random  3 checkcode=''
 4 for i in range(4):  5     current=random.randrange(0,4)  6     if current == i :  7         temp = chr(random.randint(65,90))  8     else:  9         temp = random.randint(0,9) 10     checkcode+=str(temp) 11 print(checkcode)


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM