Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Doc/reference/expressions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2423,6 +2423,14 @@ The expression ``x if C else y`` first evaluates the condition, *C* rather than
If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
evaluated and its value is returned.

Conditional expressions group from right to left, so
``a if b else c if d else e`` means ``a if b else (c if d else e)``::

>>> 'spam' if True else 'eggs' if False else 'ham'
'spam'
>>> ('spam' if True else 'eggs') if False else 'ham'
'ham'
Comment on lines +2429 to +2432

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry to spoil the fun, but I don't think this example adds too much clarity: it feels like someone who doesn't already know what they're looking for would have trouble parsing it.
I'd prefer if the result had more of a connection to the conditions -- something like:

Suggested change
>>> 'spam' if True else 'eggs' if False else 'ham'
'spam'
>>> ('spam' if True else 'eggs') if False else 'ham'
'ham'
>>> n = 2
>>> 'positive' if n > 0 else 'negative' if n < 0 else 'zero'
'positive'

The switched-around version for such an example would probably be best omitted, though:

>>> ('bizarre' if n > 0 else 'negative') if n < 0 else 'non-negative'
'non-negative'

What do you think about using newlines to make the grouping in such a “ladder” clearer, like this?

>>> n = 2
>>> print('positive' if n > 0
...       else 'negative' if n < 0
...       else 'zero')
positive

(Personally I wish I'd seen this style sooner than I did; it helped me wrap my head around the priority.)


See :pep:`308` for more details about conditional expressions.


Expand Down
Loading