简体   繁体   English

为什么我的密码生成器只生成一个密码?

[英]Why is my password generator only generating one password?

Im a beginner to python and wish for help with this我是 python 的初学者,希望得到帮助

print('Password generator ')
letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*().,?0123456789'
numv = int(input('Amounts of Passwords to generate:'))
leny = input('Input your password length:')
leny = int(leny)
print('Here are your passwords:')
for pwd in range(numv):
    passwords = ''
for c in range(leny):
    passwords += random.choice(letter)
print(passwords)

I don't understand why it isn't printing out more than one password when I run it.我不明白为什么它在运行时不打印出多个密码。

What you want to do is nest the second for-loop in the first one.您要做的是将第二个 for 循环嵌套在第一个循环中。

for pwd in range(numv):
    passwords = ''

This for-loop doesn't do anything as of right now it is equivalent as if you had just written:这个 for 循环目前没有做任何事情,它等同于你刚刚编写的代码:

passwords = ''

To achieve the desired behaviour you'd need to do something like this:要实现所需的行为,您需要执行以下操作:

passwords = ''
for pwd in range(numv):
    for c in range(leny):
        passwords += random.choice(letter)
    passwords += "|" # This is just a separator 

You'll notice I added passwords += "|"你会注意到我添加了passwords += "|" at the end of every iteration of the outer for-loop.在外部 for 循环的每次迭代结束时。 This is just for you to be able to distinguish the different passwords when you print the string later.这只是为了让您在稍后打印字符串时能够区分不同的密码。 Without it the output would look like password1password2password3 but with it you'd get password1|password2|password3没有它 output 看起来像password1password2password3但有了它你会得到password1|password2|password3

An even better approach is to declare passwords as a list and append the different passwords to that list:一种更好的方法是将passwords声明为列表,并将 append 声明为该列表的不同密码:

passwords = []
for pwd in range(numv):
    password = ""
    for c in range(leny):
        password += random.choice(letter)
    passwords.append(password)

for password in passwords:
    print(password)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM