Skip to content

Commit cdcc71b

Browse files
anupyyasoob
authored andcommitted
Shorthand ternary. (yasoob#165)
* Shorthand ternary. * Update ternary_operators.rst * Update ternary_operators.rst * Update ternary_operators.rst * Update ternary_operators.rst
1 parent 0767511 commit cdcc71b

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

ternary_operators.rst

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,34 @@ first built, then an index is found. For the if-else ternary operator,
7070
it follows the normal if-else logic tree. Thus, if one case could
7171
raise an exception based on the condition, or if either case is a
7272
computation-heavy method, using tuples is best avoided.
73+
74+
75+
**ShortHand Ternary**
76+
77+
In python there is also the shorthand ternary tag which is a shorter version of the
78+
normal ternary operator you have seen above.
79+
80+
Syntax was introduced in Python 2.5 and can be used in python 2.5 or greater.
81+
82+
**Example**
83+
84+
.. code:: python
85+
86+
>>> True or "Some"
87+
True
88+
>>>
89+
>>> False or "Some"
90+
'Some'
91+
92+
The first statement (`True or "Some"`) will return `True` and the second statement (`False or "Some"`) will return `False`.
93+
94+
This is helpful in case where you quickly want to check for the output of a function and give a useful message if the output is empty:
95+
96+
.. code:: python
97+
98+
>>> func_output = None
99+
>>> msg = output or "No data returned"
100+
>>> print(msg)
101+
No data returned
102+
103+

0 commit comments

Comments
 (0)