Password Checker loop not working - python

I have tried to create an app in Python that makes a user create a password and then makes them verify it. Obviously I had to create a loop so that when the user entered an unmatching password they had to try again. I am not very experienced with loops so here is what I got. How do I make this work?
here is the code:
password = raw_input ("Create a password: ")
passwordv = raw_input ("Retype your password: ")
a = ("Passwords don't match! Please try again!: ")
b = ("Congrats, you have created a password")
def password():
if password == passwordv :
print ("Congrats, you have created a password")
else :
print (a)
return password
return passwordv
while password !=passwordv:
print (a)
here is another set of code trying to do the same thing:
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
while (password != passwordv):
print raw_input('Passwords do not match, try again: ')
if (password == passwordv) :
print ('Password set')
break

Your conditional to test whether the passwords match was included in the loop which checks that they don't match -- so, it never gets run.
Try this instead:
password = raw_input('Create a password: ')
passwordv = raw_input('Verify your password: ')
while (password != passwordv):
print raw_input('Passwords do not match, try again. ')
password = raw_input('Create a password: ')
passwordv = raw_input('Verify your password: ')
continue
print ('Password set')
Note how only the code that should be run if the passwords don't match is included within the while loop.

What you need here is an "N and a half times loop". To avoid repeating code (guided by the DRY principle) you might consider writing a function to get the passwords. The following might work:
def get_passwords():
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
return password, passwordv
pw1, pw2 = get_passwords()
while pw1 != pw2:
print "Sorry, passwords do not match"
pw1, pw2 = get_passwords()
The loop won't be entered at all if the original passwords match. Otherwise it will repeat until they do.

password=raw_input('Enter password: \t\t\t')
passwordv=raw_input('Enter password again to verify: \t')
if password == passwordv:
print "\ncongratz you have created password"
else:
print "\nPlease try again...!"
while password != passwordv:
password=raw_input("Enter password: \t\t\t")
passwordv=raw_input("Enter password again to verify: \t")
if password == passwordv:
print"\ncongratz you have created password"
else:
print"\nPlease try again...!"
I know this one is long, It is just for basic understanding

