'Returning multiple values in a for loop function

The concept of return in a function don't enter my head.

I created this code to generate random passwords, and the return value exits the for loop i created and then just send me one result.

import random
import string


def criador_senha(tamanho, quantidade):
    for senha in range(quantidade):
        senha = []
        for char in range(tamanho):
            lower = string.ascii_lowercase
            upper = string.ascii_uppercase
            num = string.digits
            special = string.punctuation
            char = lower + upper + num + special
            senha += str(random.choice(char))
    return print(senha)


quantidade = input("How many passwords? ")
quantidade = int(quantidade)

tamanho = input("What's the lenght? ")
tamanho = int(tamanho)

criador_senha(tamanho, quantidade)

How can i fix this code?



Solution 1:[1]

The print function does not return anything. It exists only for its side effects. Thus, your function returns None.

As a VERY general rule, a utility function like this should do its job and return a useful value. It should be up to the caller to decide what to DO with that value (like print it).

Also, you were reinitializing the senha list every time through the outer loop. I expect you want it to accumulate everything here.

Also, there's no reason to recompute the list of characters in each loop. It isn't going to change.

Also, you have a bad habit of reusing your variables. You had senha with two meanings, and char with two meanings. That's an easy way to make bugs.

Also, your random.choice is going to return a 1-character string. There's no need to call str on something that's already a string.

Finally, you were appending all of the characters into one big list. I expect you want a list of individual passwords of the given length.

import random
import string


def criador_senha(tamanho, quantidade):
    senha = []
    lower = string.ascii_lowercase
    upper = string.ascii_uppercase
    num = string.digits
    special = string.punctuation
    alphabet = lower + upper + num + special
    for _ in range(quantidade):
        pw = ''
        for char in range(tamanho):
            pw += random.choice(alphabet)
        senha.append(pw)
    return senha

quantidade = input("How many passwords? ")
quantidade = int(quantidade)

tamanho = input("What's the lenght? ")
tamanho = int(tamanho)

print(criador_senha(tamanho, quantidade))

Those nested loops can be replaced with one statement:

    senha = [''.join( [random.choice(alphabet) for _ in range(tamanho)]) for _ in range(quantidade)]

But that's going a bit far for today.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1