Best way to do this?

Jeremy Yallop jeremy at jdyallop.freeserve.co.uk
Sat Jan 17 18:38:01 EST 2004


Wil Schultz wrote:
> One of the exercises asks for a program to ask for a password three 
> times. Surprisingly this took me much longer that it probably should 
> have so I am curious if the following is the easiest way this is done. 
> Thanks much!
> 
> *************************************************
> #!/usr/local/bin/python
> 
> count = 0
> password = "null"
> 
> while count < 3:
>          count = count + 1
>          password = raw_input("what's the pass: ")
>          if password == "mypass":
>                  print "Access Granted"
>                  count = 3
>          else:
>                  if count < 3:
>                          print "Try Again"
>                  else:
>                          print "Too Bad"
> *************************************************

I'd write it something like this:

    from getpass import getpass
    attempts, password = 3, 'mypass'
    
    for i in range(attempts):
	if i != 0:
            print 'Try again'
        if getpass("What's the pass: ") == password:
            print 'Access Granted'
            break
    else:
         print 'Too bad' 

Jeremy.



More information about the Python-list mailing list