[Tutor] Help with Guess the number script

eryksun eryksun at gmail.com
Sat Mar 8 15:29:36 CET 2014


On Sat, Mar 8, 2014 at 8:36 AM, Dave Angel <davea at davea.name> wrote:
>  Mark Lawrence <breamoreboy at yahoo.co.uk> Wrote in message:
>> On 08/03/2014 01:23, Scott W Dunning wrote:
>>
>>> def print_hints(secret, guess):
>>>      if guess < 1 or guess > 100:
>>
>> Only now do I feel that it's time to point out that the above line would
>> probably be written by an experienced Python programmer as:-
>>
>> if 1 > guess > 100:
>>
>
> With an appropriate 'not' or its equivalent,  of course.

i.e.

    guess < 1 or guess > 100

becomes

    not not (guess < 1 or guess > 100)

distribute over the disjunction

    not (not (guess < 1) and not (guess > 100))

logically negate the comparisons

    not (1 <= guess and guess <= 100)

finally, write the conjoined comparisons as a chained comparison:

    not (1 <= guess <= 100)

i.e., guess isn't in the closed interval [1, 100].

Anyway, you needn't go out of your way to rewrite the expression using
a chained comparison. The disjunctive expression is actually
implemented more efficiently by CPython's compiler, which you can
verify using the dis module to disassemble the bytecode.


More information about the Tutor mailing list