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?
You can use
re
module for regular expressions.With it your code would look like this:
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.
password.isdigit()
does not check if the password contains a digit, it checks all the characters according to:password.isupper()
does not check if the password has a capital in it, it checks all the characters according to: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):and a
hasUpper()
-function:this code will validate your password with :
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
Or you can use this to check if it got at least one digit: