if then elif
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:
n = n or 
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:
n = n is None and 
but if you're going to write that much, it's clearer to just go with
if n is None:
n = 
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
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:
Good table, except for higher presedence being further down in the
table which might be confusing pedagogically.
More information about the Python-list