[Tutor] Python Programming exercise

Alan Gauld alan.gauld at btinternet.com
Wed Jul 1 10:02:29 CEST 2009


"Daniel Sato" <sato.photo at gmail.com> wrote

> I have been able to make the module quit after entering a password three
> times, but can't get it to quit right away after the correct one is

------------
password = "qwerty"
guess = "0"
count = 0
while count != 3:
   guess = raw_input("Enter your password: ")
   guess = str(guess)
   if guess != password
            print "Access Denied"
            count = count + 1
   else:
         print "Password Confirmed"

---------

There are a couple of ways to do it. The simplest is probably just to 
insert the break command
into the code after printing "Password Confirmed"

But you could alternatively change the test in the loop to be:

while count <= 3 and guess != password:
     as before...

Either way works.
Notice that I changed the loop test from !=3 to <=3
This is a little bit safer because if for some reason (a bug say)
the loop code changes the count beyond 3 your code will loop
forever...

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list