1 > 0 == True -> False

Jussi Piitulainen jpiitula at ling.helsinki.fi
Thu Jan 30 09:56:19 EST 2014


Roy Smith writes:

> In article <3dcdc95d-5e30-46d3-b558-afedf9723c7c at googlegroups.com>,
>  Thibault Langlois wrote:
> 
> > You are right. I should have given some context.  I am looking at
> > this from the perspective of the teacher that has to explain
> > idiosyncrasies of the language to inexperienced students.
> >
> > There are two aspects in this example. 

> > 1. the equivalence of True/False with integers 1/0 which have pro
> > and cons.
> > 2. the chaining rules of operators. I agree that it may make sense
> > in some cases like x > y > z but when operators are mixed it leads
> > to counter intuitive cases as the one I pointed out.
> > 
> > The recommendations to student are 1) do not assume True == 1 and
> > do not use operator chaining.
> 
> Better than that, do what I do.
> 
> 1) Assume that you don't have the full operator precedence table
> memorized and just parenthesize everything.
> 
> 2) In cases where the expression is so simple, you couldn't possibly
> be wrong, see rule #1.

There's nothing to parenthesize in x <= y < z = w, unless you mean
something rather weird that is not equivalent anyway (and may not be
compatible with avoiding assumptions like True == 1).

There's not much to remember: the comparison operators are a
semantically coherent class (as far as I can see) and have the same
precedence level somewhere between proper operators (let's call them
that) and and and or and if else[1]. Ok, I'm not quite sure how the
two branches of a conditional expression combine. Rather than find
out, use parentheses, yes:

   (x + 1) if c else x ==  x + (1 if c else 0) == x + bool(c)

I agree about using parentheses when in doubt, but there is some room
here for more education and less doubt. Python gets these right.

[1] Sorry...



More information about the Python-list mailing list