My user wants to make a password and I'm supposed to be checking if it's valid or not. So far, I have down the code to check if it is valid/not valid. Now, the next step (after determining it is not valid) is to tell the user it is not valid AND why their password is not a valid option.
while True:
pw = input('Enter password to be tested if valid or not: ')
correct_length = False
uc_letter = False
lc_letter = False
no_blanks = True
first_letter = False
if len(pw) >= 8:
correct_length = True
for ch in pw:
if ch.isupper():
uc_letter = True
if ch.islower():
lc_letter = True
if pw.isalnum():
digit = True
if pw[:1].isalpha():
first_letter = True
if not pw.find(' '):
no_blanks = True
if correct_length and uc_letter and lc_letter and digit and first_letter and no_blanks:
valid_pw = True
print('Your password to be tested is valid.')
else:
valid_pw = False
print('Your password to be tested is not valid because:')
print(----------)
#This is the part where I'm suppose to display the errors if the user gets it wrong.
#Initially, in the test for ch. above, I put in an else: with a print statement but because of the for- statement, it prints it out for every single character.
answer = input('Try another password input? y/n ')
if answer == 'y':
answer = True
else:
break
Hm.. I think you can simply put the extra else statement, then raise an error:
if not pw.find(' '):
no_blanks = True
else:
raise ValueError('Invalid input!')
And similarly with your other conditionals.
If you want your loop to keep going, you can just print the message, and then continue:
else:
print("Invalid input! Please re enter it:")
continue
Hope this helps!
You check for all valid conditions. The correct approach is, instead of checking for the condition to be true like this,
if len(pw) >= 8:
correct_length = True
check for
if len(pw) < 8:
correct_length = False
print "Password not lengthy"
This will help identify the error. basically, find what all evaluate to false, so that the user could be pointed out those errors.
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()
pss = input("Enter a password")
symb = ["!","£","$","%","^","&"]
num = ["1","2","3","4","5","6","7","8","9","0"]
done = 0#to break symbol check
done2 = 0#break num check
check = 0#keep track of things correct
found = False
while found == False:
#checks for a symbol in the password
for ch in pss:
done = done + 1
if ch in symb:
check = check + 1
break
elif done == len(pss):#done , only to say once
print("Add a symbol to your password")
#WORKS!! :D
#checks for number in password
for ch in pss:
done2 = done2 + 1
if ch in num:
check = check + 1
break
elif done2==len(pss):
print("Add a number to your password")
#capital letter check
if pss == pss.lower():
print("You need to have at least one capital letter")
else:
check = check + 1
#checking
if check == 3:
print("Password Validated")
found = True
else:
pss = input("Correct you password")#re enters password
check = 0
#need to make pss update correctly
Its the final few lines that I am having trouble with, the program works, its just that the password doesn't get updated, so unnecessary lines are printed. For example, when entering the initial password "Jellybean" i get reminded to add a number and a symbol to the password. Next, when i get the oppouruntiy to correct, I enter "Jellybean5£" and I still get prompted to add a number and a symbol. However the program recognizes the change and exits, due to the password being successful .
Update the done and done2 variables back to 0 when you're trying to validate
#checking
if check == 3:
print("Password Validated")
found = True
else:
pss = input("Correct you password")#re enters password
check = 0
done = 0
done2 = 0
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.
Very limited on using python and totally stuck, I've managed to get a while loop running on the code below so that the user can keep entering a code until they put in the correct one.
What I'm now looking to do is add a for loop so that it only asks the user to enter the code (4 wrong digits) 3 times and then locks them out. At the same time it needs a while loop to ensure if the user puts more than or less than 4 digits it continually runs and doesn't lock them out.
I just cant get the for loop and while loop working at the same time and don't know what I'm doing wrong.
user = ("1234")
valid = False
while not valid:
#for i in range (3):
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if user == ("1234") :
print("You have cracked the code, well done")
valid = True
break
if user != ("1234") :
print ("that is incorrect, please try again")
valid = False
elif len(user) > 4:
print ("That is incorrect, please try again")
valid = False
elif len(user) < 4:
print ("That is incorrect, please try again")
valid = False
else:
print ("You have been locked out!! Alarm!!!!!!")
user = ("1234")
counter = 0
while counter < 3:
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if len(user) != 4:
print("I said 4 digits!")
continue
if user == ("1234") :
print("You have cracked the code, well done")
break
print ("that is incorrect, please try again")
counter += 1
if counter == 3:
print ("You have been locked out!! Alarm!!!!!!")
else:
print ("Everything is fine.")
I adapted your code a little bit and added a counter variable
user = ("1234")
valid = False
counter = 0
while not valid:
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if user == ("1234") :
print("You have cracked the code, well done")
valid = True
break
elif len(user) != 4:
print ("That is incorrect, please try again")
else:
print ("that is incorrect, please try again")
counter = counter + 1
if counter == 3:
print ("You have been locked out!! Alarm!!!!!!")
#Do stuff to actually abort here...
It counts up if there is a wrong answer now
the inner loop is just for valid input:
user = '1234'
locked = False
miss_cnt = 0
while True:
while True:
ans = raw_input('User -> ')
if len(ans) == 4 and ans.isdigit():
break
if ans != user:
miss_cnt += 1
if miss_cnt >= 3:
locked = True
break
else:
break
I left out the prints for clarity of flow
The following code should work for you.
answer = "1234"
valid = False
count = 0
while not valid and count < 3:
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if user == answer:
print("You have cracked the code, well done")
valid = True
elif count < 2:
print ("that is incorrect, please try again")
else:
print ("You have been locked out")
count += 1
I took the () off of the strings because that would make them sets so the if statement would never be true, because sets don't equal string inputs.
The following code, is the one I want it to be capitalized. Meaning once the user inputs their answer to the licence plate, I want it to be outputted in capitals:
ask2 = ""
plate = ""
if int(ask) == 1:
stop = False
time.sleep(0.5)
print("========================================================================")
while not stop:
ask2 = input("Please enter it in such form (XX00XXX): ").lower()
valid = re.compile("[a-z][a-z]\d\d[a-z][a-z][a-z]\Z")
# b will start and end the program, meaning no more than 3-4 letters will be used.
# The code which tells the user to enter the right format (keeps looping)
# User can exit the loop by typing 'exit'
# This is the default exit_message
exit_message = "Verification Failed!"
while (not valid.match(ask2)) and (ask2 != 'exit'):
time.sleep(0.5)
print("========================================================================\n", exit_message,
sep="")
print("You can exit the validation by typing 'exit'.")
time.sleep(0.5)
print("========================================================================")
time.sleep(0.5)
ask2 = input("Or stick to the rules, and enter it in such form (XX00XXX): ").lower()
if ask2 == 'exit':
exit_message = "Verification Stopped!"
stop = True
break
I already have constructed a code to make it capitalized, this is it; however I have no idea where to put it:
var = input("no caps: ")
def isvalid(s):
for i in s:
if i in "ABC...XYZ":
return False
return True
while not isvalid(var):
def isvalid(s):
for i in s:
if i in "ABC...XYZ":
return False
return True
Thank you for the help.
Simply use the upper() method.
>>> "hello".upper()
'HELLO'