Adding an if statement to a while loop - python

The premise of this code is to ask for a name, with a maximum of 3 attempts.
password = 'correct'
attempts = 3
password = input ('Guess the password: ')
while password != 'correct' and attempts >= 2:
input ('Try again: ')
attempts = attempts-1
if password == 'correct': #Where the problems begin
print ('Well done')
I can only enter the right password for the first attempt to return 'well done.' On the other two attempts, it will return as 'try again.' How can I get it to return well done, if entered on any of the attempts?

If you want to try again, then you need to capture that value.
password = input ('Try again: ')
Otherwise, the while loop never stops.
Additionally, Python has while-else, which could help you debug the issue
while password != 'correct' and attempts >= 2:
password = input ('Try again: ')
attempts = attempts-1
else:
print('while loop done')
if password == 'correct': #Where the problems begin
print ('Well done')
Or
attempts = 3
password = input('Enter pass: ')
while attempts > 0:
if password == 'correct':
break
password = input ('Try again: ')
attempts = attempts-1
if attempts > 0 and password == 'correct':
print ('Well done')

attempts = 3
while attempts > 1:
password = input("Guess password")
if password == "correct" and attempts > 2:
print("Well done")
break
else:
print("try again")
attempts = attempts - 1

This is a fun way to do it, instead of using a counter, you can create a list with three elements and the while test makes sure there are still elements left:
password,wrong,right = 'nice',['Wrong']*3,['you got it!']
while len(wrong)>0 and len(right)>0:
right.pop() if input('guess:')==password else wrong.pop()

Related

im trying to make a age and name approval. When they have 0 chances they cant continue. My problem is when they get 0 they can still continue

password = "12345"
for i in range(4):
pwd = input("ENTER YOUR PASSWORD : ")
j = 3
if(pwd == password):
print("WELCOME!")
break
else:
print("Not Valid, try again and chances left are",j-i)
continue
If you want to continue even if it reaches 0 chance. Instead of using for loop use while loop instead. So until the requirements meet, it's don't stop.
password = "12345"
while True:
pwd = input("ENTER YOUR PASSWORD : ")
j = 3
if(pwd == password):
print("WELCOME!")
break
else:
print("Not Valid, try again")
continue
with nested if to restart every time it reach zero
password = "12345"
chances = 4
while True:
pwd = input("ENTER YOUR PASSWORD : ")
j = 3
if(pwd == password):
print("WELCOME!")
break
else:
print("Not Valid, try again")
chances -= 1
if(chances <= -1):
print("Your chance depleted pls restart again")
#restart chance
chances += 4
continue
output

Trouble looping back to certain point and quitting program on 3 wrong guesses

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.

The != statement in the while loop is returning True even when it shouldn't - Python

In the password function, I am trying to make the user enter a password and if he/she inputs the wrong password, then give them another chance to write the correct password or just simply quit.
The problem which I am facing is if I enter the wrong password, and then if i use TRY AGAIN, then even if I write the correct password(i.e, 1234), it still says INCORRECT PASSWORD!
To check what was wrong, I used print(answer, type(answer)) and print(passwd, type(passwd)) to see if they were actually the exact same or not (which they were btw). I also used print(answer != passwd) to see if this was causing the issue and it was. It is returning True even after both answer and passwd are equal. Please suggest what I should do.
passwd = '1234'
def password():
global passwd
answer = input("ENTER THE PASSWORD:\t")
print(answer, type(answer))
print(passwd, type(passwd))
while answer != passwd:
print(answer != passwd)
print('INCORRECT PASSWORD!')
print("1. TRY AGAIN.\n2. QUIT")
ans = input("Answer(1/2):\t")
while ans not in ['1', '2']:
print("Incorrect input.")
ans = input("Answer(1/2):\t")
if ans == '1':
password()
elif ans == '2':
print("Bye!")
quit()
password()
This does not mean "go back to the start of the function". It means "call the function again, as a completely new action; let it use its own completely separate set of local variables; figure out what is returned; and then continue from this point after it returns".
In other words: it means the exact same thing that it would mean if you called any other function.
When the new function call happens, it prompts for input again and you give it matching input. That means the while loop does not run, and the end of the function is reached - for that call.
Then it returns back to where it was in the old function call (just like it would if any other function had been called), with no effect on the local answer. So now answer != passwd because answer != passwd before, and neither value changed. passwd is global, but answer is local - and the local value is local to this call of the function.
You should try to rethink your logic, draw a flowchart, and re-write it without the recursive call. Make sure you understand how break and continue work, as you may find them useful.
passwd = '1234'
# I added answer = None for the first function call
answer = None
def password():
global passwd
# The global answer ensures I use whatever the latest value of answer is(defined by the return statement at teh end of function)
global answer
answer = input("ENTER THE PASSWORD:\t")
print(answer, type(answer))
print(passwd, type(passwd))
while answer != passwd:
print(answer != passwd)
print('INCORRECT PASSWORD!')
print("1. TRY AGAIN.\n2. QUIT")
ans = input("Answer(1/2):\t")
while ans not in ['1', '2']:
print("Incorrect input.")
ans = input("Answer(1/2):\t")
if ans == '1':
password()
elif ans == '2':
print("Bye!")
quit()
# This would return the answer and change the global variable
return answer
password()
Personnaly speaking, your main problem was the order of using while loops. I have managed to solve your problem with the password function by editing your code and changing the order of while loops and some other stuff:
passwd = '1234'
def password():
global passwd
while True:
answer = input("ENTER THE PASSWORD:\t")
if answer != passwd:
wrongAnswer = input("1. TRY AGAIN.\n2. QUIT\nAnswer(1/2):\t")
while wrongAnswer != "1" and wrongAnswer != "2":
print("Incorrect input.")
wrongAnswer = input("Answer(1/2):\t")
if wrongAnswer == "2":
print("Bye!")
break
else:
print("Password is correct! Goodby")
break
Example output
ENTER THE PASSWORD: 8765
1. TRY AGAIN.
2. QUIT
Answer(1/2): 1
ENTER THE PASSWORD: 8765
1. TRY AGAIN.
2. QUIT
Answer(1/2): 1
ENTER THE PASSWORD: 1234
Password is correct! Goodby
You have to include an else statement or answer == passwd
passwd = '1234'
def password():
global passwd
answer = input("ENTER THE PASSWORD:\t")
print(answer, type(answer))
print(passwd, type(passwd))
while answer != passwd:
print(answer != passwd)
print('INCORRECT PASSWORD!')
print("1. TRY AGAIN.\n2. QUIT")
ans = input("Answer(1/2):\t")
while ans not in ['1', '2']:
print("Incorrect input.")
ans = input("Answer(1/2):\t")
if ans == '1':
password()
elif ans == '2':
print("Bye!")
quit()
else:
print('correct')

