Program to prompt password - python

I'm trying to create this python program that will prompt the user to enter a password. However, the password has to be between 6 and 12 characters. Also it must have a "#" in it but not in the first character or last. This is what I have so far, I'm not sure what I'm doing wrong I just keep getting the "Not a valid password" response. Any help would be greatly appreciated. Thank You
# This program will determine whether a password meets all security requirements
import re
print ("Hello, please enter a password between 6 and 12 characters.")
print ("The password may consist of a combination of numbers and letters, but the one of characters (after the first and before the last) must be a # sign.")
password = input("Please enter your password: ")
x = True
while x:
if (len(password)<6 or len(password)>12):
break
elif not re.search("[a-z]", password):
break
elif not re.search("[0-9]", password):
break
elif not re.search("[A-Z]", password):
break
elif not re.search("[#]", password):
break
else:
print("Valid Password")
x = false
break
if x:
print("Not a valid password")

# This program will determine whether a password meets all security requirements
import re
print ("Hello, please enter a password between 6 and 12 characters.")
print ("The password may consist of a combination of numbers and letters, but the one of characters (after the first and before the last) must be a # sign.")
is_valid = False
while not is_valid:
password = input("Please enter your password: ")
if (len(password)<6 or len(password)>12):
print('Password is the wrong length')
continue
if not re.search("[a-z]", password):
print('Password missing lowercase letter.')
continue
if not re.search("[0-9]", password):
print('Password missing a number.')
continue
if not re.search("[A-Z]", password):
print('Password missing uppercase letter.')
continue
if re.search("^#", password) or re.search("#$", password):
print('Password cannot begin or end with #.')
continue
print("Valid Password")
is_valid = True
I think this is roughly what you're trying to do, you can improve it to fit your use case. The way you have your loop currently it will only ever run once, the break statement exits the loop if it hits one of your conditions. The while statement never gets a chance to check the x variable you set to false.
I modified the loop so it will repeatedly prompt until the password fits the format you specified. You could also add a prompt to quit or try another password for a better user experience. I modified your # check so the regex checks if it is either at the beginning or the end of the password.
Also I changed all your conditions to if statements. The order the conditions are checked is important, and could potentially hid a false condition. Like the classic FizzBuzz problem.

Related

Password verification in Python

I am studying Python for a little while and trying to resolve following problem:
Part of verification routine is given below. When the user enters the password, it is checked to ensure it is between 8 and 15 characters and then requested to verify the password by typing it again. Require complete task(a) CONDITION 1, CONDITION 2, and task (b) IF ... ELSE statement. Code and test the program.
password1 = input("Please enter a new password, between 8 and 15 characters: ")
match = False
while CONDITION 1
while CONDITION 2
password1 = input ("Password must be between 8 and 15 characters - please re-enter: ")
endwhile
password2 = input ("Please verify password: ")
if ....
print
else
endif
endwhile
I complete the task (b) but in task (a) I have a problem with while loop condition "while match:". When I leave variable match = False and enter the password with required amount of characters the loop terminates straight away and does not do verification with if .. else statement. If I write match = True and on first attempt enter incorrect number of characters (with correct number it terminates the loop again) program goes for verification anyway ignoring the number of characters. If the password was the same (example 111 and 111) it goes back to the loop and asks again for the password with required amount of characters. Then if I enter after the right amount of characters and password verification is the same it terminates the program like it suppose to be. I think something with the condition "match" in while loop is not right but can't figure out what it should be. Thanks
password1 = input("Please enter a new password, between 8 and 15 characters: ")
match = True
while len(password1) < 8 or len(password1) > 15:
password1 = input ("Password must be between 8 and 15 characters - please re-enter: ")
while match:
password2 = input ("Please verify password: ")
if password1 == password2:
print ("Password is valid")
break
else:
print ("Password is invalid")
I think like myself you are new to this. I find the following wrong with your code interpretation of the problem:
Condition 1 and 2 are misplaced
If statement is in the wrong loop.
Your match is also not switched.
Check this out:
def password_verification():
password1 = input('Please enter a new password, between 8 to 15 characters: ')
match = False
while match is False:
while len(password1) < 8 or len(password1) > 15:
password1 = input('Password must be between 8 to 15 characters - please re-enter password: ')
password2 = input('Please verify password: ')
if password1 == password2:
print('Password is valid')
match = True
else:
print('Password is invalid')
return match
password_verification()
You are matching only when the first time wrong number of characters were entered. What will happen if in the first time, user enters between 8 to 15 characters? The first while loop will not execute, and hence nothing will execute. Condition1 (length between 8 and 15) must be checked outside the loop, and the second while loop must be kept separate.
pass1 = input('Enter a password : ')
while len(pass1) < 8 or len(pass1) > 15:
print('Incorrect, try again')
pass1 = input('Enter a password : ')
# Program reaches here only if pass1 is between 8 to 15 characters, otherwise first loop will be infinite
pass2 = input('Verify the password : ')
if pass1 == pass2:
print('Valid')
else:
while pass1 != pass2:
pass2 = input('Invalid. Re-enter the correct password : ')
The above code first takes password1, checks if it is within the 8-15 characters range. If it is not, the first while loop keeps on executing. When a valid input is given, it takes password2, and checks for equality. If it matches for the first time, no further while loop is needed. If it doesn't match, the while loop keeps on executing till equal passwords are not provided. Hope this helps!

How to display symbol characters for Python?

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.")

How to make my code break out of loop and actually detect a certain input

