27 ms·
It's worth noting the second can't be used inline. I don't know the history, but it seems like that might be one of the reasons `x() if y()` isn't allowed in p
by closed 8y ago
It's worth noting the second can't be used inline.
I don't know the history, but it seems like that might be one of the reasons `x() if y()` isn't allowed in python. [x() if y()] if it existed, might carry an explicit else None.
On the other hand [x() and y()] does something different when y() is falsey.
- vram22 8y ago>I don't know the history, but it seems like that might be one of the reasons `x() if y()` isn't allowed in python. Maybe I misunderstood your context, but if not, conditional expressions do exist in Python: $ python Python 2.7.12 |Anaconda 4.2.0 (32-bit)| (default, Jun 29 2016, 11:42:13) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org >>> 1 if 1 == 1 else 2 1 >>> 2 if 1 == 1 else 2 2 >>> ^Z $ py -3 Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 1 if 1 == 1 else 2 1 >>> 2 if 1 == 1 else 2 2 >>> Using nested conditional expressions to classify characters: https://jugad2.blogspot.com/2017/04/using-nested-conditional-expressions-to.html https://jugad2.blogspot.com/2017/04/using-nested-conditional...
- vram22 8y agoSorry, the code shown in the two Python interpreter sessions above, is not a good example. To make the concept of conditional expressions more clear, this example is better: >>> from __future__ import print_function >>> for i in range(3, 5): ... print(i, "is", "odd" if i % 2 == 1 else "even") ... 3 is odd 4 is even which can be shortened to this: >>> for i in range(3, 5): ... print(i, "is", "odd" if i % 2 else "even") ... 3 is odd 4 is even Now print() is printing 3 values: i, "is", and either "odd" or "even" based on the boolean condition. That works in both Python 2 and 3.