>> i = 1 >>> j = 1 >>> i += j > 0 and i >>> print(i) 2 What is th...">

The effect of "and" on assignment and addition

The line of code worked:

>>> i = 1
>>> j = 1
>>> i += j > 0 and i
>>> print(i)
 2

What is the main mechanic or system that does this job? It seems to be syntactic sugar for i = i + i if j > 0 else i, but it is a lot to unpack. Am I mistaken? Is there any other system in the game that I do not know?

Thanks!

EDIT:

For clarity:

>>> i = 3
>>> j = 2
>>> i += j > 1 and i
>>> i
6
+4
source share
2 answers

Let me break it:

In [1]: i = 1

In [2]: j = 1

Now look at the expression i += j > 0 and i:

In [3]: j > 0
Out[3]: True

Because jwhich is 1greater than 0, it is rated as True.

In [4]: j > 0 and i
Out[4]: 1

Since j > 0- True, the value of the Boolean expression is the value of the right side, namely 1.

, i += j > 0 and i i += i i = i + i:

In [5]: i += i

In [6]: i
Out[6]: 2

:

>>> i = 3
>>> j = 2
>>> i += j > 1 and i
>>> i
6

:

i += j > 1 and i
i = i + (j > 1 and i)
i = 3 + (2 > 1 and 3)
i = 3 + (True and 3)
i = 3 + 3
i = 6
+6

Python and or , , .

, and False, , True:

>>> 1 and 3
3

>>> 1 and 0
0

, or , , False:

>>> 2 or 3
2

>>> 0 or 2
2

>>> False or 0
0

, , and or True/False, , True False.

+4

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


All Articles