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

Asked

Viewed 110 times

4

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

if 'a' <= c <= 'z': # c é uma variável de tipo `chr`
    print("Ronal... D'oh!")

1 answer

5


She’s rated left to right, like:

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

Moreover, if c was an expression with side effects, like

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

The call to c() only occur once, still in left-to-right order, i.e. after a() and before z(). Source.

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 as in the latter case the first comparison gave False, the second was not performed (short circuit).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.