[Tutor] Newbie question

ibraheem umaru-mohammed iumarumo@eidosnet.co.uk
Sat, 17 Aug 2002 21:59:26 +0100


[Billie wrote...]
-| Hello:
-| I'm doing an exercise in which you get three guesses before the program quits.
-| 
-| #Note that this must not be the password so that the
-| #while loop runs at least once.
-| password = "foobar"
-| count = 0 #intialize to zero
-| #note that !=means not equal

> Don't think the comment above is necessary, as the reader should/would
know "!=" is what it is.

-| while password != "unicorn":
-|     password = raw_input("Password:")
-|     count = count + 1  # add one each time round the loop
-|     print "You've entered the password %d times."%count
-|     if password != "unicorn" and count >= 3:
-|         print" You cannot enter!"
-|         break
-| if password == "unicorn":
-|     print "Welcome in"
-| 

> Although this works, it could be neater. Looking at your code, you
test password against unicorn three times. I think you could test
password against unicorn once, and test count against the maximum number
of incorrect passwords once. Here is an example,

			-- <snip> --
#!/usr/bin/python

password_attempts=0
max_incorrect_attempts=3

while password_attempts < max_incorrect_attempts:
  password = raw_input("Password: ")
  password_attempts+=1
  if password == "unicorn":
    print "Password accepted. Welcome in."
    break
  else:
    print "Incorrect password. Please try again."
else:
  print
  print "%d incorrect password attempts!" % max_incorrect_attempts
  print "You cannot enter!"

			-- <snip/> --
-| 
-| My question is "Isn't using the break here bad form?"  I don't know how 
-| to stop the program at 3 guesses unless the answer is "unicorn".  I need 
-| it to stop also if at 3 guesses the password is wrong.

> The code snippet above uses a break in a similar way, so there is
nothing wrong in terms of form. The break statement terminates the loop,
and also skips the else statement of the while loop. We use the else statement with
the while loop, so that when the condition is false (i.e
password_attempts < max_incorrect_attempts) the else statement is
executed, as the last step before termination of the loop. 

-| 
-| Help!
-| Billie

HTH			--ibs.

-- 
			ibraheem umaru-mohammed
			   www.micromuse.com
			         --0--