views:

134

answers:

3

I'm a newbie and i need to know how to modify a password guessing program to keep track of how many times the user has entered the password wrong. If it has been entered more than 3 times then it should print " This seems to be complicated" and the program should be ended. The password guessing program is

password="abcd"
while password != "password"
       password = raw_input("Password:")
print "Welcome in"

How should i modify this program to get one as i mentioned earlier? Could anyone guide me? Thank you.

A: 

Initialise a count variable to zero and increment it within your loop. You can then use the count within your while loop condition and then after the loop to determine how many tries it took and to print a message.

ar
Thanks ar for your reply. Modified the program like thispassword="abcd"current_count=0while password!="password": password=raw_input("Guess Password:") current_count=current_count+1 if current_count>2: print "That must have been complicated." print "WELCOME IN"once i run the program after 3 wrong tries it still displays the message "Guess password?" and once i give the right password it gives the message " That must have been complicated" and then only displays "Welcome in". Is there any way that i could terminate "Guess Password?" after 3 wrong tries?
Satish
@Satish. Here's a hint: don't post code in a comment. You might want to add to your question.
S.Lott
+1  A: 
import sys
counter = 0;
while counter < 3:
    counter += 1
    password = raw_input("Password:")
    if password == "password":
        print "Welcome in"
        break
else:
    print "This seems to be complicated"
    sys.exit(0)
Tendayi Mawushe
Thanks Tendayi. But since i am a newbie, in the book i'm refering to has given this as an exercise, i haven't gone to the stage of "for in" command. So is there any other way by just using "if, while" commands to compile this?
Satish
Updated the answer to use a while loop instead.
Tendayi Mawushe
Thanks Tendayi. The else part doesn't seem to work in the code given above.The program exits only when i give the right password.
Satish
+2  A: 
for trial in range(3):
    if raw_input('Password:') == 'password':
        break
else:
    # didn't find password after 3 attempts
    sys.exit(10)
print 'Welcome in'
Paul Hankin
I think you may need to fix your indentation
inspectorG4dget
Thanks Paul. It was really useful.
Satish
@inspectorG4dget nope, the indentation is right -- the else is attached to the for.
Paul Hankin