密码生成器函数的奇数“返回”

2024-07-07 07:11:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个练习创建一个密码生成函数,在这个函数中,我检查用户是否为要生成的密码指定了至少8个符号长度,同时要检查是否有3次错误的输入尝试,我将使用return退出程序。你知道吗

我希望返回函数停止所有操作,之后不再继续下面的循环,但事实并非如此。你知道吗

你能帮我理解为什么会这样吗?你知道吗

代码如下:

    import string
    import random
    attempts = 0

def PasswordGenerator(passwordlenght):
    passwordlenght = int(passwordlenght)
    password= ""
    i = 0

    if passwordlenght < 8:
        print("Password length must be more than 8 symbols !!!")
        global attempts
        attempts += 1

        if attempts <3:
            PasswordGenerator(passwordlenght)
        else:
            return 1    

    while i < passwordlenght:
        if i in range(1,passwordlenght,3):
            password += string.ascii_lowercase[random.randrange(len(string.ascii_lowercase))]
        elif i in range(2, passwordlenght, 3):
            password += string.ascii_uppercase[random.randrange(len(string.ascii_uppercase))]
        elif i in range(3, passwordlenght, 3):
            password += string.digits[random.randrange(len(string.digits))]
        i += 1

    print(password)

PasswordGenerator(5)

Tags: 函数in密码stringlenreturnifascii
2条回答

我怀疑你的问题出在这条线上:

PasswordGenerator(passwordlenght)

您的函数是递归地调用自身的,但是由于它没有return递归调用返回的值,因此它将在之后继续运行其余的代码。你知道吗

您可以通过添加return来“修复”它:

return PasswordGenerator(passwordlenght)

但这仍然不是一个很好的解决方案。对于大多数需要执行一定次数的程序,使用循环比递归要好得多。尝试这样的方法,它将检查三次相同的长度是否确实太短:

for attempt in range(3):
    if passwordlenght < 8:
        print("Password length must be more than 8 symbols !!!")
    else:
        # put the rest of the code here, including the return

显然这有点傻,因为如果第一次的长度太短,第二次和第三次的长度也会太短。我真的不确定多次尝试对于这个特定的检查有什么意义(对于候选密码的其他一些检查可能有意义,但是对于这个检查没有意义,因为长度是由用户提供的,而不是随机的)。你知道吗

发生的事情是,它进入“invalid”部分,再次调用PasswordGenerator,然后完成其余的代码。因此,在第三次尝试时,它将返回,不生成密码,但随后将完成第二次尝试,并生成密码,然后完成第一次尝试并生成密码。有几种方法可以做到这一点,将末尾的while循环设为if passwordlength<;8的“else”条件,或者从if attempts<;3的“else”中删除返回。下面演示了这两种技术(尽管您只需要1)

import string
import random
attempts = 0

def PasswordGenerator(passwordlenght):
    passwordlenght = int(passwordlenght)
    password= ""
    i = 0

    if passwordlenght < 8:
        print("Password length must be more than 8 symbols !!!")
        global attempts
        attempts += 1

        if attempts <3:
            PasswordGenerator(passwordlenght)
        return 1
    else:

        while i < passwordlenght:
            if i in range(1,passwordlenght,3):
                password += str ing.ascii_lowercase[random.randrange(len(string.ascii_lowercase))]
            elif i in range(2, passwordlenght, 3):
                password += string.ascii_uppercase[random.randrange(len(string.ascii_uppercase))]
            elif i in range(3, passwordlenght, 3):
                password += string.digits[random.randrange(len(string.digits))]
            i += 1

        print(password)

PasswordGenerator(5)

编辑:我假设它当前的编码方式是出于测试目的,否则您将只传递最初提供的值作为密码长度,并且它将始终失败(如果小于8)。如果这不是你正在做的,你也应该改变。你知道吗

相关问题 更多 >