The other answers provide the code that will do what you want. I thought that it could be interesting to tell you a little bit more what was wrong with the code you provided because the problem is more about your understanding of how things work.
1st attempt: a variable and a function have the same name
# Here you define your password variable as a string
password = raw_input ("Create a password: ")
[...]
# And then you reassign it here: it contains now the address of that function!
def password():
[...]
# Now you're comparing a function to a string: they'll never be equal
while password !=passwordv:
[...]
This could have been avoided simply by changing the name of your function (which is never called by the way so I'm not sure what you wanted to do but I thought you might find that interesting). Further reading: Python: function and variable with same name
2nd attempt: the values of the variables stay the same
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
# At this point, if the test is true, you'll reach the end of the code without
# displaying the 'Password set' message you wanted
while (password != passwordv):
# This only prints a message
print raw_input('Passwords do not match, try again: ')
# The condition below can never be true: you just tested that they were
# different but did nothing to give them new values!
if (password == passwordv) :
print ('Password set')
break
The way to fix that is what the other answers provide: take your message out of the loop (getting out of the loop means that your condition was met) ; make sure that you do something inside the loop that will assure that the next test will be different from the previous one (otherwise, you will end up testing the same values over and over again) ; to avoid breaking inside the loop, set your values outside the loop, and then get new values inside the loop in case the initial test failed.

Here's an idea:
First define these:
MinPass = 6
MaxPass = 12
Then this:
print ("Now, lets try with a password. Please enter one here")
EnteredPassword = input("Password: ")
while len(EnteredPassword) < MinPass:
print ("That password is too small. Please try again")
EnteredPassword = input("Password: ")
while len(EnteredPassword) > MaxPass:
print ("That password is too long, please try again")
EnteredPassword = input("Password: ")
Hope this helps!

Related

How can I see if my password variable is within a line so that my code can proceed?

I am creating a password re-setter for school, and i want to check that if the password is within the first line of the text file, then it can say "Okay, choose a new password")
Newpass=""
Network=""
setpass=""
Newpass=""
password=""
def newpass():
Network=open("Userandpass.txt")
lines=Network.readlines()
password=input("just to confirm it is you, re-enter your old password:")
for i in range (3):
if password in line:
newpass=input("Okay, choose a new password ")
Network.close()
Network=open("Userandpass.txt","a")
if len(newpass)>= 8 and newpass[0].isalnum()==True and newpass[0].isupper()==True:
print('password change successful')
Network.write("New Password : " + newpass )
Network.close()
break
else:
print("password did not match requirements, try again ")
else:
print("error")
break
print("3 tries up or else password updated")
Network=open("Userandpass.txt","w")
Network.write(input("What is your Username")+",")
Network.write(input("Password:")+ ",")
question=input("Do you want to change your password?")
if question=="yes":
Network.close()
newpass()
else:
Network.close()
print("Okay thank you.")
Please help! I have been looking all over here and i can't find a solution
You can try by two things :
lines=Network.read() # change here
password=input("just to confirm it is you, re-enter your old password:")
for i in range (3):
if password == lines.split(",")[1]: # change here also
Explanation :
The problem with readlines is o/p as list where read return as string which is better one to use here .
The second thing it returns as a single string ie, combined form of name and password just with ,. So if you split it you will get an list of separated values. Then you can take only password from it and check with input.
In your code you are just checking the input element is just present in that whole string, not checking whether it is same password or not
You said you needed this for school, so i assume it's somewhat urgent:
All the changes i did are minor and i commented what i did and why.
# no need to intialize these variables
#Newpass=""
#Network=""
#setpass=""
#Newpass=""
#password=""
def newpass():
# the with open() construct takes care of closing the file for you and gives you a nice handle for working with the file object.
with open("Userandpass.txt") as Network:
# this reads all filecontents into a list and while doing so strips away any kind of whitespace.
username,current_password=[x.strip() for x in Network.readlines()]
for i in range (3):
password=input("just to confirm it is you, re-enter your old password: ")
if password == current_password:
# communicate the requirements instead of letting potential users run into errors
newpass=input("Okay, choose a new password (must be 8 chars or more, alphanumeric and have it's first letter capitalized.) ")
if len(newpass)>= 8 and newpass.isalnum() and newpass[0].isupper():
with open("Userandpass.txt","a") as Network:
print('password change successful')
Network.write("New Password : " + newpass )
return
else:
print("password did not match requirements, try again ")
else:
print("error")
break
print("3 tries up or else password updated")
with open("Userandpass.txt","w") as pwfile:
# separate by newline instead of punctuation => personal preference
pwfile.write(input("What is your Username? ")+"\n")
pwfile.write(input("Password: ")+ "\n")
question=input("Do you want to change your password? (yes/no): ")
if question[0].lower() == 'y':
newpass()
else:
print("Okay thank you.")
# properly terminate
exit(0)
You are missing an 's' in the line
if password in line**s**:
maybe the problem comes from there.

Dictionary search results in key error in Python

I've looked up similar stackoverflow questions but none are quite like this.
Quite simply, I have the following code that seeks to look up a dictionary for a username and corresponding password. If they match, then access granted and go to the loggedin function, else access denied.
Having set it up like below, it works perfectly when the credentials are correct, but on getting them wrong, results in a key error:
Code
username=input("Enter username:")
password=input("Enter password:")
accessgranted=False
while accessgranted==False:
if userinfo_dict[username]==password:
loggedin()
accessgranted==True
else:
break
print("Sorry, wrong credentials")
main()
Error
if userinfo_dict[username]==password:
KeyError: 'ee'
The file is simply:
user1,pass1
user2,pass2
Could someone please
a) Correct and comment on the error
b) Suggest alternative or more efficient ways of achieving the same thing
The problem is, as many others already pointed out, you are trying to get the value for a non-existing key.
An easy workaround would be to check if userinfo_dict[username] == password only if username is an existing key.
username = input("Enter username:")
password = input("Enter password:")
access_granted = False
while access_granted is False:
if username in userinfo_dict.keys() and userinfo_dict[username] == password:
loggedin()
access_granted = True
else:
break
print("Sorry, wrong credentials")
main()
Edit: access_granted flag is useless, you could do just:
username = input("Enter username:")
password = input("Enter password:")
if username in userinfo_dict.keys() and userinfo_dict[username] == password:
loggedin()
else:
print("Sorry, wrong credentials")
You could check that both the username and passwords are in the dictionary and that they are a key-value pair, with the following:
#Check that both username and password in dictionary
if username in userinfo_dict.keys() and password in userinfo_dict.values():
if userinfo_dict[username] == password:
accessgranted = True
else:
print('Access Denied') #Print if either username or password not in dictionary
The keys() method returns a list of the keys in the dictionary whereas the values() method returns a list of the values in the dictionary.
Almost always use dictionary.get(key) instead of dictionary[key]. The former is safe for when keys don't exist (like in this case) while the latter will throw an error.
if userinfo_dict.get(username) == password: # returns None is key doesn't exist
loggedin()
accessGranted=True
else:
break
What the error is telling you is that you have entered the value "ee" for the user name, but there is no user named "ee" (that is, no key-value pair with the key "ee") in the dictionary. This is the expected result when attempting to get the value for a non-existent key.
The correct python idiom for testing for the presence of a key is:
if user_name in userinfo_dict:
I concur to the above. The problem is with getting the non-existing key. Try it either:
via try/except block,
via dictionary get() method.
Also the code requires a bit of refactoring e.g.:
checking to False via 'is' a;
accessgranted==True should be assignment, not comparison;
the logic of loop had to be changed as well.
See below:
username = input("Enter username:")
password = input("Enter password:")
access_granted = False
while access_granted is False:
if userinfo_dict.get(username) == password:
# loggedin()
access_granted = True
else:
print("Sorry, wrong credentials")
break
# main()

