#Password Generator Project
import random
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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', ' ']
print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
#Eazy Level - Order not randomised:
#e.g. 4 letter, 2 symbol, 2 number = JduE&!91
def my_function():
for i in range(1,nr_letters 1):
variable=random.choice(letters)
print(variable, end='')
for j in range(1,nr_symbols 1):
variable1=random.choice(symbols)
print(variable1, end='')
for k in range(1,nr_numbers 1):
variable2=random.choice(numbers)
print(variable2, end='')
#Hard Level - Order of characters randomised:
#e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P
#my_function()
function_to_list=my_function()
print[(function_to_list)]
shuffle_my_function=random.shuffle(function_to_list)
print(shuffle_my_function)
這是一種個人專案,我的任務是生成密碼。在簡單的級別上,只需明智地列印密碼序列,而在困難的級別上,我希望我的密碼被打亂。我的簡單級別代碼運行良好,但在困難級別上,我想改組簡單級別的結果,因為我認為如果我定義簡單部分的函式,然后以某種方式將該函式轉換為我可以輕松使用的串列洗牌功能。所以請幫助我。請嘗試以我的思維方式給出解決方案,然后請提出您的解決方案
uj5u.com熱心網友回復:
這是一個常見的初學者問題。當您列印某些內容時,它會出現在螢屏上,但只是作為文本。并且程式看不到該文本。你必須對變數做一些事情來隨時跟蹤它們。在這種情況下,您需要將它們附加到串列中。不僅如此,您還需要將串列回傳給呼叫者,以便function_to_list = my_function()分配除Noneto以外的其他內容function_to_list:
def my_function():
list_of_characters = []
for i in range(nr_letters):
list_of_characters.append(random.choice(letters))
for j in range(nr_symbols):
list_of_characters.append(random.choice(symbols))
for k in range(nr_numbers):
list_of_characters.append(random.choice(numbers))
return list_of_characters
請注意,我取出了列印陳述句。那是因為一個函式應該只做一件事并且把它做好。您可以在取回串列和密碼后立即列印它們:
list_from_function = my_function()
print(list_from_function)
要將串列列印為單個字串,請將其包含的字母與 emtpy 字串連接:
print(''.join(list_from_function))
你可以隨機播放結果,或者做任何你想做的事情:
random.shuffle(list_from_function)
print(list_from_function)
請記住,shuffle操作到位并回傳None。這意味著如果您嘗試列印它的回傳值,您將一無所獲。
uj5u.com熱心網友回復:
你不需要使用for loop. 您可以傳遞引數來random.choices()指示您想要多少專案。
import random
# For demo, I hardcoded the numbers
nr_letters = 4
nr_symbols = 5
nr_numbers = 3
# create a list from randomly choosen characters
password_characters = random.choices(letters, k = nr_letters) \
random.choices(symbols, k = nr_symbols) \
random.choices(numbers, k = nr_numbers)
# shuffle the list:
random.shuffle(password_characters)
# convert the list to string
password = ''.join(password_characters)
輸出:
>>> print(password)
>>> &J0*4oR!I3$!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/486718.html
上一篇:迭代多個資料幀
