[Tutor] Help with Guess the number script

eryksun eryksun at gmail.com
Mon Mar 10 04:38:33 CET 2014


> On Mar 8, 2014, at 7:29 AM, eryksun <eryksun at gmail.com> wrote:
>>
>>    not not (guess < 1 or guess > 100)
>
> Why a not not?  Wouldn’t that just be saying do this because the
> second not is undoing the first?

In boolean algebra, `not (A or B)` is equivalent to `not A and not B`
(De Morgan's law). I double negated in order to mechanically apply
this rule, e.g.

    A or B
    = not not (A or B)
    = not (not A and not B)

>> 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.
>
> I’m not sure what you’re talking about in the above paragraph.

There's hardly any difference in how the interpreter evaluates the
code in a simple case like this, and it's actually slightly more
efficient (in CPython) without chaining. That said, chained
comparisons are more efficient when the expressions being compared are
computationally expensive, since each expression is only evaluated
once.

Regarding bytecode, CPython compiles Python source code to a sequence
of bytecode operations that get interpreted at runtime. It's an
implementation detail, but examining CPython bytecode is nonetheless
informative. Here's a basic example:

    >>> def f():
    ...     x = 'abc'

The function's code object contains the compiled code as a byte sting
in its co_code attribute:

    >>> f.__code__.co_code
    b'd\x01\x00}\x00\x00d\x00\x00S'

This assembled code isn't easy to read. Also, reading it requires
referencing other fields of the code object such as co_consts and
co_varnames. The dis module disassembles it to a form that's a bit
easier to read:

    >>> dis.dis(f)
      2           0 LOAD_CONST               1 ('abc')
                  3 STORE_FAST               0 (x)
                  6 LOAD_CONST               0 (None)
                  9 RETURN_VALUE

The documentation for the dis module includes a basic description of
each operation.

http://docs.python.org/3/library/dis


More information about the Tutor mailing list