Login system on Python

This is a really newbie question.
So, I am trying to code a login system in Python, where it asks for an username (only 1 username available), if the username typed in is incorrect, it says the username is invalid, if it is correct, it asks for a password, if the password is incorrect, it says incorrect password and proceeds to ask for the password once again, and if the password typed in is correct, it just says logged in.
What I've been able to do so far is:
a = 0
while a < 1:
print ('Username:')
name = input()
if name != 'Teodor': #checks the username typed in
print ('Invalid username.')
continue
else:
print ('Hello, Teodor.')
print ('Password:')
a = a + 1
password = input()
b = 0
while b < 1:
if password != '1234': #checks the password typed in
print ('Password incorrect.')
b = b + 1
continue
else:
print ('Password correct.')
print ('Logging in...')
print ('Logged in.')
break
This works, although it does something I don't want if the user types in the incorrect password. If the user types in the incorrect password, I wanted the program to tell the user 'Incorrect password' and proceed to ask for it once again, but it doesn't do that, it just prints 'Incorrect password', and then it terminates. It works 100% on the part where it asks for the username, though.
It's a little thing I am missing. How can I fix this?
Thanks a lot!
The statement b = b + 1 is terminating your while loop every time the user enters an incorrect password. There is really no need for it.
You can alternatively just wrap your password prompt in a while loop:
while input("Enter password") != "1234":
print("Password incorrect")
There is no need for the + 1 when checking for the password. That just breaks you out of the loop.
Instead, try:
if password != '1234': #checks the password typed in
print ('Password incorrect.')
continue
A much better solution, instead of using +1 and <1 to break out of loops is to use booleans.
Sample:
userCorrect = False
while not userCorrect:
print ('Username:')
name = raw_input()
if name != 'Teodor': #checks the username typed in
print ('Invalid username.')
continue
else:
print ('Hello, Teodor.')
print ('Password:')
userCorrect = True
password = raw_input()
passCorrect = False
while not passCorrect:
if password != '1234': #checks the password typed in
print ('Password incorrect.')
print ('Password:')
password = raw_input()
else:
passCorrect = True
# Since password is correct, continue.
print ('Password correct.')
print ('Logging in...')
print ('Logged in.')
This loop (while b < 1:) terminates the moment an invalid password is entered.
Look at
> if password != '1234': #checks the password typed in
> print ('Password incorrect.')
> b = b + 1
> continue
The line of code b = b + 1 makes it such that while b < 1: becomes false, thus ending the loop and terminating your program.
As others have already pointed out, the problem lies is b = b + 1 breaking the condition while b < 1:, causing it not to ask for another password. Simple delete the line b = b + 1
Want to make it better?
Avoid the 'over-the-shoulder' attack with getpass() instead of input(). Your password input is masked as ****
ex.
from getpass import getpass
password = getpass()
Cryptify
Well, apart from sounding cool, this doesn't really stop somebody from modifying the code to skip past the password phase -but it can stop them from seeing the raw password in the code.
this post has a good example using passlib
This helps protect non-unique/sensitive passwords (like the password you use for 5x other things, or your mother's maiden name... lets not drag her into this)

Python GCSE homework help - password

For my homework I need to make a user registration system in python. I need to make a password section.
What I am meant to do?.
Here is my code, I can't work out whats wrong:
password = input("Please enter your password: ")
passwordl = len(password)
while passwordl <= 8:
print("password must be more than 8 characters - please try agian")
password = input("Please enter your password: ")
passworda = password.isalpha()
passwordi = password.isdigit()
while passworda != True or passwordi != True:
print("password needs to contain digits and characters - please re-enter")
password = input("Please enter your password: ")
The code is in a function btw.
Thanks
The functions isalpha() and isdigit() return true if all the members in the string are alphanumeric and digits, respectively.
What you need to do instead is to check if any characters in the string have the right properties, for example like this:
passworda = any([x.isalpha() for x in password])
passwordi = any([x.isdigit() for x in password])
Additionally, you need to redo all the checks (both length and character set checks) each time when the password is entered anew.
Instead of following
Password = input("Please enter your password")
In the last while loop with the checks over again you would be better just calling the password function as it's more efficient.

Can't Assign to Literal in Python

I'm receiving an error in python that says I, "Can't assign to literal". I was hoping that somebody could help me understand why this is coming up. Here's my code:
# Chapter 3 Challenge part 3
# use the code below and the following
# directions to see if you can solve the problem
# Your Co-Worker has been asked to write a
# 1st time "Log-in" program in which a user has to
# sign in with their user name. If they enter
# the correct id name they need to be asked
# to create their password.
# They were required to make sure the user did
# not leave the username entry blank and must have the
# correct user name or the progam should re-ask
# them to sign in... They cannot figure out what
# to do, so they have called on you to help...
# Here is what they have so far...
# They started their program like this....
# and included some of their documentation.
# Get username, check to see if not empty,
# then verify that username is correct.
# using username "jalesch" as test user.
name = False
while not name:
name = raw_input("Enter your user name: ")
print "Welcome," , name , "you must create a password."
password = False
while not password:
password = raw_input("""Enter a password.
Password must be at least 6 characters in length,
and must include one of these symbols (!, $, ?, &): """)
while len(password) < 6:
for "!" in password or "$" in password or "?" in password or "&" in password:
password = raw_input("""Enter a password.
Password must be at least 6 characters in length,
and must include one of these symbols (!, $, ?, &): """)
print "This has met the requirements."
check = raw_input("Please re-enter your password:")
while check != password:
print "You have entered the wrong password"
check = raw_input("Please re-enter your password:")
print "Welcome to the program!"
# prompt user to create a password that meets the
# following requirements:
# - Must be at least 6 characters in length
# - Must include at least one of these 4 symbols
# - ! $ ? &
# Once the user has entered their password, the program
# must check to see if it meets the requirements.
# If the requirements are not met, it should reask them
# to put in a password that meets the requirements
# until they get it correct.
# Test password is: $program!
# If it meets the requirements then prompt the user
# to re enter the password, and check that the
# first and second entry matches.
# If the 1st and 2nd match. display "Welcome to the program"
# If the 1st and 2nd don't match, re-prompt for the password
# until they get a correct match.
I also believe that the code is malfunctioning when I try to find the special characters, because it is skipping one of the while loops. Any help is appreciated, thanks.
on this line:
for "!" in password or "$" in password or "?" in password or "&" in password:
You probably meant to use if:
if "!" in password or "$" in password or "?" in password or "&" in password:
for x in y iterates over y, assigning each member to x sequentially, running the following indented code in a loop for each member of y. You can't assign a value to "!" because that's a literal character, not a variable.
def get_name(prompt):
while True:
name = raw_input(prompt).strip()
if name:
return name
def get_password(prompt):
while True:
name = raw_input(prompt).strip()
if len(name) >= 6 and (set(name) & set("!$?&")):
return name
name = get_name("Enter your user name: ")
print("Welcome, {}, you must create a password.".format(name))
while True:
print("Now enter a password. It must be at least 6 characters in length, and must include a symbols (!, $, ?, &).")
pass1 = get_password("Enter a password: ")
pass2 = get_password("Please re-enter your password: ")
if pass1 == pass2:
print("Welcome to the program")
break
else:
print("No match! Please try again")

Categories

Resources