This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I'm very new at Python, and I'm trying to make a simple program that asks the user for a password, and if the user didn't guess the password they were asked, ask again until they guess it. How do I do that?
Password = input("guess the password: ")
while (password) != "12345":
Print(input("try again : "))
Welcome to Programming and StackOverflow. Have a look a this Example,
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('Loop ended.')
The break statement ends the while loop.
#g23's Answer is more apt in the context of the question
Make sure your capitalization is right, generally variables are lowercase, but you need to be consistent.
Also when you ask for the password again, you need to store what the user gives you so it can be checked in the loop condition (the while password != "12345": part)
Something like
password = input("Enter the password: ")
while password != "12345":
password = input("try again: ")
This code does what you want. It has a while loop to check if the password was guessed until the right password is entered. Then it has an if statement to write a message: if the right password is entered, it writes it.
password = input("Enter the password: ")
while password != "12345":
password = input("try again: ")
if password == "12345":
print("Correct password!")
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 months ago.
Right now with what I have, even if the password meets all the criteria it prints "Weak password try again!". It allows for another user input but it doesn't break and print "Strong password" if it is strong.
Code:
if (l>= and u>=1 and p>=1 and d>=1 and l+u+p+d==len(s)):
break
print("Strong password")
else:
print(input("Weak password, try again: "))
while True:
passwordName = input("Password ? ")
if (l>= and u>=1 and p>=1 and d>=1 and l+u+p+d==len(s)):
print("Strong password")
break
else:
print("Weak password, try again")
Ok, I'm pretty new to python and I was trying to see if I could make a simple login/register system that just uses usernames and passwords. I added this at the start of the code so I didn't have to manually restart it every time I want to test something:
loop = True
while loop == True:
then, I made two lists called 'accountUsernames' and 'accountPasswords' with just a couple of random usernames and passwords. The idea was that every account would have its password and username index be the same, and the code would check if the username and password the user entered while logging in had the same index. When I started writing the code of the register system, I realized I was kind of stuck. I was using the append feature to add the username and password the user had entered into the previously mentioned lists, but when it did so, the code would loop back to the start because it was over, meaning the lists would also be changed to their previous state. I was wondering if there was a way I could define those lists at the start without giving them any values, or changing the values it already has from the previous loop. Here's the full code:
loop = True
while loop == True:
accountUsernames = ['a', '1']
accountPasswords = ['b', '2']
lr = input('Would you like to login or register?\n')
if lr.lower() == 'login':
loginUsername = input('Please enter your username.\n')
loginPassword = input('Please enter your password.\n')
if loginUsername in accountUsernames:
loginIndex = accountUsernames.index(loginUsername)
if accountPasswords[loginIndex] == loginPassword:
print('You have successfully logged in!')
else:
print('Invalid username or password. Please try again.')
else:
print('Invalid username or password. Please try again.')
elif lr.lower() == 'register':
registerUsername = str(input('Please enter a username.\n'))
registerPassword = str(input('Please enter a password.\n'))
registerPasswordConfirmation = str(input('Please confirm your password.\n'))
if registerUsername in accountUsernames:
print('That username is already taken. Please try again.')
elif registerPassword != registerPasswordConfirmation:
print('These passwords do not match. Please try again.')
else:
accountUsernames.append(registerUsername)
accountPasswords.append(registerPassword)
print('You have successfully registered! You can now log in.')
I know it probably has a lot of glaring issues but as I said, I'm pretty new to python. Also, sorry if I over/under-explained the issue. I would really appreciate your help.
I don't really understand the question, but why don't you define the accountUsernames and accountPasswords before the loop starts, like this:
accountUsernames=[]
accountPasswords=[]
while loop:
#insert loop code here
Another suggestion that you should implement is instead of having two lists, to have a dictionary.
userData={}
def addUser(username, password):
global userData
userData[username]=password
def checkUser(username,password):
global userData
if username in userData:
if password==userData[username]:
return True
return False
loop=True
while loop:
#insert code
Just place the accountUsernames and accountPasswords lists outside the loop like this:
accountUsernames = ['a', '1']
accountPasswords = ['b', '2']
loop = True
while loop == True:
lr = input('Would you like to login or register?\n')
if lr.lower() == 'login':
loginUsername = input('Please enter your username.\n')
loginPassword = input('Please enter your password.\n')
if loginUsername in accountUsernames:
loginIndex = accountUsernames.index(loginUsername)
if accountPasswords[loginIndex] == loginPassword:
print('You have successfully logged in!')
else:
print('Invalid username or password. Please try again.')
else:
print('Invalid username or password. Please try again.')
elif lr.lower() == 'register':
registerUsername = str(input('Please enter a username.\n'))
registerPassword = str(input('Please enter a password.\n'))
registerPasswordConfirmation = str(input('Please confirm your password.\n'))
if registerUsername in accountUsernames:
print('That username is already taken. Please try again.')
elif registerPassword != registerPasswordConfirmation:
print('These passwords do not match. Please try again.')
else:
accountUsernames.append(registerUsername)
accountPasswords.append(registerPassword)
print('You have successfully registered! You can now log in.')
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
After I type in any username and password (doesn't matter whether it's correct or not), it keeps printing another part of the code.
The login part works fine but it doesn't show the correct output afterwards. It continuously shows:
"Incorrect login details entered
Have you made an account?
Yes or No"
This has stumped both my teacher and I. I have looked at different websites with examples of login/registration systems. I have also tried re-arranging the code differently.
This is the code:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
file = open("Usernames.txt","r")
found = False
for line in file:
user = line.split(",")
if user[0] == username and user[1] == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
else:
found == False
print("Incorrect login details entered")
print("Have you made an account?")
ans = input("Yes or No ")
while ans not in ("Yes", "No"):
if ans == "Yes":
print ("Please sign in again")
username = input("Please enter your correct username: ")
password = input("Please enter your correct password: ")
elif ans == "No":
print("Would you like to make an account? ")
else:
ans = input("Please enter Yes or No ")
The expected result when the username and password is correct:
Username: Smartic
~~~~~
Welcome to the game, Smartic
The expected result when the username and password is incorrect:
Incorrect login details entered
Have you made an account?
Yes or No
The expected result when the user enters Yes:
Please sign in again
Please enter your correct username:
Please enter your correct password:
The expected result when the user enters No:
Would you like to make an account?
The expected result when the user enters something other than Yes or No:
Please enter Yes or No
No matter what username you enter, it won't satisfy every username in the file. Every time it doesn't, your error text will be printed. Reformat your code as is described in this question.
There is a new line at the end of each line in the file. You can remove newline by using strip() function.
if user[0] == username and user[1].strip() == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
Change your:
while ans not in ("Yes", "No"):
In:
while True:
Besides I can recommend to make a function.
Also as John Gordon mentioned use breaks, so your script will look like:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
user = {0:'e',1:'w'}
found = False
if user[0] == username and user[1] == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
else:
found == False
print("Incorrect login details entered")
print("Have you made an account?")
ans = input("Yes or No ")
while True:
if ans == "Yes":
print ("Please sign in again")
username = input("Please enter your correct username: ")
password = input("Please enter your correct password: ")
break
elif ans == "No":
print("Would you like to make an account? ")
break
else:
ans = input("Please enter Yes or No ")
break
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
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I'm trying to get the user to enter a password (when making an account for my quiz) and check that the password is over 6 characters. If it isn't, it will loop back and ask the user to try another password. Here's what I've got so far:
def password ():
password = input("enter a password over 6 characters")
count = 0
for letter in password:
count = count + 1
while count < 6:
password = input("password too short try again")
password ()
Here's what I get if my password is long enough:
enter a password over 6 characters longpassword
Here's what I get if my password's too short:
enter a password over 6 characters lol
password too short try again lol
password too short try again longpassword
password too short try again
It doesn't seem to count the characters after the first time and I don't know why.
password = ""
while len(password) < 6:
password = input("....")