0

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?

1
  • FYI, attempts = attempts-1 can be more simply written as attempts -= 1 Commented Feb 28, 2017 at 19:38

3 Answers 3

4

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. After assigning password to input ('Try again'), it worked perfectly.
0
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  

2 Comments

Please explain your answer!
attempts are 3, when 0 attempt remains,it gets out of the loop. When attempts remaining are 2, it should print well done,, But when attempts remaining are less than 2, then it should print try again and ask for the pasword again.
0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.