Best way to do this?

Mel Wilson mwilson at the-wire.com
Tue Jan 27 14:45:13 EST 2004


In article <40106D38.3010302 at void.com>, sambo <sambo at void.com> wrote:
>
>>The "obscure" for/else can help:
>>
>>
>>def get_password (prompt):
>>    for i in (1, 2, 3):
>>        password = raw_input (prompt)
>>        if password == 'mypass':
>>            return True
>>        else:
>>            print "Try Again"
>>    else:
>>        print "Too Bad"
>>        return False
>>
>Obscure? at least it does something.

   Well, yeah, but I did put it in quotes.  It was some time
before I realized that else could go with for.  And a bit
longer before I got my head around what it did.

   In retrospect, I would say that for/else would have
looked its best in a code snippet, as presented by the
original poster.  "Cleaning up" the code into a function
meant that I could have ditched the "else" and just made the
next two statements the last in the function.  So:

    for i in (1, 2, 3):
        password = raw_input (prompt)
        if password == 'mypass':
            good_password = True
            break
        else:
            print "Try Again"
    else:
        print "Too Bad"
        good_password = False
...
    if good_password:
...


>What is the advantage of the following assignment ( a few messages up)
>
>attempts, password = 3, 'mypass'
>
>Reading difficulty - at least 3 (no relation, hehe)

   No particular advantage I can imagine.  When two
variables are fated to be together throughout the algorithm,
then you can help express this with tuple unpacking.  The
serious reason for tuple unpacking is to make sure that all
the value calculations are done before you try the
assignments:

        a, b = b, a

or
        try:
            v1, v2, v3 = f1(), f2(), f3()
        except some_exception:
...

which makes the assignments to the v's an all-or-nothing
operation.

        Regards.        Mel.



More information about the Python-list mailing list