[Tutor] Help with Guess the number script

eryksun eryksun at gmail.com
Sun Mar 9 01:25:21 CET 2014


On Sat, Mar 8, 2014 at 1:44 PM, Scott dunning <swdunning at cox.net> wrote:
>> if 1 > guess > 100:
>>
> OH!  I see what you're saying, ignore my last post.  Yes that looks
> cleaner.

Please read section 6.9 of the language reference, which defines
Python comparison expressions.

http://docs.python.org/3/reference/expressions#not-in

Here's the description of chained comparisons:

    Comparisons can be chained arbitrarily, e.g.,
    x < y <= z is equivalent to x < y and y <= z,
    except that y is evaluated only once (but in
    both cases z is not evaluated at all when
    x < y is found to be false).

    Formally, if a, b, c, ..., y, z are expressions
    and op1, op2, ..., opN are comparison operators,
    then a op1 b op2 c ... y opN z is equivalent to
    a op1 b and b op2 c and ... y opN z, except
    that each expression is evaluated at most once.

    Note that a op1 b op2 c doesn’t imply any kind
    of comparison between a and c, so that, e.g.,
    x < y > z is perfectly legal (though perhaps
    not pretty).

Thus `1 > guess > 100` is equivalent to `(guess < 1) and (guess >
100)`, which is always false. The correct chained comparison is `not
(1 <= guess <= 100)`.

Chaining is generally simpler, since all expressions are only
evaluated once. In this particular case, with a local variable
compared to constants, the chained form is slightly less efficient in
CPython. Though if it "looks cleaner" to you, certainly use it.
Readability takes precedence.


More information about the Tutor mailing list