How this expression 'a' = c = 'z' is evaluated in Python

4

I would like to know the order of evaluation of this expression in Python:

if 'a' <= c <= 'z': # c é uma variável de tipo 'chr'
    print("Ronal... D'oh!")
    
asked by anonymous 15.10.2014 / 00:48

1 answer

6

It is evaluated from left to right, as if it were:

'a' <= c and c <= 'z'

Furthermore, if c was an expression with side effects, type

a() <= c() <= z()

Calling c() would only occur once, still in left-to-right order, i.e. after a() and before z() . Font .

Another example:

>>> def a():
...   print('a')
...   return 'a'
...
>>> def z():
...   print('z')
...   return 'z'
...
>>> if a() <= 'c' <= z():
...   print('ok')
...
a
z
ok
>>> if a() <= 'A' <= z():
...   print('ok')
...
a
>>>

Note that since in the latter case the first comparison gave False , the second was not performed (short circuit).

    
15.10.2014 / 01:07