標籤:must 字母 code not before cal choice 隨機產生數字 inspect
#!/usr/bin/python
#-*- encoding:UTF-8 -*-
#date:20180516
random模組的方法:隨機產生想要的數字、字母等
‘‘‘隨機函數,random產生的只能是數,不是可迭代對象沒有方法.__iter__()‘‘‘import random#隨機產生數字a = random.random() #隨機產生0到1中間的小數a = random.randint(1,3) #隨機產生[1,3]1到3三個數的任意一個,兩個參數必須寫,單獨寫一個報錯TypeError: randint() missing 1 required positional argument: ‘b‘a = random.randrange(3) #隨機產生(0,2]三個數的任意一個a = random.choice([1,3,3,[33,44,]]) #隨機顯示序列中的元素a = random.uniform(1,3) #隨機產生實數(整數、小數、無限迴圈小數)
list_t = [1,3,4,‘sigle‘,5]
a = random.sample(list_t,2)#從指定序列中擷取指定長度的個數,即從list_t中隨機拿出2個元素
a = random.suffle(list_t)#將指定序列中的元素隨機打亂print(a)‘‘‘練習:4位包含字母數字驗證碼的生產思路:1、需要4位驗證碼且是隨機的即項目要求通過運算最後返回一個4位的字串2、4位驗證碼的每一位都需要是隨機的,且應在包含有所有數字及字元的序列中選擇3、故需先要產生帶有所有數字及字母的序列,然後從中選4次,拼接成一個4位字串4、隨機播放參數需要用到模組random模組‘‘‘import randomdef verify_fun(): # while True: verify = ‘‘#建立一個空的字串,當拼接成4位的字串返回,即實現需求 for i in range(1,5): #迴圈4次,此處如用random.randint會報錯不是可迭代的對象 ver_num = random.randint(0,9)#隨機產生0,9中任一數字 # ver_num = chr(random.randint(48,57))##ASCII碼錶中48~57分別表示0~9 ver_upper = chr(random.randint(65,90))#ASCII碼錶中65~90分別表示a~z,通過chr(a)可將數字轉換成對應字母 ver_lower = chr(random.randint(97,122))#ASCII碼錶中97~122分別表示A~Z choic_table = [ver_num,ver_lower,ver_upper]#產生一個帶有數字和字母的列表 single_str = str(random.choice(choic_table)) verify += single_str #連續遞加拼接,產生目標字串 return verify#verify是全域變數,如果在前面將verify放到for裡面就是局部變數,如果在for外調用,只會得到一個數,因為每次迴圈,開始都會將verify上次的值重新賦值為空白。
#如果return放到for裡面就會執行一次就結束,因為函數中一遇到return函數就會結束,不再運行
print(verify_fun())
註:
1、字串拼接只能是字串與字串,single_str拼接時它必須是字串類型才行: TypeError: must be str, not int
2、局部變數的含義,當變數verify在for裡時,在for外調用verfiy變數會報如下錯誤:Local variable ‘verify‘ might be referenced before assignment less... (Ctrl+F1)
This inspection warns about local variables referenced before assignment.
Python學習_random模組使用