Validation of a Password - Python

前端 未结 11 1989
自闭症患者
自闭症患者 2020-11-27 08:20

So I have to create code that validate whether a password:

  • Is at least 8 characters long
  • Contains at least 1 number
  • Contains at least 1
11条回答
  •  长情又很酷
    2020-11-27 08:29

    You are checking isdigit and isupper methods on the entire password string object not on each character of the string. The following is a function which checks if the password meets your specific requirements. It does not use any regex stuff. It also prints all the defects of the entered password.

    #!/usr/bin/python3
    def passwd_check(passwd):
        """Check if the password is valid.
    
        This function checks the following conditions
        if its length is greater than 6 and less than 8
        if it has at least one uppercase letter
        if it has at least one lowercase letter
        if it has at least one numeral
        if it has any of the required special symbols
        """
        SpecialSym=['$','@','#']
        return_val=True
        if len(passwd) < 6:
            print('the length of password should be at least 6 char long')
            return_val=False
        if len(passwd) > 8:
            print('the length of password should be not be greater than 8')
            return_val=False
        if not any(char.isdigit() for char in passwd):
            print('the password should have at least one numeral')
            return_val=False
        if not any(char.isupper() for char in passwd):
            print('the password should have at least one uppercase letter')
            return_val=False
        if not any(char.islower() for char in passwd):
            print('the password should have at least one lowercase letter')
            return_val=False
        if not any(char in SpecialSym for char in passwd):
            print('the password should have at least one of the symbols $@#')
            return_val=False
        if return_val:
            print('Ok')
        return return_val
    
    print(passwd_check.__doc__)
    passwd = input('enter the password : ')
    print(passwd_check(passwd))
    

提交回复
热议问题