python-3.x 有什么好的方法来遍历我的方法一,并检查每个方法的结果?

eivnm1vs  于 2023-03-31  发布在  Python
关注(0)|答案(4)|浏览(105)

我是Python编程的新手,但我想做一个密码检查器来检查单个字符串输入中的某些内容。如果任何方法返回else,我想重新启动while循环。

def length():
    if len(password) > 8:
        print("Password is long enough. ")
    else:
        print("Password too short, please try a new password. ")

def numbers():
    if len([num for num in password if num.isdigit()]) >= 2:
        print("Password has two digits. ")
    else:
        print("Password needs two digits, please try a new password. ")


def lower():
    if any(map(str.islower, password)):
        print("Password has lower case. ")
    else:
        print("Password needs an lowercase letter, please try a new password.")


def upper():
    if any(map(str.isupper, password)):
        print("Password has upper case. ")
    else:
        print("Password needs an uppercase letter, please try a new password.")


while True:
    password = str(input("What is your password? \n"))
    length()
    numbers()
    lower()
    upper()

我不知道我能做些什么来有效地通过这些方法,并检查我是否得到了我想要的结果。

8hhllhi2

8hhllhi21#

你可以这样做:

from typing import List

def length(pwd: str) -> bool:
    return len(pwd) > 8

def numbers(pwd: str) -> bool:
    return len([num for num in pwd if num.isdigit()]) >= 2

def lower(pwd: str) -> bool:
    return any(map(str.islower, pwd))

def upper(pwd: str) -> bool:
    return any(map(str.isupper, pwd))

if __name__ == "__main__":
    functions_to_check: List = [length, numbers, lower, upper]
    is_password_satisfactory: bool = False
    password: str = ""
    while not is_password_satisfactory:
        password = str(input("What is your password? \n"))
        is_password_satisfactory = all(map(lambda f: f(password), functions_to_check))
    print(f"{password} is satisfactory")

简单回顾一下anyall的工作原理:它们都将布尔值列表作为参数,并且如果列表中的任何(或所有)元素是True,则返回True
在这个想法的基础上,我们首先列出了我们必须用来验证密码的函数(functions_to_check)。
然后我们将循环直到密码有效。
我们通过构建一个布尔值列表来检查密码是否有效,这些布尔值表示密码是否通过了每次检查(map(lambda f: f(password), functions_to_check):我们将每个验证函数应用于密码并将结果存储在列表中),然后我们检查该列表的所有元素是否都是True(我们将其作为参数传递给all函数)。
然后,我们将all函数的结果存储到用于继续循环的变量中,如果密码有效,则破解。

vnjpjtjt

vnjpjtjt2#

你可以从你的函数中返回一个布尔值,作为while循环是否应该继续的标志。
如果密码中没有大写字母,则函数返回True,因此循环将继续调用upper()。
我鼓励你尝试找到如何实现它的所有功能。

def upper():
    if any(map(str.isupper, password)):
        print("Password has upper case. ")
        return False #exit
    else:
        print("Password needs an uppercase letter, please try a new password.")
        return True # keeps going

flag = True
while flag:
    password = str(input("What is your password? \n"))
    flag = upper()
lpwwtiir

lpwwtiir3#

1.为函数添加参数。
1.让函数返回bool值。
1.如果满足所有条件,则使用break中断while-循环。

def length(password):
    if len(password) > 8:
        print("Password is long enough.")
        return True
    else:
        print("Password too short, please try a new password.")
        return False

def numbers(password):
    if len([num for num in password if num.isdigit()]) >= 2:
        print("Password has two digits.")
        return True
    else:
        print("Password needs two digits, please try a new password.")
        return False

def lower(password):
    if any(map(str.islower, password)):
        print("Password has lower case.")
        return True
    else:
        print("Password needs a lowercase letter, please try a new password.")
        return False

def upper(password):
    if any(map(str.isupper, password)):
        print("Password has upper case.")
        return True
    else:
        print("Password needs an uppercase letter, please try a new password.")
        return False

while True:
    pw = str(input("What is your password?\n"))
    if (length(pw) and numbers(pw) and lower(pw) and upper(pw)):
        break
fcy6dtqo

fcy6dtqo4#

返回布尔值的另一种方法是使用异常:

class InvalidPasswordException(Exception):
    pass

def validate_length(password: str):
    if len(password) < 9:
        raise InvalidPasswordException("Password too short, please try a new password.")

def validate_numbers(password: str):
    if len([num for num in password if num.isdigit()]) < 2:
        raise InvalidPasswordException("Password needs two digits, please try a new password.")

def validate_lower(password: str):
    if not any(map(str.islower, password)):
        raise InvalidPasswordException("Password needs an lowercase letter, please try a new password.")

def validate_upper(password: str):
    if not any(map(str.isupper, password)):
        raise InvalidPasswordException("Password needs an uppercase letter, please try a new password.")

def get_password() -> str:
    while True:
        try:
            password = str(input("What is your password? \n"))
            validate_length(password)
            validate_numbers(password)
            validate_lower(password)
            validate_upper(password)
            return password
        except InvalidPasswordException as error:
            print(error)

if __name__ == '__main__':
    get_password()

另外,你可能想跳出while True循环。为此,你可以使用breakreturn(如果它在函数内部)。
使用异常并不比其他方法更好也更差,它更像是一种不同的风格(参见"ask for forgiveness not permission")。

相关问题