简体   繁体   English

嵌套循环不会在随机密码生成器中迭代

[英]nested loop will not iterate in random password generator

I have having trouble with my num_char output in my random password generator.我的随机密码生成器中的 num_char output 遇到问题。 I am getting the number of passwords but not the length on each password.我得到了密码的数量,但不是每个密码的长度。 Can you solve this?你能解决这个问题吗?

from random import choice
import string

def create_password():

    num_passwords = int(input('How many passwords would you like?  '))
    num_char = int(input('How long would you like your password to be?  '))
    
    for j in range(num_passwords):
        for k in range(num_char):
            password = ''.join([choice(string.ascii_lowercase + string.ascii_uppercase + string.digits)])
            num_passwords -=1
        print(password)

create_password()

output: output:

y
t
K
S
7

You might want to use list comprehension您可能想使用list comprehension

Also, you don't need num_passwords -=1此外,您不需要num_passwords -=1

And this和这个

password = ''.join([choice(string.ascii_lowercase + string.ascii_uppercase + string.digits)])

Will give you something like a per password会给你a类似每个密码的东西

from random import choice
import string

def create_password():

    num_passwords = int(input('How many passwords would you like?  '))
    num_char = int(input('How long would you like your password to be?  '))
    
    for j in range(num_passwords):
        pwd = [choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for k in range(num_char)]
        print(''.join(pwd))
create_password()

output (num_pwd = 5, num_char = 5) output (num_pwd = 5, num_char = 5)

VY1bi
jAvLG
zUxlo
jMBZD
VQHV6

this maybe easier to understand for beginer.这对于初学者来说可能更容易理解。
but list comprehension is better solution但列表理解是更好的解决方案

from random import choice
import string

def create_password():

    num_passwords = int(input('How many passwords would you like?  '))
    num_char = int(input('How long would you like your password to be?  '))
    
    for j in range(num_passwords):
        password = ''
        for k in range(num_char):
            #in your code.you just replace password to last one every time
            password += ''.join([choice(string.ascii_lowercase + string.ascii_uppercase + string.digits)])
            # num_passwords -=1 #no need for this
        print(password)

create_password()

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

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