Triple operator behavior

I recently started using a ternary operator, but I came across a situation where I needed to use several ternary operators on the same line, but they did not seem to work as I expected.

Can someone please give an explanation of why this line gives a different result.

x = 1 if True else 2 + 3 if False else 4  # x = 1, I expected 5
x = (1 if True else 2) + (3 if False else 4)  # x = 5

If I add brackets, I get the expected result, but I do not understand that the brackets are changing.

And if I turned the addition, without parentheses, I get the correct value.

3 if False else 4 + 1 if True else 2  # x = 5

However, I get the wrong result if the second ternary operator is False:

3 if False else 4 + 1 if False else 2  # x = 5 # x = 2 ???

Is it because you shouldn't use multiple ternary operators on the same line or is this their other reason?

+4
source share
3 answers

:

x = (1) if (True) else ((2 + 3) if (False) else (4))

, x 1 2 + 3... .

:

(3) if (False) else ((4 + 1) if (True) else (2))

, 3 , False, 4 +...

(3) if (False) else ((4 + 1) if (False) else (2))

2, (4+1) ( False)

, if :

x = (1) if (True) else ((2 + 3) if (False) else (4))

if True:
    x = 1
else:
    if False:
        x = 2 + 3
    else:
        x = 4
+5

. , , - . ,

1 if True else 2 + 3 if False else 4

1 if True else ((2 + 3) if False else 4)

1.

+6
x = 1 if True else 2 + 3 if False else 4

x = (1) if (True) else (2 + 3 if False else 4)

( , .)

+4

Source: https://habr.com/ru/post/1695985/


All Articles