I am writing a login function where the user enters their username and if it's wrong it loops back and asks them to enter it again. Same thing for their password.
print('kindly key in your username')
while True:
username = input()
if username != 'tom':
print ('wrong username, please key in your username again')
continue
else:
print('key in your password')
password = input()
if password != '1234':
print('wrong password, key again')
else:
print('access granted')
How can I ask the user to re-enter their password if they type it wrong their first try? Right now this code loops all the way back to asking the user to enter their username if they enter the wrong password.
You'll just need either an inner while loop, or write a helper function to get user input:
def user_input(prompt, target_response):
while True:
user_response = input(prompt + "\n > ")
if user_response != target_response:
print("Incorrect input! Please try again!")
continue
return user_response
Then you can reuse this function to get the username:
username = user_input("Kindly key in your username", "tom")
password = user_input("Please enter your password", "1234")
Just write two separate while loops and break out of each when you get the desired result:
print('kindly key in your username')
while True:
username = input()
if username != 'tom':
print('wrong username, please key in your username again')
else:
break
print('key in your password')
while True:
password = input()
if password != '1234':
print('wrong password, key again')
else:
break
print('access granted')
I don't think we can jump to arbitary positions inside a loop in Python. We could do that in older languages like C and C++ using goto, but this practice is generally frowned upon as it makes the code harder to read and understand. For this reason most of the newer languages don't provide goto.
Your code has another logical error as well. You are not breaking out of the loop even if you input the correct credentials and it will run infinitely, asking you for the credentials again and again.
One thing that you could do is to break up your code into 2 parts, like this:
print('kindly key in your username')
while True:
username = input()
if username != 'tom':
print ('wrong username, please key in your username again')
else:
break
while True:
print('key in your password')
password = input()
if password != '1234':
print('wrong password, key again')
else:
print('access granted')
break
Also as #blorgon pointed out, since you are repeating the same kind of action twice, i.e taking input and checking whether it is correct, you could turn that into a function to keep your code DRY.
Just like you used a while for the whole situation, you can put in a while loop just for the password part,
print('kindly key in your username')
while True:
username = input()
if username != 'tom':
print ('wrong username, please key in your username again')
continue
else:
print('key in your password')
while True:
password = input()
if password != '1234':
print('wrong password, key again')
continue
else:
print('access granted')
break
Additionally, you can avoid the if conditionals by directly using the conditions in the while loop, instead of while True.
Related
while True:
print('enter username: ')
username = input()
if username.lower() != 'joe':
print("imposter!")
continue
print(f'Hello {username.capitalize()}')
print('enter password: ')
password = input()
tries = 0
if password != 'Water':
tries += 1
continue
if tries == 3:
print("3 strikes, you're out")
quit()
else:
break
print("access granted")
Trying to make a username and password prompt. I am trying to give infinite tries to username entries, and only 3 chances for a correct password. When you type in the correct user name and password everything works fine. BUT when typing in the incorrect password, it loops back up to enter username, and the 'tries' counter does not work. python noob trying to learn using Automate The Boring Things in Python
You could try restructuring your code like the below:
import sys
access = False
while not access:
username = input('Enter username: ')
if username.lower() != 'joe':
print("imposter!")
continue
else:
print(f'Hello {username.capitalize()}')
for i in range(3):
password = input('Enter password: ')
if password == 'Water':
access = True
break
else:
print("3 strikes, you're out")
sys.exit()
print("Access granted")
You reset tries = 0 within the loop.
How would I put "if" or "else" in code like this?
user = input('Login: Username\n')
time.sleep(1)
password = input('Login: Password\n')
print('Welcome, %s.' % user)
I think this is what you want to do. But this is not a secure way of doing password requests.
user = input('Login: Username\n')
password = input('Login: Password\n')
users = {"You" : "1234", "Me" : "abcd"}
if user in users.keys():
if users[user] == password:
print("Welcome, {u}".format(u=user))
else:
print("Wrong password")
else:
print("This user does not exist")
Here is a simple version on how this should work but is not secure at all, but functions (almost) the same way as you requested (came up with this under 5 mins)
user = input('Login Username: ')
password = input('Login Password: ')
if user == ("Your username here"):
if password == ("Your password here"):
print("Welcome ", user)
Also you do not need "time.sleep()" as it only slows down your code
How do I go about stopping 'Access granted' being printed when password is correctly input? Access granted get printed three times when 'swordfish' is entered
print ('The Database is password protected') # Says the Data base is password protected
print ('please enter password') #say please enter password
password = ('swordfish')
swordfish = 3
password = input()
if password == 'swordfish':
print ('Access granted.')
else:
if password != ('swordfish'):
print ('wrong password.')
print ('two attempts remain')
else:
password = input()
if password == 'swordfish':
print ('Access granted.')
else:
password = input()
if password == 'swordfish':
print ('Access granted.')
else:
print ('wrong password.')
print ('one attempt remain')
password = input()
if password == 'swordfish':
if password != ('swordfish'):
print ('You have been blocked from the database')
If you want to stop it from being printed and clean up your code then use a loop:
Edit: This is a perfect time to use the for-else block of code. In this example, the else clause will only run when the full for-loop has been exhausted i.e it wont run 'You have been blocked from the database' in the event that the correct password was entered (because then the break statement has executed)
password = 'swordfish'
print('The Database is password protected')
for attempts in range(2, -1, -1):
if input('Please enter password') == password:
print('Access granted.')
break
else:
print('Wrong password.')
print('%s attempts remain' % attempts)
else:
print('You have been blocked from the database')
print ('The Database is password protected')
print ('please enter password')
password = "swordfish"
for i in range(3):
attempt = input("Enter the password: ")
if attempt == password:
print("Access Granted")
break
else:
print("Wrong password")
print(2 - i, "attempt(s) reamin")
if i == 2:
print("You have been blocked from the database")
You could try a for-loop :)
for e in range(3):
a=input()
if a=="swordfish":
print("Access Granted")
break
else:
print("Wrong Password. You have "+str(3-(e+1))+" attempts left")
Just started python and racking my brains on this but can't seem to get it right.
print('Enter correct username and password combo to continue')
count=0
password=Hytu76E
username=bank_admin
while password!='Hytu76E' and username!='bank_admin' and count<4:
username=input('Enter username: ') and password=input('Enter password: ')
if password=='Hytu76E' and username=='bank_admin':
print('Access granted')
else:
print('Access denied. Try again.')
count-=1
syntax error, can't assign to operator on line 6 username=input.
Fixed the code to achieve what you are trying to do:
print('Enter correct username and password combo to continue')
count=0
while count < 3:
username = input('Enter username: ')
password = input('Enter password: ')
if password=='Hytu76E' and username=='bank_admin':
print('Access granted')
break
else:
print('Access denied. Try again.')
count += 1
Changes that have been made:
Removed the definition of username and password since it is redundant and can be omitted
Changed the while statement to count 3 iterations of count
Validation of the credentials only in the if statement and not in the while
Changed the decreasing of count to increasing (from count -= to count +=)
break the loop when the right credentials are entered
here try this (I try to change your code as less as possible so that you can identify the same logic yourself)
print('Enter correct username and password combo to continue')
count = 0
# "" or '' because you are assigning a value string into it
password = ""
username = ""
# looping will continue when wrong input for three times and ask again...
while password!='Hytu76E' and username!='bank_admin' and count < 3:
# you are collecting user input from CLI separately (you can not assign and operator to such operation as per your code ;)
username = input("Enter username: ")
password = input("Enter password: ")
if password=='Hytu76E' and username=='bank_admin':
# if match, grand and break
print('Access granted')
break
else:
print('Access denied. Try again.')
count+=1 # as per gbse, in the comments, you will need the + to count up
issues in your code:
# you are assigning string value, what for? this would make the loop hit positive the first time
password=Hytu76E # string assignment error in syntax, anyway
username=bank_admin # string assignment error in syntax, anyway
# you can not assigning and operator in the input because of no if condition in this line, also you should compare the values of the input
username=input('Enter username: ') and password=input('Enter password: ')
# if code is ok, then move outside the loop in the case when the user enters the first time good answers
if password=='Hytu76E' and username=='bank_admin':
print('Access granted')
else:
print('Access denied. Try again.')
# you are decremented the counter which would never leave teh loop at 4, you should add one on each iteration so count+=1 (count = count + 1)
count-=1
I think this is what you're looking for: Accept username and password and verify it against a particular one mentioned in the code, with a max try limit of 3
print('Enter correct username and password combo to continue')
count=1
while count<4:
username=input('Enter username: ')
password=input('Enter password: ')
if password=='Hytu76E' and username=='bank_admin':
print('Access granted')
count=5
else:
print('Access denied. Try again.')
count+=1
Firstly you can remove the initial definition you gave to password and username at the start as well as changing the while loop to become while count<4
So it would look like:
print('enter the correct username and password combo to continue')
count = 0
while count<4:
If we had kept it how it was previously it would be unnecessary and clutter your program more.
To fix your syntax error you need to remove the and placed inbetween username and password, so the middle will look more like this:
username = input('Enter username: ')
password = input('Enter password: ')
Then at the end you want to change count-=1 to count+=1, because if it takes one away every time it will never hit 4 and your loop will be infinite, which is not what you are trying to achieve.
Here is the entire fix:
print('Enter correct username and password combo to continue')
count=0
while count<4:
username=input('Enter username: ')
password=input('Enter password: ')
if password=='Hytu76E' and username=='bank_admin':
print('Access granted')
count=5
else:
print('Access denied. Try again.')
count+=1
Here is a list of changes I have made:
Removed the password and username definition in lines 3 and 4
Changed your while loop to become while<4
Removed the and inbetween username=input and password=input
Added count=5 after if statement so that the loop ends
You can use for loop:
#!/usr/bin/python3
for _ in range(3):
usr = input("Enter username: ")
psw = input("Enter password: ")
if usr == "bank_admin" and psw == "Hytu76E":
print("Access Granted!")
break
else:
print("Access Denied!")
print("Try Again!")
else:
print("No more attemps!")
I mean the idea behind this:
password=Hytu76E
username=bank_admin
while password!='Hytu76E' and username!='bank_admin' and count<4:
seems to be that you get into the loop. But why so complicated? You could also just start a loop that runs 3 times:
for i in range(3):
[do something]
And in terms of what the [do something] could be. Well first of all you need to check the user input:
username=input('Enter username: ') and password=input('Enter password: ')
So the idea is good but what you do is you request 2 inputs in the same statement and then COMPARE them with an AND statement. So no wonder the interpreter gets confused here. What you probably wanted to do instead is just write them on two separate lines:
username=input('Enter username: ')
password=input('Enter password: ')
if you really want to/need to do it on one line you could use:
username, password = input(), input()
Then you'd need to insert "[Your Name][ENTER]" "[Your Password][ENTER]", but although it would work I'd not recommend it as it's probably nothing but confusing to both you and the potential user.
Next up you'd need your condition as it's no longer part of the loop:
if username == [username] and password == [password]:
print('Access granted')
break
else:
print('Access denied. Try again.')
Here break skips the rest of the loop once the condition is met. If you want to be fancy you can also add a condition to check whether it's the last try:
else:
if i < 2:
print('Access denied. Try again.')
else:
print('Access denied. IP was added to the log')
Not sure you want this, but you can split the inputs of Username and Password:
count = 1
while count < 4:
username = input('Enter username: ')
if username == 'Sdfh123':
print('OK! Enter your Password:')
count = 5
else:
print('Access DENIED. Try Again:')
count+=1
count = 1
while count < 4:
password = input('Enter Password: ')
if password == 'swordfish':
print('ACCESS GRANTED!')
count = 5
else:
print('Access DENIED. Try Again:')
count+=1
user = 'Mike'
pw = '1234'
print('Please enter your username and password: ')
username = ""
password = ""
count = 0
while username != user and password != pw and count < 3:
username = input('Username: ')
password = input('password: ')
if username == user and password == pw:
print('Welcome',username)
else:
print('Denied, Please try again') count = count + 1
I'm trying to make a small program which can tell whether or not the correct password has been entered and keep asking for the correct password until it is entered. The correct password is 'Secret'.
I get as far as creating my while loop. It will ask for the password and ask to enter it again, but it will do this regardless of whether you enter the correct password first time round or not. Where am I going wrong? And how can I get it to break if the correct password is entered first time and how do I keep it asking for the password until it is entered correctly?
This is my code so far:
password = raw_input('What is the password? ')
correctPassword = 'Secret'
tryAgain = raw_input ('Enter password again ')
password
while password == False:
print 'Enter password again '
if password == correctPassword:
print 'You are in!'
break
Try the below code: -
password= raw_input('What is the password? ')
correctPassword= 'Secret'
while password != correctPassword:
password = raw_input ('Enter password again ')
print "Success"
This will execute the while loop until the password input in the while loop is not equal to the correct password.
Here is the right code.
correctPassword= 'Secret'
while True:
password= raw_input('What is the password? ')
if password == correctPassword:
print 'You are in!'
break
print 'Enter password again '
Here is my code
password = 'password'
Get_password = input("Enter the password: ")
while Get_password != password:
print("the password you entered is not correct, enter the correct password")
break
print("You are logged in!")