奇怪的回归'密码生成器功能

时间:2017-11-24 18:45:02

标签: python

我正在为练习创建密码生成功能,我正在检查用户是否为要生成的密码指定了至少8个符号长度,同时想要检查是否有3次错误的输入尝试我会使用return退出程序。

我期待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)

2 个答案:

答案 0 :(得分:0)

我怀疑你的问题出在这一行:

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

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

答案 1 :(得分:0)

发生了什么,是它进入'无效'部分,再次调用PasswordGenerator,然后完成剩下的代码。因此,在第3次尝试时,它将返回,不生成密码,但将完成第2次尝试,并生成密码,然后完成第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)。如果那不是你正在做的事情,你也应该改变它。