首先应该是大写和小写。
然后它应该是数字和字符。
然后它应该是所有角色的混合。
import random
pswd = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbrs = "0123456789"
chars = "@#$&*_-:;',./^"
def pswd_generator(data):
if data == 1:
genpswd = "".join(random.sample(pswd,size))
elif data == 2:
genpswd ="".join(random.sample(pswd+numbrs+chars,size))
elif data == 3:
genpswd = "".join(random.sample(pswd+numbrs+chars,size))
print "Your Generated Password is:",genpswd
m = False
while not m:
size = int(raw_input("How many digits of password do you want to generate: "))
print "1.Weak Password"
print "2.Medium Password"
print "3.Strong Password"
print ("Select 1,2,3")
data = int(raw_input("Enter the option: "))
if data == 1:
m = True
elif data == 2:
m = True
elif data == 3:
m = True
else:
print "Wrong option.Try again"
pswd_generator(data)
我怎样才能以pythonic的方式实现?
答案 0 :(得分:1)
要清理它并使其更加Pythonic以及满足您的密码要求的目标,我建议如下:
pswd_generator
功能,使其接受两个参数:option
和size
。这样做的原因是您在调用此函数之前依赖于正在创建的size
变量... pswd_generator
仅在size
启用在size =
pswd_generator
中执行一些非常基本的错误检查,以确保传入的选项有效。def pswd_generator(option, size):
assert(option in (1, 2, 3))
size = max(6, size)
prefix_size = min(5, size / 3)
number_size = min(5, size / 3)
filler_size = size - prefix_size - number_size
if option == 1:
genpswd = "".join(random.sample(pswd, size))
elif option == 2:
genpswd = "".join(
random.sample(pswd, prefix_size) +
random.sample(numbrs + chars, number_size) +
random.sample(pswd + numbrs + chars, filler_size)
)
else:
genpswd = "".join(random.sample(pswd + numbrs + chars, size))
return genpswd
对于你的主循环,我建议:
while
条件,只需查看是否已创建密码。它的设置方式现在你正在使用一个变量来摆脱循环...有更简单的方法来实现它。psswd
变量,然后打印出来,这也将终止循环。psswd = None
while not psswd:
# stuff
option = int(raw_input("Enter the option: "))
if 0 < option < 4:
psswd = pswd_generator(option, size)
print "Your Generated Password is: ", psswd
else:
print "Wrong option.Try again"