Search code examples
pythonpython-3.xconditional-statementsoperatorsboolean-expression

Certain conditions evaluate differently then expected in Python


Currently creating a piece that takes values a given value in an array and adds 32

My IDE (PyCharm) recommended that I remove a redundancy in my code by doing the following

if ascii_key[i] >= 65 and ascii_key[i] <= 90:
    ascii_key[i] = ascii_key[i] + 32

to

if 65 <= ascii_key[i] <= 90:
    ascii_key[i] = ascii_key[i] + 32

Both solutions work for me, but I'm curious as to why this arrangement of conditions breaks

if ascii_key[i] <= 65 >= 90:
    ascii_key[i] = ascii_key[i] + 32

I'd appreciate an explanation in pseudo-code if convenient, I'm still a bit novice


Solution

  • In the third code provided by you.

    ascii_key[i] <= 65 >= 90 this is always evaluated to False.

    ascii_key[i] <= 65 >= 90 is evaluated as ascii_key[i] <= 65 and 65 >= 90. 65>=90 is False.

    Byte-code evaluation of a<b<c.

    In [17]: dis.dis('a<b<c')
      1           0 LOAD_NAME                0 (a)
                  2 LOAD_NAME                1 (b)
                  4 DUP_TOP
                  6 ROT_THREE
                  8 COMPARE_OP               0 (<)
                 10 JUMP_IF_FALSE_OR_POP    18
                 12 LOAD_NAME                2 (c)
                 14 COMPARE_OP               0 (<)
                 16 RETURN_VALUE
            >>   18 ROT_TWO
                 20 POP_TOP
                 22 RETURN_VALUE
    

    Byte-code evaluation of a<b and b<c.

    In [18]: dis.dis('a<b and b<c')
      1           0 LOAD_NAME                0 (a)
                  2 LOAD_NAME                1 (b)
                  4 COMPARE_OP               0 (<)
                  6 JUMP_IF_FALSE_OR_POP    14
                  8 LOAD_NAME                1 (b)
                 10 LOAD_NAME                2 (c)
                 12 COMPARE_OP               0 (<)
            >>   14 RETURN_VALUE
    

    You can observe observe a<b<c is equivalent to a<b and b<c.