I'm checking my password for this criteria
be at least 10 characters long
contain at least 1 capital letter
contain at least 1 number
contain at least one of the characters $, #, %, &, or *
not contain any spaces
my code:
password = input("enter a password ")
def passwordIsOk (password):
symbols = "$#%&*"
if len (password) > 10:
if any(i.isupper() for i in password):
if any(i.isdigit() for i in password):
if " " not in password:
for i in range(0,5):
if symbols[i] in password:
passwordValid = True
if passwordValid == True:
print("ok buddy")
else:
print("Password must contain $#%&*")
else:
print("Password must not contain spaces")
else:
print("Password must have at least 1 number")
else:
print("Password must have at least 1 capital letter")
else:
print("Password must be greater than 10 characters")
passwordIsOk(password)
It works, but It just don't feel right :(
You can avoid this kind of nested if structure by inverting the conditions. This makes the code much more readable, and puts the error messages next to the conditions which check for those errors.
def passwordIsOk(password):
symbols = "$#%&*"
if len (password) <= 10:
print("Password must be greater than 10 characters")
elif not any(i.isupper() for i in password):
print("Password must have at least 1 capital letter")
elif not any(i.isdigit() for i in password):
print("Password must have at least 1 number")
elif " " in password:
print("Password must not contain spaces")
elif not any(s in password for s in symbols):
print("Password must contain at least one of " + symbols)
else:
print("ok buddy")
password = input("enter a password ")
passwordIsOk(password)
Putting aside the nested if structure, you could use any to check if it contains any special symbol:
password = input("enter a password ")
def passwordIsOk (password):
symbols = "$#%&*"
if len (password) > 10:
if any(i.isupper() for i in password):
if any(i.isdigit() for i in password):
if " " not in password:
if any(s in password for s in symbols):
passwordValid = True
print("ok buddy")
else:
print("Password must contain $#%&*")
else:
print("Password must not contain spaces")
else:
print("Password must have at least 1 number")
else:
print("Password must have at least 1 capital letter")
else:
print("Password must be greater than 10 characters")
passwordIsOk(password)
It is arguably easier to read and it will print all the problems with the password if you invert and flatten out the if statements using the passwordValid flag like so:
password = input("enter a password ")
def passwordIsOk (password):
passwordValid = True
symbols = "$#%&*"
if len (password) <= 10:
passwordValid = False
print("Password must be greater than 10 characters")
if not any(i.isupper() for i in password):
passwordValid = False
print("Password must have at least 1 capital letter")
if not any(i.isdigit() for i in password):
passwordValid = False
print("Password must have at least 1 number")
if " " in password:
passwordValid = False
print("Password must not contain spaces")
if not any(s in password for s in symbols):
passwordValid = False
print("Password must contain at least one of $#%&*")
if passwordValid:
print("ok buddy")
passwordIsOk(password)
A common method in password validation are regular expressions.
# coding: utf-8
import re
from getpass import getpass
def passwordIsOk(password):
if len(password) < 10:
print("Password must be greater than 10 characters")
elif not re.search('[A-Z]',password):
print("Password must have at least 1 capital letter")
elif not re.search('[0-9]',password):
print("Password must have at least 1 number")
elif not re.search('[$#%&*]',password ):
print("Password must contain at least one of $#%&*")
elif " " in password:
print("Password must not contain spaces")
else:
print("ok buddy")
pswd = getpass("Enter password: ")
passwordIsOk(pswd)
Related
def isValidPassword(password):
if (len(password)<=8):
print("Password must be at least 8 characters or more.")
return False
if any(digit.isdigit() for digit in password):
print("Password must have at least single digit or more.")
return False
if any(digit.isupper() for digit in password):
print("Password must have at least one uppercase letter or more.")
return False
if any(digit.islower() for digit in password):
print("Password must have at least one lowercase letter or more.")
return False
return True
def confirmedPassword():
isSecure = False ; isMatch = False
password = "" ; reenterPassword = ""
while(isSecure == False):
password = input("Enter your password: ")
isSecure = isValidPassword(password)
while(isMatch == False):
reenterPassword = input("\nPlease re-enter your password: ")
if (password == reenterPassword):
isMatch = True ; print("Password is confirmed. Thank you.")
print("The password you entered is approved and safe.")
else:
(password == reenterPassword)
isMatch = False ; print("Password is not confirmed. Please try again.")
confirmedPassword()
If anyone can please help. It is appreciated. I had a hard time figuring out how to condense a failed list of criteria printed out when I input "ABC" to run the program.
I changed your code to print out all the issues with the password before returning whether or not it is a valid password. I also fixed all of the if statements you had to correctly capture the password issue.
def isValidPassword(password):
valid = True
if (len(password) < 8):
print("Password must be at least 8 characters or more.")
valid = False
if not any(digit.isdigit() for digit in password):
print("Password must have at least single digit or more.")
valid = False
if not any(digit.isupper() for digit in password):
print("Password must have at least one uppercase letter or more.")
valid = False
if not any(digit.islower() for digit in password):
print("Password must have at least one lowercase letter or more.")
valid = False
return valid
def confirmedPassword():
isSecure = False ; isMatch = False
password = "" ; reenterPassword = ""
while(not isSecure):
password = input("Enter your password: ")
isSecure = isValidPassword(password)
while(not isMatch):
reenterPassword = input("\nPlease re-enter your password: ")
if (password == reenterPassword):
isMatch = True
print("Password is confirmed. Thank you.")
print("The password you entered is approved and safe.")
else:
isMatch = False
print("Password is not confirmed. Please try again.")
confirmedPassword()
Here, I am trying to validate a password and check to see if there are capitals and numbers in the password before saving it as a different variable. Using functions, is it possible for me to do so. The indents have changed on the format, so please help me with other aspects.
def length(long):
while len(long) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(long) + " characters long")
if password.isupper() = True:
print("Welcome to this student interface")
username = input("Please enter a username")
password = input("Please enter a strong password")
length(password)
This is what I have now done:
def length(long):
bool LengthCheck = False
if len(long) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(long) + " characters long")
else:
LengthCheck = True
errors = []
print("Welcome to this student interface")
username = input("Please enter a username")
password = input("Please enter a strong password")
length(password)
bool Capcheck = False
bool DigCheck = False
while CapCheck = False or CapCheck = False:
length(password)
if not any(x.isupper() for x in password):
errors.append("Your password needs at least 1 capital.")
else:
CapCheck = True
break
if not any(x.islower() for x in password):
errors.append("......... Why?")
if not any(x.isdigit() for x in password):
errors.append("You need to have at least 1 digit")
else:
DigCheck = True
break
if errors:
print(" ".join(errors))
password = input("Please enter a stronger password")
Apparently there is an error with my boolean here, please help
def length(long):
bool LengthCheck = False
if len(long) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(long) + " characters long")
else:
LengthCheck = True
Try using islower():
password.islower()
This returns True if there are no Uppercases in the password.
Now if you want to check if it has number i it, you have to follow #jubnvz:
any(i.isdigit() for i in password)
or a more specific way:
any(map(str.isdigit, password))
And for your password entries, try:
while True:
password = input(""Please enter a strong password:")
if not any(x.isupper() for x in password):
print("Your password needs at least 1 upper case.")
elif not any(x.isdigit() for x in password):
print("You need to have at least 1 digit")
elif not any(x.islower() for x in password):
print("Your password needs at least 1 lower case.")
elif len(password) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(password)) + " characters long")
else:
break
If you want to and a confirm password too, try:
while True:
password = input(""Please enter a strong password:")
if not any(x.isupper() for x in password):
print("Your password needs at least 1 upper case.")
elif not any(x.isdigit() for x in password):
print("You need to have at least 1 digit")
elif not any(x.islower() for x in password):
print("Your password needs at least 1 lower case.")
elif len(password) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(password)) + " characters long")
else:
passwordcon = input(""Please confirm your password:")
if passwordcon == password:
break
else:
print("Your passwords do not match, try again'")
any([p.isupper() for p in password])
I've been trying to figure this out my own, but I couldn't come up with solutions for this. I did come across to SpecialSym["$", "#", "#"] but I wasn't able to work that one into this code.
print("Password is incorrect, please try again...")
passW()
You can do this by adding the condition which would check whether any of the characters is in the list ["$", "#", "#"] or not.
The updated code would be:
import re #regular expression
print("Please enter a password to log in...")
def passW():
while True:
password=input("Enter a password:\n")
if password=="Y0urC0llege":
print("Logging in...")
print("Your login was successful.")
print("Welcome, Professor.")
break
elif len(password) < 10:
print("Please make sure your password is as least 10 characters long.")
elif re.search("[0-9]", password) is None:
print("Please contain as least 1 number in your password.")
elif re.search("[A-Z]", password) is None:
print("Please contain 1 capital letter in your password")
elif re.search("[$##]", password) is None:
print("Please contain as least 1 character symbol in your password.")
else:
print("Password is incorrect, please try again...")
passW()
Hope it helps.
You have to take special characters in a variable after that you can check the condition like below:
SpecialSym = ['!','#','#'] # You can add as many symbols you want.
elif not any(char in SpecialSym for char in password):
print("Please contain as least 1 character symbol in your password.")
incorrectPassword= True
while incorrectPassword:
password = input("type in your password: ")
if len(password) < 8:
print("your password must be 8 characters long")
if len(password) >24:
print("Your password must be shorter than 24 characters")
elif not any(i.isdigit() for i in password):
print("you need a number in your password")
elif not any(i.isupper() for i in password):
print("you need a capital letter in your password")
elif not any(i.islower() for i in password):
print("you need a lowercase letter in your password")
incorrectPassword = False
How can I only allow certain characters (like !, $, %, ^, &, *, (, ), -, _, = or +) as needed input?
I would use regex, but to do it in a similar fashion to your other tests:
any(i not in '!$%^&*()-_=+' for i in password)
you can simply use
elif " " in password:
#print error
or use Python's re package to define what characters are allowed in your password
I have set up a program to change a "password". I have it checking to see if it is at least 8 characters, contains a capital letter and has a number, and if it does not meet this criteria, it asks for the password again. I have everything working except the checking for a number and I was wondering if someone could help.
npwv = 1
while npwv == 1:
npw = input("Please enter new password.")
npwc = input ("Please confirm new password")
if npwc == npw:
if npwc.isupper()== False:
if npwc.islower()== False:
if len(npwc) >= 8:
if str.isdigit(npwc) == True:
npw=npwc
print("Your password has been changed")
else:
print("Your password must contain a number")
npwv = 1
else:
print("Your password must contain at least 8 characters.")
npwv = 1
else:
print("Your password must contain at least 1 upper case character.")
npwv = 1
else:
print ("Passwords don't match")
npwv = 1
You are checking if the password itself is fully uppercase or composed of numbers. What you need to check if if the characters in the password match this criteria.
has_upper = any([c.isupper() for c in npwc])
has_digit = any([c.isdigit() for c in npwc])
You can also use regular expressions.
By the way, you should prefer getpass to get the password from the user.
Have you considered using .isalnum()?
>>> foo = "123asd"
>>> foo
'123asd'
>>> foo.isalnum()
True
>>>
Edit: Judging by the other answers, I am not sure what are you looking for, could explain it with examples?
I would suggest using sets, and the string package from stdlib for your list of acceptable characters.
I would also suggest refactoring a bit to remove a lot of the nesting with if / else branches.
import string
upper = set(list(string.uppercase))
lower = set(list(string.lowercase))
numbers = set(list(string.digits))
while True:
npw = input("Please enter new password: ")
npwc = input("Please confirm new password: ")
if npwc != npw:
print("Passwords don't match")
continue
if len(npcw) < 8:
print("Your password must contain at least 8 characters.")
continue
chars = set(list(npwc))
if not upper.intersection(chars):
print("Your password must contain at least 1 upper case character.")
continue
if not lower.intersection(chars):
print("Your password must contain at least 1 lower case character.")
continue
if not numbers.intersection(chars):
print("Your password must contain a number")
continue
npw = npwc
print("Your password has been changed")
break
This can be made more compact but yeah..
while True:
npw = input("Please enter new password.")
npwc = input ("Please confirm new password")
if npwc == npw:
if any(x.isupper() for x in npwc):
if any(x.islower() for x in npwc):
if len(npwc) >= 8:
if any (x.isdigit() for x in npwc):
npw=npwc
print("Your password has been changed")
#break # you probably want to exit the loop at this point
else:
print("Your password must contain a number")
else:
print("Your password must contain at least 8 characters.")
else:
print("Your password must contain at least 1 upper case character.")
else:
print("Your password must contain at least 1 lower case character.")
else:
print("Passwords don't match")
This looks like a job for regular expressions. Solution below:
import re
def password_validator(password):
if len(password) < 8:
return False, "Your password must contain at least 8 characters"
if not re.match('.*[0-9]', password):
return False, "Your password must contain a number"
if not re.match('.*[A-Z]', password):
return False, "Your password must contain at least 1 upper case character."
if not re.match('.*[a-z]', password):
return False, "Your password must contain at least 1 lower case character."
return True, "Your password has been changed"
while True:
npw = input("Please enter new password.")
npwc = input("Please confirm new password")
if npw != npwc:
print("Passwords don't match")
continue
is_valid, message = password_validator(npw)
print(message)
if is_valid:
break
You could also validate the whole thing in one go as:
pattern = """
(?=.*[a-z]) # use positive lookahead to see if at least one lower case letter exists
(?=.*[A-Z]) # use positive lookahead to see if at least one upper case letter exists
(?=.*\d) # use positive lookahead to see if at least one digit exists
[A-Za-z0-9##$%^&+=]{8,} # match any character in [] at least 8 times
"""
pwd_validator = re.compile(pattern, re.VERBOSE)
if pwd_validator.match(password):
# legit password
else:
# no match ask again
Hope this helps. The re.VERBOSE just makes this regular expression self-documenting so a lot easier to understand in future.