if then elif

thebjorn BjornSteinarFjeldPettersen at gmail.com
Thu Oct 11 01:24:51 CEST 2007


On Oct 10, 11:03 pm, Larry Bates <larry.ba... at websafe.com> wrote:
[...]
>
> Boolean problem:
>
> if cal or fat <= 0
>
> That may be the way you say it or "think" it but it won't work.
>
> 'cal or fat' is evaluated first.  Since they both have values this ALWAYS
> evaluates to 1 which is NEVER less than or equal to 0.

That's not correct. The comparison operator has higher presedence than
the or operator, so the above is interpreted as:

    if (cal) or (fat <= 0):

This idiom is occasionally useful in a couple of scenarios like e.g.
default and mutable function arguments:

    def foo(n=None):
        n = n or [42]

which is very common in Perl code, but causes problems if you pass it
an empty list. The better way of doing that in Python is probably:

    def foo(n=None):
        n = n is None and [42]

but if you're going to write that much, it's clearer to just go with
the canonical:

    def foo(n=None):
        if n is None:
            n = [42]

but I digress :-)

> You are looking for
>
> if (cal <= 0) or (fat <=0):
>
> (Note: Parenthesis not required, but it may help you understand precedence of
> evaluation.

That is a correct coding of the OP's intentions, although I would
think that the number of fat grams could indeed be zero for some
foods(?) so perhaps it would be more correct to say:

   if cal <= 0 or fat < 0:

>  Also read here:
>
> http://www.ibiblio.org/g2swap/byteofpython/read/operator-precedence.html
>
> -Larry

Good table, except for higher presedence being further down in the
table which might be confusing pedagogically.

-- bjorn




More information about the Python-list mailing list