Skip to content

Commit 08784b2

Browse files
lul-casmas192johnslavik
authored
gh-65058: Document the grouping of conditional expressions (GH-162167)
The "Evaluation order" section said that expressions are always evaluated from left to right, but a conditional expression evaluates its condition first. Add a sentence and an example showing that chained conditional expressions group from right to left. Co-authored-by: Sam Joshva <samjoshva@gmail.com> Co-authored-by: Bartosz Sławecki <bartosz@ilikepython.com>
1 parent 62b809d commit 08784b2

1 file changed

Lines changed: 9 additions & 0 deletions

File tree

‎Doc/reference/expressions.rst‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2426,6 +2426,15 @@ The expression ``x if C else y`` first evaluates the condition, *C* rather than
24262426
If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
24272427
evaluated and its value is returned.
24282428

2429+
Conditional expressions group from right to left, so
2430+
``a if b else c if d else e`` means ``a if b else (c if d else e)``::
2431+
2432+
>>> n = 2
2433+
>>> print('positive' if n > 0
2434+
... else 'negative' if n < 0
2435+
... else 'zero')
2436+
positive
2437+
24292438
See :pep:`308` for more details about conditional expressions.
24302439

24312440

0 commit comments

Comments
 (0)