綜合前幾天所學的內容,這裡實作了一個專題-密碼產生器。在這個專題中,我們運用了變數、串列、for迴圈、random模組等概念,讓使用者可以從數字、符號、英文字母中指定字元的數目,隨機生成一串密碼。
首先,先載入random模組。
# import random module
import random
利用串列定義出隨機密碼的候選字元,在這裡設定了三組集合,分別是數字0~9、特殊符號、以及英文大小寫字母。
# define characters used in password
numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
symbols = ["~", "!", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+"]
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
接著,我們讓使用者輸入在每組字元的集合中,各選出需要幾個字元來隨機組合出密碼。
# input password combination
print("Password Generator")
num_numbers = int(input("How many numbers would you like in your password?\n"))
num_symbols = int(input("How many symbols would you like in your password?\n"))
num_letters = int(input("How many letters would you like in your password?\n"))
定義一個空的串列password_list,並從各個集合中利用random.choice()隨機取出指定個數的字元,逐步加到這個串列中。
# randomly choose characters
password_list = []
for number in range(1, num_numbers + 1):
password_list += random.choice(numbers)
for symbol in range(1, num_symbols + 1):
password_list += random.choice(symbols)
for letter in range(1, num_letters + 1):
password_list += random.choice(letters)
此時,雖然需要的字元已經隨機被取出,但password_list中仍是相同類型的字元緊鄰在一起,前段是數字、中段是特殊符號、後段是英文字母,因此我們必須再做一次「洗牌」的動作,才能讓密碼的排列真正變成隨機。
# shuffle the password_list
random.shuffle(password_list)
最後,將串列的內容處理一下變成字串印出。
# turn the password list into string
password = ""
for password_char in password_list:
password += password_char
print(password)
以下是執行結果:
Password Generator
How many numbers would you like in your password?
3
How many symbols would you like in your password?
4
How many letters would you like in your password?
5
0W^qt^9_4)ki
程式範例