Reputation: 21
Below is my small program I am working
Build a password checker. It will take string input. Condition: password string must contain at least one upper case, one lower case, one number and length must be minimum 8 characters. Otherwise it will say ‘invalid password’.
I am trying with the below codes
password = str(raw_input("Enter the password: "))
if password.isalnum() == False:
print "Password should contain atleast one special character or number"
if password.isalnum() == False:
print "Password should contain atleast one numeric number"
elif len(password)<8:
print 'Too short'
elif password.isupper() == False:
print 'Password should contain atleast one uppercase character'
elif password.islower() == False:
print 'Password should contain atleast one lowercase character'
else:
print "Password is OK"
But it is inconsistent, it is asking for uppercase even it is there,
Enter the password: niswdgER41
Password should contain atleast one uppercase character
Upvotes: 0
Views: 4928
Reputation: 1
def checkpassword ():
password = input ("please enter password")
def menu ():
print ("1. Check Password")
print ("2. Generate Password")
print ("3. Quit")
optionchoice = input (" please chose a menu,1,2,3")
if optionchoice == "1":
checkpassword()
elif optionchoice == "2":
pass
elif optionchoice == "3":
pass
else :
print ("invalid answer!")
menu()
menu()
Upvotes: 0
Reputation: 8501
You have a couple of mistakes, but the most important one is that all the methods you use check if the entire string upholds the condition, rather than once of its chars.
Change it to:
def validate_password(pwd):
conds = [
lambda s: any(x.isupper() for x in s),
lambda s: any(x.islower() for x in s),
lambda s: any(x.isdigit() for x in s),
lambda s: len(s) >= 8
]
return all(cond(pwd) for cond in conds)
But, if you really want the user to know what is missing, you could use the following implementation:
def validate_password(pwd):
conds = {
"uppercase": lambda s: any(x.isupper() for x in s),
"lowercase": lambda s: any(x.islower() for x in s),
"number": lambda s: any(x.isdigit() for x in s),
"length": lambda s: len(s) >= 8
}
valid = True
for name, cond in conds.iteritems():
if not cond(pwd):
print "Password lacking " + name
valid = False
if valid:
print "Password OK"
else
print "Password Invalid"
return valid
Upvotes: 2
Reputation: 3049
You can check all characters in the string with a list comprehension:
contains_upper_case_character = any([letter.isupper() for letter in password])
# contains_upper_case_character is True if password contains an uppercase letter.
If you want to extend this to more that one upper case letter:
password = 'StrinG12'
upper_case_letters = [letter.isupper() for letter in password].count(True)
print(upper_case_letters)
>>> 2
Upvotes: 0