Python one liner conditional -


can please explain code for?

shift, range = order < self.order , (1, (to, orig-1)) or (-1, (orig+1, to)) 

i know set shift , range depending on result of order < self.order

what don't know why there and , or statement there

from documentation of boolean expressions in python -

the expression x , y first evaluates x ; if x false, value returned; otherwise, y evaluated , resulting value returned.

the expression x or y first evaluates x; if x true, value returned; otherwise, y evaluated , resulting value returned.

so and / or expressions in python don't return true or false, instead -

  1. for and return last evaluated false value, or if values true , return last evaluated value.

  2. for or returns last evaluated true value, or if values false, returns last evaluated value.

so , in case if condition true , returns value of (1, (to, orig-1)) , otherwise returns value of (-1, (orig+1, to)) .

very simple examples show -

>>> 1 < 5 , 2 or 4 2 >>> 6 < 5 , 2 or 4 4 

also, though not directly applicable condition , in general case, condition -

cond , or b 

if cond true-like value , a has false-like value (like 0 or empty string/list/tuple, etc), return b . example -

>>> 1 < 5 , 0 or 2 2 

so, better use equivalent if..else ternary expression, example -

a if cond else b 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

how to prompt save As Box in Excel Interlop c# MVC 4 -

xslt 1.0 - How to access or retrieve mets content of an item from another item? -