[Tutor] (no subject)

Magnus Lycka magnus@thinkware.se
Thu, 08 Aug 2002 16:28:02 +0200


At 00:27 2002-08-08 +0100, steven bruce wrote:
>Hi everyone again,
>
>I have sorted it now thanks to all your help and just to give you all a=20
>good laugh I thought id show you how not to do it.

You are not so far off...but details make a big difference
in programming. A few tips:

If you ask for a password, you don't want it echoed to the
screen in case someone looks over your shoulder. Use the
"getpass" module as below.

Secondly, an authentication routine is suitable for breaking
out from the general program flow, so make it a function that
returns different values for success and failure. (From version
2.3 (I think) the values true and false will be included in the
Python language, but for now, 1 and 0 will do.)

I placed your code indented in a function definition, and
call the function below.

For your 'count < max' to make sense you need to make a loop.
You do that with the "while" statement. (I don't understand
what 'password !=3D "steve":' was supposed to mean.)

BTW, you should avoid redundant information such as in:
         if password =3D=3D "steve":
                 count =3D 4
         elif password <> "steve":
                 count =3D count + 1
That is exactly the same thing as:
         if password =3D=3D "steve":
                 count =3D 4
         else:
                 count =3D count + 1
Apart from being a bit faster, less typing and easier to read,
the second version is less likely to cause problems when you
change the password from steve to something else. One rainy
day you will change the password in one place, but not in the
other, like this:
         if password =3D=3D "batman":
                 count =3D 4
         elif password <> "steve":
                 count =3D count + 1
In this case, count won't be incremented if the user persists in
trying to log in as steve. So, remember that it's a virtue to
be a lazy programmer! Type less!

def authenticate():
     count =3D 0
     max =3D 4
     while count < max:
         count =3D count + 1
         password =3D getpass.getpass("What is your secret password? ")
         if password =3D=3D "steve":
             return 1
     print "Sorry, only", max, "tries allowed!"
     return 0

if authenticate():
     print "Access OK"
else:
     print "Access denied"

Now it might be a good time to introduce code to read the secret password
from a file, and to allow for several users/passwords. Or perhaps to put
the code to some real use...


Good luck,


Magnus


--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se