Python username and password with 3 attempts

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

How do i fix my while loop

I am writing a program that asks the user to enter a password. If the password matches the constant I've set it prints out a "successfully logged in message". However if the password is incorrect, it gives the number of guesses left and asks the user to try again. The program should end after 3 incorrect guesses but it keeps on asking even after 3 attempts have been used. I think the problem is in my while loop but I am unsure.
Code:
def main():
PASSWORD = "apple"
ALLOWED = 3
password = input("Enter the password: ")
while password != PASSWORD :
ALLOWED = ALLOWED - 1
print("Wrong. You have", ALLOWED, "guesses left")
if ALLOWED == 0:
print("You have been locked out")
password = input("Enter again ")
print("You have successfully logged into the system")
main()
Right now you never exit your while loop. To break out of it, use the break keyword.
To exit your program completely, you will need to import sys and sys.exit()
I suggest adding these to your if ALLOWED == 0 statement.
You need to use break to exit the loop, or add a secondary condition, otherwise it will keep going anyway until the password is correct.
So, either:
while (password != PASSWORD) and (ALLOWED > 0):
Or:
if ALLOWED == 0:
print("You have been locked out")
break
The condition password != PASSWORD is not enough to exit the loop (It will exit the loop only if you give the right password). Add the condition also in while (password != PASSWORD and ALLOWED > 0)
Change print("You have been locked out") to sys.exit("You have been locked out") (or otherwise exit the main). Remember to import sys to use sys.exit.
Your while loop requires a correct password to finish, and there is no other way to exit the loop. I suggest a break statement:
def main():
PASSWORD = "apple"
ALLOWED = 3
password = input("Enter the password: ")
while password != PASSWORD :
ALLOWED = ALLOWED - 1
print("Wrong. You have", ALLOWED, "guesses left")
if ALLOWED == 0:
print("You have been locked out")
break
password = input("Enter again ")
print("You have successfully logged into the system")
You may want to do more research if your program needs to be secure.
Managed to make it work but just making it check if ALLOWED == 0 and if it does print "you are locked out", and if ALLOWED <= 0 then it will not let you go any further.
def main():
PASSWORD = "apple"
ALLOWED = 3
password = input("Enter the password: ")
while password != PASSWORD or ALLOWED <= 0:
ALLOWED = ALLOWED - 1
if ALLOWED > 0: print("Wrong. You have", ALLOWED, "guesses left")
if ALLOWED == 0: print("You have been locked out")
if ALLOWED < 0:
print("You have been locked out")
password = input("Enter again ")
print("You have successfully logged into the system")
main()
also wrote a different version which seemed easier in my opinion
def main():
USERNAME = "admin"
PASSWORD = "root"
ATTEMPTS = 3
while ATTEMPTS >= 1:
print("You have",ATTEMPTS,"attempts left")
if ATTEMPTS == 0:
break
user = input("Please enter your username:")
password = input("Now enter your password:")
if user == USERNAME and password == PASSWORD:
print("\nYou have successfully logged into the system")
return
else:
print("\nThis user name or password does not exist\n")
ATTEMPTS -= 1
print("you have been locked out.")
main()

Categories

Resources