I have did a little research around "Google", "YouTube", "Facebook" and "Stack Overflow" and I haven't found what I was looking for. So, I need your guidance. :)
I want program to ask user input "PASSWORD" and every time user inputs wrong password the program asks password again, and again, and again until user
types the correct password. Let's say that the password is as simple as "abc123".
So, I start the program and it asks to input: "PASSWORD: ". If user types "abc123" then program prints "GOOD PASSWORD". If user types anything what is not "abc123" then program prints "BAD PASSWORD". As simple as that.. for now.
My best attempt:
#SECTION1_ASKING
passwordInput=input('PASSWORD: ')
password='abc123'
while password == passwordInput:
print('GOOD PASSWORD')
break
else:
print('BAD PASSWORD')
passwordInput=input('PASSWORD: ')
#SECTION2_RE-ASKING
while False:
while password == paswordInput:
print('GOOD PASSWORD')
else:
print('BAD PASSWORD')
passwordInput=input('PASSWORD: ')
but I either make password asked once or twice or I stuck in Infinite while Loop.
Try this:
passwordInput=raw_input('PASSWORD: ')
password='abc123'
while True:
if password == passwordInput:
print('GOOD PASSWORD')
break
else:
print('BAD PASSWORD')
passwordInput=raw_input('PASSWORD: ')
You can do as below in few lines.
password='abc123'
while(True):
passwordInput=input('PASSWORD: ')
if(passwordInput==password):
print("Good password")
break
else:
print("Bad password")
Here is my solution:
password = 'abc123'
while True:
passwordInput = input('PASSWORD: ')
if password == passwordInput:
print('GOOD PASSWORD')
break
else:
print('BAD PASSWORD')
How does that differ from yours? For a start you can see that I only have one call to input(), that's generally a good idea because then you only need to check the password in one place. Notice that I use if instead of while for the test.
In your second example you have while False:. Can this ever be True? No, so it won't get executed.
Notice as well that I use more whitespace. That does not slow the program down, it makes it easier to read. See also PEP008
Now you have it working, just for fun, consider an improvement. Normally you don't want the password to be visible when it is typed, but there's a module for that: getpass - it's part of the standard library so you don't need to download anything.
Add import getpass to the top of your script. Instead of input use getpass.getpass, in the same place in the program, with the same parameters. Now it won't echo the password entered by the user.
getpass is the module name, getpass is also a function name, so getpass.getpass('PASSWORD: ') means execute the getpass() function in the getpass module. We use lots of modules in Python, so its worth getting used to using them. You can find the documentation here, note there is also a getpass.getuser() to play with.
Related
so i have this code
pa=""
newpa=""
use=''
use=input('enter username:')
pa=input('enter password')
while True:
if len(pa)==12:
newpa=input('re-enter password:')
else:
print('the password used did not meet our system requirements, please enter a 12 digit password')
if newpa==pa:
print('you have successfully created a new account!')
whenever I insert a pa that's incorrect the else print keeps looping. How do I make it so whenever I enter a pa that doesn't meet the if to loop back to newpa
if this help this is my algorithm alogrythm of what I am trying to go for
First thing to do would be the put the input statement inside the while loop. At the moment your code loops back to the top of the while loop without giving the user a chance to re-enter their password.
You'll also want to move the check for the re-entry part so that it only executes if the first password was valid. And let the user know if their passwords didn't match.
Finally, you'll want to break the loop when a valid password is entered and verified. Use break for this.
The final code would look like this:
pa=""
newpa=""
use=''
use=input('enter username:')
while True:
pa=input('enter password')
if len(pa)==12:
newpa=input('re-enter password:')
if newpa==pa:
print('you have successfully created a new account!')
break
else:
print('the passwords did not match!')
else:
print('the password used did not meet our system requirements, please enter a 12 digit password')
Hope that helps and makes sense!
Your loop will run continuously until you add break statement.
You can try something like below,
pa=""
newpa=""
use=''
use=input('enter username:')
while True:
pa=input('enter password')
if len(pa)==12:
newpa=input('re-enter password:')
if newpa==pa:
print('you have successfully created a new account!')
break
else:
print('the password used did not meet our system requirements, please enter a 12 digit password')
When you enter in the last if you want to exit from loop. So, add break after print.
if newpa==pa:
print('you have successfully created a new account!')
break
Use a while True loop and break from that loop if the password meets the requirements. Then you can enter the password a second time and compare if both inputs match.
username = input('enter username:')
while True:
password = input('enter password')
if len(password) == 12 and password.isdigit():
break
print('the password used did not meet our system requirements, please enter a 12 digit password')
password_check = input('re-enter password:')
if password == password_check:
print('you have successfully created a new account!')
You might want to wrap that in an additional loop if the passwords don't match.
If you use functions you can reduce the complexity of the main part.
def enter_password(message):
while True:
password = input(message)
if len(password) == 12 and password.isdigit():
break
print('the password used did not meet our system requirements, please enter a 12 digit password')
return password
def main():
username = input('enter username:')
while True:
password = enter_password('enter password')
password_match = enter_password('re-enter password')
if password == password_match:
break
print("The passwords don't match.")
print('you have successfully created a new account!')
if __name__ == '__main__':
main()
Please use break to break the statement and continue to continue the loop statement according to your requirement. I hope the following code meets your requirement. Thanks and let me know if there's anything I can help with.
user=input('enter username:')
while True:
pa=input('enter password:')
if len(pa)==12:
newpa=input('re-enter password:')
while newpa!=pa:
newpa=input('re-enter password:')
else:
print('the password used did not meet our system requirements, please enter a 12 digit password')
continue;
if (newpa==pa):
print('you have successfully created a new account!')
break;
I am self-teaching myself python and have run into a problem that I can not seem to find a way around.
I have created a piece of code that compares an entered password to one stored in a database.
My code should have two possibilities.
1) If the password is correct.
The user is prompted to enter a new password and then the prompt to enter the password must appear again (This time accepting the new password).
2)If the password is incorrect the user will be prompted to enter the password until the correct password is entered.
In VBS I used to be able to use the GOTO command.
I am not sure if this is available in Python and if it is I would like to avoid using it as it creates a very illogical hard to follow the program.
password = "#123"
entry = input("Please Input The Password:")
if (password == entry):
entry = input("Password correct you may enter a new password.")
else:
entry = input("Password Incorrect, Try again.")
There are various ways you could complete this. Here is a simple way you could achieve it using while loop and break statement.
password = "#123"
while(True):
entry = raw_input("Please Input The Password: ")
if (password == entry):
print("Password correct you may enter a new password.")
break
else:
print("Password Incorrect, Try again.")
Hope it helped.
while password != entry: # Executes until (password == entry), and does not execute if it is met, even for the first time.
print('Sorry, wrong password.')
entry = input('Enter password >') # or other source of data
print('Correct!')
Edit: additional ways you can do this:
while True: # forever loop, but
entry = input('Enter password >') # or other source of data
if password == entry:
print('Correct!') # you can also put this outside of the loop
break # exit the loop no matter what
# do not put code after the break statement, it will not run!
print('Sorry, wrong password') # will execute only if password != entry, break ignores the rest of the code in the loop
Easiest to make a function with a while statement.
password = "#123"
def login():
while True:
answer = input("Please Input The Password:")
if answer == password:
print("Password correct you may enter a new password.")
else:
print("Password Incorrect, Try again.")
break
login()
so I am trying to create a program that will allow a user to login using a username and password for a school project. however, my teacher (he has allowed me to ask FYI) wants us to think of a way to make it secure.
so my thought process is that I would allow the user to create a login and store the usernames and passwords in a notepad file. to make these secure I decided to use the hash() function so that the username and passwords couldn't be seen even if the text file was accessed. the issue that I am running into is that I can't figure out how to get the program to see the saved hash version of the username and password in the text file and then compare it to the inputs for longing in without printing the hashes and or saving them as variables.
I can't do this however because if I have more than one login saved in the login file I cant save all the hashed logins as one variable.
if anyone can help it would be greatly appreciated
import sys
import time
print ("welcome to this quiz.")
account = input ("first off do you have a account already. please enter yes or no only").lower
if account == no:
account_create = input ("to continue with this quiz you need a password would you like to create a account. please enter yes or no only").lower
if account_create == no:
print (" the program will close in 30 seconds. if you change your mind come back and make an account")
time.sleep(30)
sys.exit
else:
print ("thank you for creating an account")
username = input ("first off you need a username. please enter a username. be carefull once it is chasen it cant be changed")
# need to add a function that searches the login file and compares no username is repeated
password = input ("secondly you need a password. please choose a password. be carefull you can change it later but you will need the current one to do this.")
username = hash(username)
password = hash(password)
file = open("Login.txt","w")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
print ("Your login details have been saved. ")
print ("now please login")
else:
login? = input ("would you like to login to the program").lower
if login? == no:
print ("please come back another time")
time.sleep(20)
sys.exit
else:
username_check = input ("please enter your username")
password_check = input ("please enter your username")
username_check = hash(username_check)
password_check = hash(password_check)
file = open("Login.txt","r")
if username_check ==
Load the file as a dictionary mapping usernames (or their hashes) to the hash of the password.
You can iterate through the file and load each line into your dictionary.
However this will be a bit fragile. What if some user want to have a space or comma in their username. A better and easier approach is to use a library to serialize and deserialize the dictionary. The common one used in python would be pickle or if you want the data to still be somewhat human readable json.
This question already has answers here:
Getting a hidden password input
(6 answers)
Closed 7 months ago.
I have been trying to make a secure login on a python program I've been working on, but everything I try doesn't seem to help. I need a snippet of code that I can put in my script. My main issue is that anyone who looks at my script can just see the password. Plus I don't know how to put stars instead of characters when they type in password. This is my login code, it is very basic because I'm pretty much a beginner.
#login
import webbrowser as w
def username():
print("Enter UserName")
usrnm = input()
if(usrnm == "example"):
password()
else:
notusername()
def notusername():
print("Try Again")
username()
def password():
print("Enter Password")
pswrd = input()
if(pswrd == "password"):
w.open("www.example.net")
else:
notusername()
username()
First, let me preface this by saying that, especially if you're a beginner, it is usually not a good idea to try to implement your own login/security code for anything that is public and seriously needs security.
Having said that, the general approach to hiding the actual password is to store a hash (e.g. SHA-1) of the password, not the password itself. You can then safely store that hash value wherever you like (e.g. database, text file etc.)
In python you can do this using something like hashlib e.g.
import hashlib
sh = hashlib.sha1()
sh.update('password')
hash_value = sh.hexdigest()
# write hash_value to file/db...
When you go to validate against the stored password, you take the hash of the user input and compare it against the stored hash. If they are the same, then the password is correct.
Again, for any serious security, use one of the many frameworks that are available, as they have been tested by many people.
You Should try this code
list1 = ('Password is Correct...' , 'Password is Incorrect' , 'Closing Python...','Hello',
'''Press Enter to Continue...''', 'Closing Python...' , 'badger123',
'''Please Enter Your Name: ''', 'Please Enter Your Password: ')
name = input(list1[7])
password = input(list1[8])
if password == list1[6]:
print(list1[0])
else:
print(list1[1])
exit()
import time
time.sleep(0)
input(list1[4])
time.sleep(0)
print (list1[3] , name)
import time
time.sleep(1)
print (list1[5])
import time
time.sleep(5)
input (list1[4])
exit()
I am doing a fun little project, making a kind of secret code program with a GUI(Tkinter) to encrypt my text(not very securely). I am trying to make a password on this program linked to a txt file. The program has default password 'abc', stored in a text file in sha-224. When the user enters 'abc', it will hash their input in sha-224, and compare it to the stored password in _hexutf2.txt. Once they have logged in, the user will have the option to choose a new password by clicking New Passcode, entering their previous passcode, clicking next, and then clicking new code. After clicking new code, the user enters a new passcode in the entrypassVariable, then clicks enter passcode, which will write the new passcode on the txt file. Instead, the program hangs on the first pressing of Enter passcode, despite the fact that I had entered 'abc' the default passcode. The program worked before I added the password element, so I will post only the password code here, but I will link to the entire program if anyone wants to see it.
EDIT
Posting just the essential code here. The problem in my main program is caused by this. For some reason, this program prints this:
Stored Password: cd62248424c8057fea8fff161ec753d7a29f47a7d0af2036a2e79632
Enter Password: Moo
Password Attempt Hash: cd62248424c8057fea8fff161ec753d7a29f47a7d0af2036a2e79632
Password Incorrect
http://snipplr.com/view/75865/cryptographer/ <----Entire program code
import hashlib
passfile = open('pass.txt','r')
stored_password = str(passfile.read())
print 'Stored Password: ' + stored_password
password = raw_input('Enter Password: ')
enter_pass_sha = hashlib.sha224(password)
enter_password = str(enter_pass_sha.hexdigest())
print 'Password Attempt Hash: ' + enter_password
if stored_password == enter_password:
print 'Password Correct'
else:
print 'Password Incorrect'
You should have noticed this:
Stored Password: cd62248424c8057fea8fff161ec753d7a29f47a7d0af2036a2e79632
# blank line?!
Enter Password: Moo
Password Attempt Hash: cd62248424c8057fea8fff161ec753d7a29f47a7d0af2036a2e79632
Password Incorrect
When you read the stored_password in from the passfile, it comes with a newline character '\n' at the end. You need to do:
with open('pass.txt') as passfile:
stored_password = passfile.read().strip()
print 'Stored Password: ' + stored_password
Note str.strip, called without arguments, removes all whitespace, including newlines, from the start and end of the string. Note also the use of the with context manager for file handling, which handles errors and closes the file for you.
One issue is hexCode = passfile.read - that's a bound method, not a string (you never called it with ()). This will not match any of your strings, and causes an exit from OnPassClick or OnNextClick, or a funny message from OnNewClick. Similarly, you raised the class SystemExit type instead of an instance of it.