I am doing a basic Python assessment on a password vault but am getting errors that I can't seem to solve myself. and btw guys I didn't come here for a grammar and punctuation lesson, so if you are just here to edit my question and not offer any assistance please dont bother.
For example, in this part of the code I want the user to input 1 or 2, and if he selects 1 it asks him to log in, while if he selects 2 it asks him to register. But at the moment it is completely ignoring the parameters and accepting anything.
Another problem is that when the user enters the valid password, instead of just stopping at password correct, it for some reason re-asks "what is your username."
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()
----------------------------------------------------------#Full code begins now
l_p = ""
print("------------------------------------------------------------------------")
print('''Welcome to password Locker, a place where you can
store all your passwords to easily enter your precious accounts without
hassle.''')
print("------------------------------------------------------------------------")
print('''First lets make an account,''')
while True:
first_name = input('''What is your first name?
''')
if first_name.isdigit(): #isdigit, detects if there
print("Please enter a valid answer, No nubers shoud be present")
elif first_name == "":
print("Please enter an answer")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break #the break loop exits the current loop and continues with the next programes following it
while True:
sur_name = input('''What is your surname?
''')
if sur_name.isdigit(): #isdigit detects if the
print("No numbers")
elif sur_name == "":
print("Please enter an answer")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break
print('''------------------------------------------------------------------------''')
print('''Welcome, {} {}
what would you like your username to be, it should be something
memorable and no longer than fifteen characters long, '''.format(first_name, sur_name))
while True:
input_username = input("")
if 0 < len(input_username) < 16:
print('''Nice, username''')
break
elif input_username == "":
print("Please enter an answer")
else:
print('''Your username should be a maximum of 15 charecters, ''')
print('''-------------------------------------------------------------------------''')
while True:
input_lockerpassword = input('''Now it's time to setup a password for your locker, It should be between 4
and 10 charecters long,
''')
if len(input_lockerpassword) > 4 and len(input_lockerpassword) < 11:
print('''{}, is locked in thanks for joining Password Locker'''.format(input_lockerpassword))
break
else:
print("It should be between 4 and 10 charecters long!")
print('''
-------------------------------------------------------------------------------------------''')
def login_originup1():
print(''' Welcome to password vault, You can either login or create a New account''')
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()```
Ok, first of all, you should know that the input() function returns a string and, as such, your first condition : if login_orsignup1 != 1 will always be true, because the string object '1' isn't equal to the int object 1. As for why you get asked again for the user after having a good password, that is because the break statement only breaks from the current loop. So you only break of this loop to get back at the start of your username verification loop. I would suggest a cleaner implementation like so :
# login or sign-up loop
while True:
login_orsignup1 = input(" Press \n1) to Log in \n2) to register a new account")
# you can have the input result in a variable like so, if you want to use it later on
if login_orsignup1 == "1": # you said '1' was for login, right?
# or you can test this directly in your if statement
# if it is only needed for this condition
while input("What is your username: ") != username:
print("Incorrect username")
# same thing for password, but could be implemented another way if you
# don't want to loop until the user gets the correct password
while input("What is your password: ") != input_lockerpassword:
print("Incorrect password for this username")
# your code gets here only if the user entered the right credentials
# so you can now break of the login or sign-up loop
break
elif login_orsignup1 == "2":
# code for registration here
This could be good enough for a simple thing. I would recommend designing this console program by following concepts of a state-machine and adding more code at each step to handle cases like going back one step or back at the start.
Hope this helps
the problem is in your login_originup1 function you are making three While loops that the program can't escape from in your function you are asking if login_orsignup1 != 1
without an else statement so if the user wanted to login he would press input in "1" then the program will say that
"1" =! 1 is false
it will look for an else statement But not find one so it will go back to the start of the loop and ask the user to input again. this is it for the First Loop.
Now if the user Inputs in "2" (which means that the user wants to register) it will make him log-in because:
"2" =! 1is true
and will continue to the next while loop in here you will be asking for the username and the user will give the username. Now this is it for the Second Loop
we now go to the last loop where you ask for the Password and the User Will give the Password. The program Will either 1. say that it was false and ask for the password again or 2. it will accept the password and Break the While loop. Now this is it for the Third Loop
so why is it asking me for the Username Because the break statement breaks only the while loop it is in so that break statement broke only the third while loop and was back to the Second Loop which the Second Loop will bring us back into the Third Loop again
so how to fix this?
simple like this:
def login_originup1():
print('Welcome to password vault, You can either login or create a New account')
while True:
login_orsignu = input('Press\n1) to Log in\n2) to register a new account\n')
loopBreaker = 0
if loopBreaker:
break
if int(login_orsignu) != 1:
while True:
if loopBreaker:
break
username = input('What is your,\nUsername:')
if input_username == username:
l_p = input('What is your password ')
while True:
if loopBreaker:
break
if l_p == input_lockerpassword:
print("Password Correct")
loopBreaker = 1
break

Identifying special characters in password verification in python

I am working on an assignment for password validation where the program keeps asking the user for a valid password until one is given. I am having trouble checking the input string for special characters. Currently the program accepts the password even if their is no special characters. Also I would like to implement a feature that terminates the loop after 3 unsuccessful attempts but am not sure which loop to implement the count in.
Here is my code:
import re
specialCharacters = ['$', '#', '#', '!', '*']
def passwordValidation():
while True:
password = input("Please enter a password: ")
if len(password) < 6:
print("Your password must be at least 6 characters.")
elif re.search('[0-9]',password) is None:
print("Your password must have at least 1 number")
elif re.search('[A-Z]',password) is None:
print("Your password must have at least 1 uppercase letter.")
elif re.search('specialCharacters',password) is None:
print("Your password must have at least 1 special character ($, #, #, !, *)")
else:
print("Congratulations! Your password is valid.")
break
passwordValidation()
There is no need to use regular expression for something so simple. How about:
elif not any(c in specialCharacters for c in password):
or
specialCharacters = set('$##!*')
...
elif not specialCharacters.intersection(password):

How to check the "password" for numbers in python

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.

Categories