Validation of a Password - Python

2020-01-25 11:40发布

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 capital letter

Here is the code:

def validate():
    while True:
        password = input("Enter a password: ")
        if len(password) < 8:
            print("Make sure your password is at lest 8 letters")
        elif not password.isdigit():
            print("Make sure your password has a number in it")
        elif not password.isupper(): 
            print("Make sure your password has a capital letter in it")
        else:
            print("Your password seems fine")
            break

validate()

I'm not sure what is wrong, but when I enter a password that has a number - it keeps telling me that I need a password with a number in it. Any solutions?

10条回答
老娘就宠你
2楼-- · 2020-01-25 11:47

You can use re module for regular expressions.

With it your code would look like this:

import re

def validate():
    while True:
        password = raw_input("Enter a password: ")
        if len(password) < 8:
            print("Make sure your password is at lest 8 letters")
        elif re.search('[0-9]',password) is None:
            print("Make sure your password has a number in it")
        elif re.search('[A-Z]',password) is None: 
            print("Make sure your password has a capital letter in it")
        else:
            print("Your password seems fine")
            break

validate()
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-01-25 11:47

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))
查看更多
手持菜刀,她持情操
4楼-- · 2020-01-25 11:48

password.isdigit() does not check if the password contains a digit, it checks all the characters according to:

str.isdigit(): Return true if all characters in the string are digits and there is at least one character, false otherwise.

password.isupper() does not check if the password has a capital in it, it checks all the characters according to:

str.isupper(): Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise.

For a solution, please check the question and accepted answer at check if a string contains a number.

You can build your own hasNumbers()-function (Copied from linked question):

def hasNumbers(inputString):
    return any(char.isdigit() for char in inputString)

and a hasUpper()-function:

def hasUpper(inputString):
    return any(char.isupper() for char in inputString)
查看更多
Luminary・发光体
5楼-- · 2020-01-25 11:52
r_p = re.compile('^(?=\S{6,20}$)(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^A-Za-z\s0-9])')

this code will validate your password with :

  1. min length is 6 and max length is 20
  2. at least include a digit number,
  3. at least a upcase and a lowcase letter
  4. at least a special characters
查看更多
来,给爷笑一个
6楼-- · 2020-01-25 11:57

Python 2.7 The for loop will assign a condition number for each character. i.e. Pa$$w0rd in a list would = 1,2,4,4,2,3,2,2,5. Since sets only contains unique values, the set would = 1,2,3,4,5; therefore since all conditions are met the len of the set would = 5. if it was pa$$w the set would = 2,4 and len would = 2 therefore invalid

name = raw_input("Enter a Password: ")
list_pass=set()
special_char=['#','$','@']
for i in name:
    if(i.isupper()):
      list_pass.add('1')
  elif (i.islower()):
      list_pass.add('2')
  elif(i.isdigit()) :
      list_pass.add('3')
  elif(i in special_char):
      list_pass.add('4')
if len(name) >=6 and len(name) <=12:
    list_pass.add('5')
if len(list_pass) is 5:
    print ("Password valid")
else: print("Password invalid")
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2020-01-25 11:57

Or you can use this to check if it got at least one digit:

min(passwd).isdigit()
查看更多
登录 后发表回答