我正在学习如何用Python编写代码,而且以前从未编写过代码,我只想知道是否有任何方法可以升级我的PasswordGenerator。
#!/usr/bin/env python3
import random
def passwordgenerator():
mypw = ""
count = 0
alphabet_number = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
symbols = "!?@%#$"
running1 = True
while running1:
if len(symbols) == 1:
# Reset symbols
symbols = "!?@%#$"
if len(alphabet_number) == 1:
# Reset letters/numbers
alphabet_number = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
elif count == pw_length:
if mypw.isupper() or mypw.islower(): # check if there is only upper or only lower letter and rerun if True
passwordgenerator()
else:
x = mypw
y = list(x) # creates a list and put the pw in to shuffle it
random.shuffle(y)
mypw = "".join(y)
print(mypw)
input("\nPress to close the program")
running1 = False
elif count % 4 == 0:
# pick a random symbol every 3 loop and add it to the pw
symbols_index = random.randrange(len(symbols))
new_symbols = symbols[symbols_index]
mypw = mypw + new_symbols
# delete the symbols that is picked so there are no duplicate
symbols_list_change = symbols.replace(new_symbols, "")
symbols = symbols_list_change
else:
# pick a random number or letter and add it to the pw
next_index = random.randrange(len(alphabet_number))
new_alphabetnumber = alphabet_number[next_index]
mypw = mypw + new_alphabetnumber
# delete the symbols that is picked so there are no duplicate
an_list_change = alphabet_number.replace(new_alphabetnumber, "")
alphabet_number = an_list_change
count += 1
if __name__ == '__main__':
print("/!\ 12 Characters is a minimum for good security /!\ ")
print("=" * 55) # just to make it pretty
running = True
while running:
pw_length = input("How many Characters do you want?\n")
if pw_length.isdigit(): # verify if user input a number
pw_length = int(pw_length)
passwordgenerator()
running = False
else:
print("A number is needed")发布于 2018-11-13 19:59:43
谢谢你贴出你的代码,很高兴你想要改进你的风格。我列出了一小张清单,列出了你可以改进的地方。这个列表可能不完整,不同的程序员可能有不同的意见,但我尽力做到建设性和不固执己见。
pw_length,不如将其作为参数传递给passwordgenerator。passwordgenerator中打印密码,不如返回密码并在主函数中打印它。random.choice从列表中选择随机元素,random.sample从列表中选择k唯一元素。发布于 2018-11-13 18:22:42
对于第一个Python程序来说,还不错:
if __name__ == '__main__':。replace、isupper、islower等)。但有些东西可以做得更好:
passwordgenerator可以将pw_length作为参数并返回mypw。(密码的打印移到本例中的主要部分)passwordgenerator内部调用passwordgenerator本身(递归调用)可能很棘手(密码意外地总是较低.?)"!?@%#$"和"abc...XYZ"都发生了两次,它们可以是程序顶部的常量。elif count == pw_length应该是不同的passwordgenerator中,解释生成密码的属性。发布于 2018-11-13 20:09:37
这造成的一个非常重要和常见的错误是使用random。
对于不需要安全性的应用程序,random就足够了,但是对于这种情况,您确实应该使用secrets 模块。这将产生不可预测的数字,而代价是稍慢一些。不幸的是,这确实会使程序的某些部分变得更难,因为模块没有提供一些方便的random方法,但是这些方法并不太难自己编写。
例如,symbols_index = random.randrange(len(symbols))变成了secrets.randbelow(len(symbols))。
https://codereview.stackexchange.com/questions/207569
复制相似问题